Skip to main content
Functions and classes exported by this package.

initLogger(cleoDir, config, projectHash)

Initialize the root logger. Call once at startup. Uses pino-roll for automatic size+daily rotation with built-in retention. No custom rotation code needed. Signature
(cleoDir: string, config: LoggerConfig, projectHash?: string | undefined) => Logger<never, boolean>
Parameters
NameTypeDescription
cleoDirstringAbsolute path to .cleo directory
configLoggerConfigLogging configuration from CleoConfig.logging
projectHash: string | undefinedStable project identity token bound to every log entry. Optional for backward compatibility; warns if absent.
Returns — The root pino logger instance

getLogger(subsystem)

Get a child logger bound to a subsystem name. Safe to call before initLogger — returns a stderr fallback logger so early startup code and tests never crash. Signature
(subsystem: string) => Logger<never, boolean>
Parameters
NameTypeDescription
subsystemstringLogical subsystem name (e.g. ‘audit’, ‘mcp’, ‘migration’)

getLogDir()

Get the current log directory path. Useful for read APIs that need to scan log files. Signature
() => string | null

closeLogger()

Flush and close the logger. Call during graceful shutdown. Returns a Promise that resolves once the pino transport worker thread has processed all pending writes. Callers that cannot await (e.g. sync shutdown handlers) may fire-and-forget safely — the underlying flush will still occur before the process exits. Signature
() => Promise<void>

getPlatformPaths()

Get OS-appropriate paths for CLEO’s global directories. Cached after first call. CLEO_HOME env var overrides the data path. The cache is automatically invalidated when CLEO_HOME changes, so test code can set process.env[‘CLEO_HOME’] without calling _resetPlatformPathsCache() manually. Signature
() => PlatformPaths

getSystemInfo()

Get a cached system information snapshot. Captured once and reused for the process lifetime. Useful for diagnostics, issue reports, and log enrichment. Signature
() => SystemInfo

_resetPlatformPathsCache()

Invalidate the path and system info caches. Use in tests after mutating CLEO_HOME env var. Signature
() => void

isProjectInitialized()

Check if a CLEO project is initialized at the given root. Checks for tasks.db. Signature
(projectRoot?: string | undefined) => boolean

getCleoHome()

Get the global CLEO home directory. Respects CLEO_HOME env var; otherwise uses the OS-appropriate data path via env-paths (XDG_DATA_HOME on Linux, Library/Application Support on macOS, %LOCALAPPDATA% on Windows). Signature
() => string

getCleoTemplatesDir()

Get the global CLEO templates directory. Signature
() => string

getCleoSchemasDir()

Get the global CLEO schemas directory. Signature
() => string

getCleoDocsDir()

Get the global CLEO docs directory. Signature
() => string

getCleoDir()

Get the project CLEO data directory (relative). Respects CLEO_DIR env var, defaults to “.cleo”. Signature
(cwd?: string | undefined) => string

getCleoDirAbsolute()

Get the absolute path to the project CLEO directory. Signature
(cwd?: string | undefined) => string

getProjectRoot()

Get the project root from the CLEO directory. Respects CLEO_ROOT env var, then derives from CLEO_DIR. If CLEO_DIR is “.cleo”, the project root is its parent. Signature
(cwd?: string | undefined) => string

resolveProjectPath()

Resolve a project-relative path to an absolute path. Signature
(relativePath: string, cwd?: string | undefined) => string

getTaskPath()

Deprecated: Use getAccessor() from ’./store/data-accessor.js’ instead. This function returns the database file path for legacy compatibility, but all task data access should go through the DataAccessor interface to ensure proper SQLite interaction. Example: // OLD (deprecated): const taskPath = getTaskPath(cwd); const data = await readJsonFile(taskPath); // NEW (correct): const accessor = await getAccessor(cwd); const data = await accessor.queryTasks();
Get the path to the project’s tasks.db file (SQLite database). Signature
(cwd?: string | undefined) => string

getConfigPath()

Get the path to the project’s config.json file. Signature
(cwd?: string | undefined) => string

getSessionsPath()

Get the path to the project’s sessions.json file. Signature
(cwd?: string | undefined) => string

getArchivePath()

Get the path to the project’s archive file. Signature
(cwd?: string | undefined) => string

getLogPath()

Get the path to the project’s log file. Canonical structured runtime log path (pino). T4644 Signature
(cwd?: string | undefined) => string

getBackupDir()

Get the backup directory for operational backups. Signature
(cwd?: string | undefined) => string

getGlobalConfigPath()

Get the global config file path. Signature
() => string

getAgentOutputsDir()

Get the agent outputs directory (relative path) from config or default. Config lookup priority: 1. config.agentOutputs.directory 2. config.research.outputDir (deprecated) 3. config.directories.agentOutputs (deprecated) 4. Default: ‘.cleo/agent-outputs’ T4700 Signature
(cwd?: string | undefined) => string

getAgentOutputsAbsolute()

Get the absolute path to the agent outputs directory. T4700 Signature
(cwd?: string | undefined) => string

getManifestPath()

Get the absolute path to the MANIFEST.jsonl file. Checks config.agentOutputs.manifestFile for custom filename, defaults to ‘MANIFEST.jsonl’. T4700 Signature
(cwd?: string | undefined) => string

getManifestArchivePath()

Get the absolute path to the MANIFEST.archive.jsonl file. T4700 Signature
(cwd?: string | undefined) => string

isAbsolutePath()

Check if a path is absolute (POSIX or Windows). Signature
(path: string) => boolean

getCleoLogDir()

Get the OS log directory for CLEO global logs. Linux: ~/.local/state/cleo | macOS: ~/Library/Logs/cleo | Windows: %LOCALAPPDATA%cleoLog Signature
() => string

getCleoCacheDir()

Get the OS cache directory for CLEO. Linux: ~/.cache/cleo | macOS: ~/Library/Caches/cleo | Windows: %LOCALAPPDATA%cleoCache Signature
() => string

getCleoTempDir()

Get the OS temp directory for CLEO ephemeral files. Signature
() => string

getCleoConfigDir()

Get the OS config directory for CLEO. Linux: ~/.config/cleo | macOS: ~/Library/Preferences/cleo | Windows: %APPDATA%cleoConfig Signature
() => string

getAgentsHome()

Get the global agents hub directory. Respects AGENTS_HOME env var, defaults to ~/.agents. Signature
() => string

getClaudeAgentsDir()

Deprecated: Use AdapterPathProvider.getAgentInstallDir() from the active adapter instead.
Get the Claude Code agents directory (~/.claude/agents by default). Signature
() => string

getClaudeMemDbPath()

Deprecated: Use AdapterPathProvider.getMemoryDbPath() from the active adapter instead. Respects CLAUDE_MEM_DB env var, defaults to ~/.claude-mem/claude-mem.db. This is a third-party tool path; homedir() is correct here (no env-paths standard).
Get the claude-mem SQLite database path. Signature
() => string

vacuumIntoBackup()

Create a VACUUM INTO snapshot of the SQLite database. Debounced by default (30s). Pass force: true to bypass debounce. WAL checkpoint is run before the snapshot for consistency. Oldest snapshots are rotated out when MAX_SNAPSHOTS is reached. Non-fatal: all errors are swallowed. Signature
(opts?: VacuumOptions) => Promise<void>

listSqliteBackups()

List existing SQLite backup snapshots, newest first. Signature
(cwd?: string | undefined) => { name: string; path: string; mtimeMs: number; }[]

getBrainDbPath()

Get the path to the brain.db SQLite database file. Signature
(cwd?: string | undefined) => string

resolveBrainMigrationsFolder()

Resolve the path to the drizzle-brain migrations folder. Works from both src/ (dev via tsx) and dist/ (compiled). Signature
() => string

isBrainVecLoaded()

Check whether the sqlite-vec extension is loaded for the current brain.db. Signature
() => boolean

getBrainDb()

Initialize the brain.db SQLite database (lazy, singleton). Creates the database file and tables if they don’t exist. Returns the drizzle ORM instance (async via sqlite-proxy). Uses a promise guard so concurrent callers wait for the same initialization to complete (migrations are async). Signature
(cwd?: string | undefined) => Promise<NodeSQLiteDatabase<typeof import("/mnt/projects/cleocode/packages/core/src/store/brain-schema", { with: { "resolution-mode": "import" } }), EmptyRelations>>

closeBrainDb()

Close the brain.db database connection and release resources. Signature
() => void

resetBrainDbState()

Reset brain.db singleton state without saving. Used during tests or when database file is recreated. Safe to call multiple times. Signature
() => void

getBrainNativeDb()

Get the underlying node:sqlite DatabaseSync instance for brain.db. Useful for direct PRAGMA calls or raw SQL operations. Returns null if the database hasn’t been initialized. Signature
() => DatabaseSync | null

getNexusDbPath()

Get the path to the nexus.db SQLite database file. nexus.db lives in the global ~/.cleo/ directory. Signature
() => string

resolveNexusMigrationsFolder()

Resolve the path to the drizzle-nexus migrations folder. Works from both src/ (dev via tsx) and dist/ (compiled). Signature
() => string

getNexusDb()

Initialize the nexus.db SQLite database (lazy, singleton). Creates the database file and tables if they don’t exist. Returns the drizzle ORM instance (async via sqlite-proxy). Uses a promise guard so concurrent callers wait for the same initialization to complete (migrations are async). Signature
() => Promise<NodeSQLiteDatabase<typeof import("/mnt/projects/cleocode/packages/core/src/store/nexus-schema", { with: { "resolution-mode": "import" } }), EmptyRelations>>

closeNexusDb()

Close the nexus.db database connection and release resources. Signature
() => void

resetNexusDbState()

Reset nexus.db singleton state without saving. Used during tests or when database file is recreated. Safe to call multiple times. Signature
() => void

getNexusNativeDb()

Get the underlying node:sqlite DatabaseSync instance for nexus.db. Useful for direct PRAGMA calls or raw SQL operations. Returns null if the database hasn’t been initialized. Signature
() => DatabaseSync | null

openNativeDatabase()

Open a node:sqlite DatabaseSync with CLEO standard pragmas. CRITICAL: WAL mode is verified, not just requested. If another process holds an EXCLUSIVE lock in DELETE mode, PRAGMA journal_mode=WAL silently returns ‘delete’. This caused data loss (T5173) when concurrent MCP servers opened the same database — writes were silently dropped under lock contention. Signature
(path: string, options?: { readonly?: boolean | undefined; timeout?: number | undefined; enableWal?: boolean | undefined; allowExtension?: boolean | undefined; } | undefined) => DatabaseSync

getDbPath()

Get the path to the SQLite database file. Signature
(cwd?: string | undefined) => string

getDb()

Initialize the SQLite database (lazy, singleton). Creates the database file and tables if they don’t exist. Returns the drizzle ORM instance (node-sqlite driver). Uses a promise guard so concurrent callers wait for the same initialization to complete (migrations are async). Signature
(cwd?: string | undefined) => Promise<NodeSQLiteDatabase<typeof import("/mnt/projects/cleocode/packages/core/src/store/tasks-schema", { with: { "resolution-mode": "import" } }), EmptyRelations>>

resolveMigrationsFolder()

Resolve the path to the drizzle migrations folder. Works from both src/ (dev via tsx) and dist/ (compiled). Signature
() => string

isSqliteBusy()

Check if an error is a SQLite BUSY error (database locked by another process). node:sqlite throws native Error with message containing the SQLite error code. T5185 Signature
(err: unknown) => boolean

closeDb()

Close the database connection and release resources. Signature
() => void

resetDbState()

Reset database singleton state without saving. Used during migrations when database file is deleted and recreated. Safe to call multiple times. Signature
() => void

getSchemaVersion()

Get the schema version from the database. Signature
(cwd?: string | undefined) => Promise<string | null>

dbExists()

Check if the database file exists. Signature
(cwd?: string | undefined) => boolean

getNativeDb()

Get the underlying node:sqlite DatabaseSync instance. Useful for direct PRAGMA calls or raw SQL operations. Returns null if the database hasn’t been initialized. Signature
() => DatabaseSync | null

getNativeTasksDb()

Get the underlying node:sqlite DatabaseSync instance for tasks.db. Alias for getNativeDb() — mirrors getBrainNativeDb() naming convention. Signature
() => DatabaseSync | null

closeAllDatabases()

Close ALL database singletons (tasks.db, brain.db, nexus.db). Must be called before deleting temp directories on Windows, where SQLite holds exclusive file handles on .db, .db-wal, and .db-shm files. Safe to call even if some databases were never opened. T5508 Signature
() => Promise<void>

safeParseJson()

Parse a JSON string, returning undefined on null/undefined input or parse error. Signature
<T>(str: string | null | undefined) => T | undefined

safeParseJsonArray()

Parse a JSON string expected to contain an array. Returns undefined for null/undefined input, empty arrays, or parse errors. Signature
<T = string>(str: string | null | undefined) => T[] | undefined

rowToTask()

Convert a database TaskRow to a domain Task object. Signature
(row: { sessionId: string | null; id: string; description: string | null; createdAt: string; updatedAt: string | null; status: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived"; ... 24 more ...; modifiedBy: string | null; }) => Task

taskToRow()

Convert a domain Task to a database row for insert/upsert. Signature
(task: Partial<Task> & { id: string; }) => { id: string; title: string; sessionId?: string | null | undefined; description?: string | null | undefined; createdAt?: string | undefined; ... 25 more ...; modifiedBy?: string | ... 1 more ... | undefined; }

archivedTaskToRow()

Convert a domain Task to a row suitable for archived tasks. Signature
(task: Task) => { id: string; title: string; sessionId?: string | null | undefined; description?: string | null | undefined; createdAt?: string | undefined; updatedAt?: string | null | undefined; ... 24 more ...; modifiedBy?: string | ... 1 more ... | undefined; }

rowToSession()

Convert a SessionRow to a domain Session. Signature
(row: { gradeMode: number | null; id: string; name: string; status: "active" | "ended" | "orphaned" | "suspended"; agent: string | null; notesJson: string | null; scopeJson: string; currentTask: string | null; ... 14 more ...; resumeCount: number | null; }) => Session

getErrorDefinition()

Look up an error definition by exit code. Signature
(code: number) => ErrorDefinition | undefined

getErrorDefinitionByLafsCode()

Look up an error definition by LAFS string code. Signature
(lafsCode: string) => ErrorDefinition | undefined

getAllErrorDefinitions()

Get all error definitions as an array. Signature
() => ErrorDefinition[]

CleoError

Structured error class for CLEO operations. Carries an exit code, human-readable message, and optional fix suggestions. Produces LAFS-conformant error shapes via toLAFSError() and RFC 9457 Problem Details via toProblemDetails(). Signature
typeof CleoError
Methods

toLAFSError()

Produce a LAFS-conformant error object. T4655
() => LAFSError

toProblemDetails()

Produce an RFC 9457 Problem Details object. T5240
() => ProblemDetails

toJSON()

Structured JSON representation for LAFS output (backward compatible).
() => Record<string, unknown>

getHttpStatus()

Derive HTTP status from exit code range. Used as fallback when catalog lookup misses.
() => number

upsertTask()

Upsert a single task row into the tasks table. Handles both active task upsert and archived task upsert via optional archiveFields. Defensively nulls out parentId if it references a non-existent task, preventing orphaned FK violations from blocking bulk operations (T5034). Signature
(db: DrizzleDb, row: { id: string; title: string; sessionId?: string | null | undefined; description?: string | null | undefined; createdAt?: string | undefined; updatedAt?: string | null | undefined; ... 24 more ...; modifiedBy?: string | ... 1 more ... | undefined; }, archiveFields?: ArchiveFields | undefined) => ...

upsertSession()

Upsert a single session row into the sessions table. Signature
(db: DrizzleDb, session: Session) => Promise<void>

updateDependencies()

Update dependencies for a task: delete existing, then re-insert. Optionally filters by a set of valid IDs. Signature
(db: DrizzleDb, taskId: string, depends: string[], validIds?: Set<string> | undefined) => Promise<void>

batchUpdateDependencies()

Batch-update dependencies for multiple tasks in two bulk SQL operations. Replaces per-task updateDependencies() loops with: 1. Single DELETE for all task IDs 2. Single INSERT for all dependency rows Callers are responsible for wrapping this in a transaction if needed. Signature
(db: DrizzleDb, tasks: { taskId: string; deps: string[]; }[], validIds?: Set<string> | undefined) => Promise<void>

loadDependenciesForTasks()

Batch-load dependencies for a list of tasks and apply them in-place. Uses inArray for efficient querying. Optionally filters by a set of valid IDs. Signature
(db: DrizzleDb, tasks: Task[], validationIds?: Set<string> | undefined) => Promise<void>

loadRelationsForTasks()

Batch-load relations for a list of tasks and apply them in-place. Mirrors loadDependenciesForTasks pattern for task_relations table (T5168). Signature
(db: DrizzleDb, tasks: Task[]) => Promise<void>

setMetaValue()

Write a JSON blob to the schema_meta table by key. Signature
(cwd: string | undefined, key: string, value: unknown) => Promise<void>

createSqliteDataAccessor(cwd)

Create a SQLite-backed DataAccessor. Opens (or creates) the SQLite database at .cleo/tasks.db and returns a DataAccessor that materializes/dematerializes whole-file structures from the relational tables. Signature
(cwd?: string | undefined) => Promise<DataAccessor>
Parameters
NameTypeDescription
cwd: string | undefinedWorking directory for path resolution (defaults to process.cwd())

atomicWrite()

Write data to a file atomically. Creates parent directories if they don’t exist. Uses write-file-atomic for crash-safe writes (temp file - rename). Signature
(filePath: string, data: string, options?: { mode?: number | undefined; encoding?: BufferEncoding | undefined; } | undefined) => Promise<void>

safeReadFile()

Read a file and return its contents. Returns null if the file does not exist. Signature
(filePath: string) => Promise<string | null>

atomicWriteJson()

Write JSON data atomically with consistent formatting. Signature
(filePath: string, data: unknown, options?: { indent?: number | undefined; } | undefined) => Promise<void>

atomicDatabaseMigration(dbPath, tempPath, validateFn)

Perform atomic database migration using rename operations. Pattern: 1. Write new database to temp file (tasks.db.new) 2. Validate temp database integrity 3. Rename existing tasks.db → tasks.db.backup 4. Rename temp → tasks.db (atomic) 5. Only delete backup on success Signature
(dbPath: string, tempPath: string, validateFn: (path: string) => Promise<boolean>) => Promise<AtomicMigrationResult>
Parameters
NameTypeDescription
dbPathstringPath to the database file (e.g., tasks.db)
tempPathstringPath to temporary database (e.g., tasks.db.new)
validateFn(path: stringAsync function to validate the temp database
Returns — Result with paths and success status

restoreDatabaseFromBackup(dbPath, backupPath)

Restore database from backup after failed migration. Signature
(dbPath: string, backupPath: string) => Promise<boolean>
Parameters
NameTypeDescription
dbPathstringPath to the database file
backupPathstringPath to the backup file
Returns — true if restore succeeded

cleanupMigrationArtifacts(backupPath)

Clean up migration artifacts after successful migration. Signature
(backupPath: string) => Promise<boolean>
Parameters
NameTypeDescription
backupPathstringPath to backup file to delete
Returns — true if cleanup succeeded

validateSqliteDatabase(dbPath)

Validate SQLite database integrity by attempting to open it. Signature
(dbPath: string) => Promise<boolean>
Parameters
NameTypeDescription
dbPathstringPath to database file
Returns — true if database is valid

createBackup()

Create a numbered backup of a file. Rotates existing backups (file.1 - file.2, etc.) and removes excess. Signature
(filePath: string, backupDir: string, maxBackups?: number) => Promise<string>

listBackups()

List existing backups for a file, sorted by number (newest first). Signature
(fileName: string, backupDir: string) => Promise<string[]>

restoreFromBackup()

Restore a file from its most recent backup. Returns the path of the backup that was restored. Signature
(fileName: string, backupDir: string, targetPath: string) => Promise<string>

acquireLock()

Acquire an exclusive lock on a file. Returns a release function that must be called when done. Signature
(filePath: string, options?: { stale?: number | undefined; retries?: number | undefined; } | undefined) => Promise<ReleaseFn>

isLocked()

Check if a file is currently locked. Signature
(filePath: string) => Promise<boolean>

withLock()

Execute a function while holding an exclusive lock on a file. The lock is automatically released when the function completes (or throws). Signature
<T>(filePath: string, fn: () => Promise<T>, options?: { stale?: number | undefined; retries?: number | undefined; } | undefined) => Promise<T>

isProviderHookEvent()

Type guard for CAAMP/provider-discoverable hook events. Signature
(event: HookEvent) => event is HookEvent

isInternalHookEvent()

Type guard for CLEO-local coordination hook events. Signature
(event: HookEvent) => event is "onWorkAvailable" | "onAgentSpawn" | "onAgentComplete" | "onCascadeStart" | "onPatrol"

HookRegistry

Central registry for hook handlers. Manages registration, priority-based ordering, and async dispatch of hook handlers. Provides best-effort execution where errors in one handler do not block others. Signature
typeof HookRegistry
Methods

register()

Register a hook handler for a specific event. Handlers are sorted by priority (highest first) and executed in parallel when the event is dispatched.
<T extends HookPayload>(registration: HookRegistration<T>) => () => void

dispatch()

Dispatch an event to all registered handlers. Executes handlers in parallel using Promise.allSettled for best-effort execution. Errors in individual handlers are logged but do not block other handlers or propagate to the caller.
<T extends HookPayload>(event: HookEvent, projectRoot: string, payload: T) => Promise<void>

isEnabled()

Check if a specific event is currently enabled. Both the global enabled flag and the per-event flag must be true.
(event: HookEvent) => boolean

setConfig()

Update the hook system configuration. Merges the provided config with the existing config.
(config: Partial<HookConfig>) => void

getConfig()

Get the current hook configuration.
() => HookConfig

listHandlers()

List all registered handlers for a specific event. Returns handlers in priority order (highest first).
(event: HookEvent) => HookRegistration<HookPayload>[]

readJson()

Read and parse a JSON file. Returns null if the file does not exist. Signature
<T = unknown>(filePath: string) => Promise<T | null>

readJsonRequired()

Read a JSON file, throwing if it doesn’t exist. Signature
<T = unknown>(filePath: string) => Promise<T>

computeChecksum()

Compute a truncated SHA-256 checksum of a value. Used for integrity verification (matches Bash CLI’s 16-char hex format). Signature
(data: unknown) => string

saveJson()

Save JSON data with optional locking, backup, and validation. Follows the CLEO atomic write pattern: 1. Acquire lock 2. Validate data 3. Create backup of existing file 4. Atomic write (temp file - rename) 5. Release lock Signature
(filePath: string, data: unknown, options?: SaveJsonOptions | undefined) => Promise<void>

appendJsonl()

Append a line to a JSONL file atomically. Used for manifest entries and audit logs. Signature
(filePath: string, entry: unknown) => Promise<void>

readLogEntries()

Read log entries from a hybrid JSON/JSONL file. Handles three formats: 1. Pure JSON: \{ "entries": [...] \} (legacy bash format) 2. Pure JSONL: one JSON object per line (new TS format) 3. Hybrid: JSON object followed by JSONL lines (migration state) Returns a flat array of all entries found. T4622 Signature
(filePath: string) => Promise<Record<string, unknown>[]>

makeCleoGitEnv()

Build environment variables that point git at the isolated .cleo/.git repo. T4872 Signature
(cleoDir: string) => ProcessEnv

cleoGitCommand()

Run a git command against the isolated .cleo/.git repo, suppressing errors. T4872 Signature
(args: string[], cleoDir: string) => Promise<{ stdout: string; success: boolean; }>

isCleoGitInitialized()

Check whether the isolated .cleo/.git repo has been initialized. T4872 Signature
(cleoDir: string) => boolean

loadStateFileAllowlist()

Load additional state file paths from config.json checkpoint.stateFileAllowlist. Returns an empty array if config is missing, malformed, or the key is absent. Signature
(cwd?: string | undefined) => Promise<string[]>

loadCheckpointConfig()

Load checkpoint configuration from config.json. T4552 Signature
(cwd?: string | undefined) => Promise<CheckpointConfig>

shouldCheckpoint()

Check whether a checkpoint should be performed. Evaluates: enabled, .cleo/.git initialized, debounce elapsed, files changed. T4552 T4872 Signature
(options?: { force?: boolean | undefined; cwd?: string | undefined; } | undefined) => Promise<boolean>

gitCheckpoint()

Stage .cleo/ state files and commit to the isolated .cleo/.git repo. Never fatal - all git errors are suppressed. T4552 T4872 Signature
(trigger?: "manual" | "auto" | "session-end", context?: string | undefined, cwd?: string | undefined) => Promise<void>

gitCheckpointStatus()

Show checkpoint configuration and status. T4552 T4872 Signature
(cwd?: string | undefined) => Promise<CheckpointStatus>

gitCheckpointDryRun()

Show what files would be committed (dry-run). T4552 T4872 Signature
(cwd?: string | undefined) => Promise<ChangedFile[]>

DataSafetyError

Safety violation error Signature
typeof DataSafetyError

getSafetyStats()

Get current safety statistics Signature
() => SafetyStats

resetSafetyStats()

Reset safety statistics (for testing) Signature
() => void

safeSaveSessions()

Safe wrapper for DataAccessor.saveSessions() Signature
(accessor: DataAccessor, data: Session[], cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<void>

safeSaveArchive()

Safe wrapper for DataAccessor.saveArchive() Signature
(accessor: DataAccessor, data: ArchiveFile, cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<...>

safeSingleTaskWrite()

Safe wrapper for single-task write operations (T5034). Performs: 1. Sequence validation 2. Write operation (caller-provided function) 3. Git checkpoint Verification is lightweight — no full-file read-back. The write itself is a targeted SQL operation that either succeeds or throws. Signature
(_accessor: DataAccessor, taskId: string, writeFn: () => Promise<void>, cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<...>

safeAppendLog()

Safe wrapper for DataAccessor.appendLog() Note: Log appends are fire-and-forget (no verification) but we still checkpoint to ensure data is committed. Signature
(accessor: DataAccessor, entry: Record<string, unknown>, cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<...>

runDataIntegrityCheck()

Run comprehensive data integrity check. Validates all data files and sequence consistency. Signature
(accessor: DataAccessor, cwd?: string | undefined) => Promise<{ passed: boolean; errors: string[]; warnings: string[]; stats: SafetyStats; }>

forceSafetyCheckpoint()

Force immediate checkpoint. Use before destructive operations. Signature
(context: string, cwd?: string | undefined) => Promise<void>

disableSafety()

Disable all safety for current process. DANGEROUS - only use for recovery operations. Signature
() => void

enableSafety()

Re-enable safety after being disabled. Signature
() => void

SafetyDataAccessor

Safety-enabled DataAccessor wrapper. Wraps any DataAccessor implementation and automatically applies safety checks to all write operations. Read operations pass through. This class CANNOT be bypassed - it’s the only way to get a DataAccessor from the factory (unless emergency disable is active). Signature
typeof SafetyDataAccessor
Methods

logVerbose()

Log safety operation if verbose mode is enabled.
(message: string) => void

getSafetyOptions()

Get safety options for data-safety-central operations.
() => Partial<SafetyOptions>

loadArchive()

() => Promise<ArchiveFile | null>

loadSessions()

() => Promise<Session[]>

saveSessions()

(data: Session[]) => Promise<void>

saveArchive()

(data: ArchiveFile) => Promise<void>

appendLog()

(entry: Record<string, unknown>) => Promise<void>

upsertSingleTask()

(task: Task) => Promise<void>

archiveSingleTask()

(taskId: string, fields: ArchiveFields) => Promise<void>

removeSingleTask()

(taskId: string) => Promise<void>

loadSingleTask()

(taskId: string) => Promise<Task | null>

addRelation()

(taskId: string, relatedTo: string, relationType: string, reason?: string | undefined) => Promise<void>

getMetaValue()

<T>(key: string) => Promise<T | null>

setMetaValue()

(key: string, value: unknown) => Promise<void>

getSchemaVersion()

() => Promise<string | null>

queryTasks()

(filters: TaskQueryFilters) => Promise<QueryTasksResult>

countTasks()

(filters?: { status?: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived" | ("cancelled" | "pending" | "active" | "blocked" | "done" | "archived")[] | undefined; parentId?: string | undefined; } | undefined) => Promise<...>

getChildren()

(parentId: string) => Promise<Task[]>

countChildren()

(parentId: string) => Promise<number>

countActiveChildren()

(parentId: string) => Promise<number>

getAncestorChain()

(taskId: string) => Promise<Task[]>

getSubtree()

(rootId: string) => Promise<Task[]>

getDependents()

(taskId: string) => Promise<Task[]>

getDependencyChain()

(taskId: string) => Promise<string[]>

taskExists()

(taskId: string) => Promise<boolean>

loadTasks()

(taskIds: string[]) => Promise<Task[]>

updateTaskFields()

(taskId: string, fields: TaskFieldUpdates) => Promise<void>

getNextPosition()

(parentId: string | null) => Promise<number>

shiftPositions()

(parentId: string | null, fromPosition: number, delta: number) => Promise<void>

transaction()

<T>(fn: (tx: TransactionAccessor) => Promise<T>) => Promise<T>

getActiveSession()

() => Promise<Session | null>

upsertSingleSession()

(session: Session) => Promise<void>

removeSingleSession()

(sessionId: string) => Promise<void>

close()

() => Promise<void>

wrapWithSafety(accessor, cwd)

Wrap a DataAccessor with safety. This is the internal factory helper that wraps any accessor with the SafetyDataAccessor wrapper. Signature
(accessor: DataAccessor, cwd?: string | undefined) => DataAccessor
Parameters
NameTypeDescription
accessorDataAccessorThe accessor to wrap
cwd: string | undefinedWorking directory
Returns — SafetyDataAccessor wrapping the input

isSafetyEnabled()

Check if safety is currently enabled. Signature
() => boolean
Returns — true if safety checks are active

getSafetyStatus()

Get safety status information. Signature
() => { enabled: boolean; reason?: string | undefined; }
Returns — Object with safety status details

createDataAccessor()

Create a DataAccessor for the given working directory. Always creates a SQLite accessor (ADR-006 canonical storage). ALL accessors returned are safety-enabled by default via SafetyDataAccessor wrapper. Use CLEO_DISABLE_SAFETY=true to bypass (emergency only). Signature
(_engine?: "sqlite" | undefined, cwd?: string | undefined) => Promise<DataAccessor>

getAccessor()

Convenience: get a DataAccessor with auto-detected engine. Signature
(cwd?: string | undefined) => Promise<DataAccessor>

showSequence()

Show current sequence state. Signature
(cwd?: string | undefined) => Promise<Record<string, unknown>>

checkSequence()

Check sequence integrity. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

repairSequence()

Repair sequence if behind. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<RepairResult>

allocateNextTaskId()

Atomically allocate the next task ID via SQLite. Uses BEGIN IMMEDIATE to guarantee no two concurrent callers receive the same ID, even across processes (WAL mode). Falls back to repair+retry if the sequence counter is behind the actual max task ID (e.g., stale counter from installations that never incremented it). T5184 Signature
(cwd?: string | undefined, retryCount?: number) => Promise<string>

SafetyError

Safety violation error. Signature
typeof SafetyError

checkTaskExists()

Check if a task ID already exists (collision detection). Signature
(taskId: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>
Throws
  • SafetyError if task exists and strict mode is enabled

verifyTaskWrite()

Verify a task was actually written to the database. Signature
(taskId: string, expectedData?: Partial<Task> | undefined, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>
Throws
  • SafetyError if verification fails

validateAndRepairSequence()

Validate and repair sequence if necessary. Signature
(cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<{ valid: boolean; repaired: boolean; oldCounter?: number | undefined; newCounter?: number | undefined; }>
Returns — true if sequence was valid or successfully repaired

triggerCheckpoint()

Trigger auto-checkpoint after successful write. Signature
(context: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<void>

safeCreateTask()

Safely create a task with all safety mechanisms. Wraps the actual createTask operation. Signature
(createFn: () => Promise<Task>, task: Task, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<Task>

safeUpdateTask()

Safely update a task with all safety mechanisms. Signature
(updateFn: () => Promise<Task | null>, taskId: string, _updates: Partial<Task>, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<...>

safeDeleteTask()

Safely delete a task with all safety mechanisms. Signature
(deleteFn: () => Promise<boolean>, taskId: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>

verifySessionWrite()

Verify session write. Signature
(sessionId: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>

safeCreateSession()

Safely create a session with all safety mechanisms. Signature
(createFn: () => Promise<Session>, session: Session, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<Session>

forceCheckpointBeforeOperation()

Force a checkpoint before destructive operations. Use this before migrations, bulk updates, etc. Signature
(operation: string, cwd?: string | undefined) => Promise<void>

runDataIntegrityCheck()

Run comprehensive data integrity check. Reports all issues found. Signature
(cwd?: string | undefined) => Promise<{ passed: boolean; issues: string[]; repairs: string[]; }>

getTask()

Get a task by ID, including its dependencies. Signature
(taskId: string, cwd?: string | undefined) => Promise<Task | null>

updateTask()

Update an existing task. Signature
(taskId: string, updates: Partial<Task>, cwd?: string | undefined) => Promise<Task | null>

deleteTask()

Delete a task by ID. Signature
(taskId: string, cwd?: string | undefined) => Promise<boolean>

listTasks()

List tasks with optional filters. Signature
(filters?: { status?: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived" | undefined; parentId?: string | null | undefined; type?: TaskType | undefined; phase?: string | undefined; limit?: number | undefined; } | undefined, cwd?: string | undefined) => Promise<...>

findTasks()

Find tasks by fuzzy text search. Signature
(query: string, limit?: number, cwd?: string | undefined) => Promise<Task[]>

archiveTask()

Archive a task (sets status to ‘archived’ with metadata). Signature
(taskId: string, reason?: string | undefined, cwd?: string | undefined) => Promise<boolean>

addDependency()

Add a dependency between tasks. Signature
(taskId: string, dependsOn: string, cwd?: string | undefined) => Promise<void>

removeDependency()

Remove a dependency. Signature
(taskId: string, dependsOn: string, cwd?: string | undefined) => Promise<void>

addRelation()

Add a relation between tasks. Signature
(taskId: string, relatedTo: string, relationType?: "related" | "blocks" | "duplicates" | "absorbs" | "fixes" | "extends" | "supersedes", cwd?: string | undefined, reason?: string | undefined) => Promise<...>

getRelations()

Get relations for a task. Signature
(taskId: string, cwd?: string | undefined) => Promise<{ relatedTo: string; type: string; reason?: string | undefined; }[]>

getBlockerChain()

Get the dependency chain (blockers) for a task using recursive CTE. Signature
(taskId: string, cwd?: string | undefined) => Promise<string[]>

getChildren()

Get children of a task (hierarchy). Signature
(parentId: string, cwd?: string | undefined) => Promise<Task[]>

getSubtree()

Build a tree from a root task using recursive CTE. Signature
(rootId: string, cwd?: string | undefined) => Promise<Task[]>

countByStatus()

Count tasks by status. Signature
(cwd?: string | undefined) => Promise<Record<string, number>>

countTasks()

Get total task count (excluding archived). Signature
(cwd?: string | undefined) => Promise<number>

createTask()

Create a task with full safety protections. Includes: collision detection, write verification, sequence validation, auto-checkpoint. Signature
(task: Task, cwd?: string | undefined, config?: Partial<SafetyConfig> | undefined) => Promise<Task>

updateTaskSafe()

Update a task with full safety protections. Includes: write verification, auto-checkpoint. Signature
(taskId: string, updates: Partial<Task>, cwd?: string | undefined, config?: Partial<SafetyConfig> | undefined) => Promise<Task | null>

deleteTaskSafe()

Delete a task with full safety protections. Includes: delete verification, auto-checkpoint. Signature
(taskId: string, cwd?: string | undefined, config?: Partial<SafetyConfig> | undefined) => Promise<boolean>

showTask()

Get a task by ID with enriched details. Checks active tasks first, then archive if not found. T4460 Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskDetail>

createPage()

Create an LAFSPage object from pagination parameters. Returns mode:“none” when no pagination is requested (no limit/offset). Returns mode:“offset” with hasMore/total when pagination is active. T4668 T4663 Signature
(input: PaginateInput) => LAFSPage

paginate()

Apply pagination to an array of items and return the sliced result with page metadata. T4668 T4663 Signature
<T>(items: T[], limit?: number | undefined, offset?: number | undefined) => { items: T[]; page: LAFSPage; }

toCompact()

Convert a full Task to compact representation. Signature
(task: Task) => CompactTask

listTasks()

List tasks with optional filtering and pagination. T4460 Signature
(options?: ListTasksOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ListTasksResult>

fuzzyScore()

Calculate fuzzy match score between query and text. Higher score = better match. 0 = no match. T4460 Signature
(query: string, text: string) => number

findTasks()

Search tasks by fuzzy matching, ID prefix, or exact title. Returns minimal fields only (context-efficient). T4460 Signature
(options: FindTasksOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<FindTasksResult>

extractAdrId()

Extract ADR ID from filename (e.g., ‘ADR-007-domain-consolidation.md’ - ‘ADR-007’) Signature
(filename: string) => string

parseFrontmatter()

Parse bold-key frontmatter pattern: Key: value Signature
(content: string) => AdrFrontmatter

extractTitle()

Extract H1 title from markdown Signature
(content: string) => string

parseAdrFile()

Parse a single ADR markdown file into an AdrRecord Signature
(filePath: string, projectRoot: string) => AdrRecord

linkPipelineAdr(projectRoot, taskId)

Link ADRs to a pipeline task when the architecture_decision stage completes. Signature
(projectRoot: string, taskId: string) => Promise<PipelineAdrLinkResult>
Parameters
NameTypeDescription
projectRootstringAbsolute path to project root
taskIdstringTask ID that owns the pipeline (e.g., ‘T4942’)

syncAdrsToDb()

Sync all ADR markdown files into the architecture_decisions table AND regenerate MANIFEST.jsonl in one pass. Signature
(projectRoot: string) => Promise<AdrSyncResult>

recordEvidence(epicId, stage, uri, type, options)

Record an evidence artifact linked to a lifecycle stage. Writes to the SQLite lifecycle_evidence table. Signature
(epicId: string, stage: string, uri: string, type: EvidenceType, options?: { agent?: string | undefined; description?: string | undefined; cwd?: string | undefined; } | undefined) => Promise<...>
Parameters
NameTypeDescription
epicIdstringEpic task ID (e.g. ‘T4881’)
stagestringCanonical stage name (e.g. ‘research’)
uristringURI of the evidence artifact
typeEvidenceTypeEvidence type: ‘file’, ‘url’, or ‘manifest’
options: \{ agent?: string | undefined; description?: string | undefined; cwd?: string | undefined; \} | undefinedOptional agent and description
Returns — The created evidence record

getEvidence(epicId, stage, cwd)

Query evidence records for an epic, optionally filtered by stage. Signature
(epicId: string, stage?: string | undefined, cwd?: string | undefined) => Promise<EvidenceRecord[]>
Parameters
NameTypeDescription
epicIdstringEpic task ID
stage: string | undefinedOptional stage name filter
cwd: string | undefinedOptional working directory
Returns — Array of evidence records

linkProvenance(epicId, stage, filePath, cwd)

Convenience wrapper to record a file as provenance evidence. Converts the file path to a URI relative to the .cleo/ directory, sets the type to ‘file’, and extracts a description from the filename. Signature
(epicId: string, stage: string, filePath: string, cwd?: string | undefined) => Promise<EvidenceRecord>
Parameters
NameTypeDescription
epicIdstringEpic task ID
stagestringCanonical stage name
filePathstringAbsolute or relative path to the file
cwd: string | undefinedOptional working directory
Returns — The created evidence record

getEvidenceSummary(epicId, cwd)

Aggregate evidence counts per stage for an epic. Signature
(epicId: string, cwd?: string | undefined) => Promise<{ stage: string; count: number; types: Record<EvidenceType, number>; }[]>
Parameters
NameTypeDescription
epicIdstringEpic task ID
cwd: string | undefinedOptional working directory
Returns — Array of per-stage summaries with type breakdowns

normalizeEpicId(dirName)

Strip suffixes from epic directory names. E.g. T4881_install-channels - T4881 Signature
(dirName: string) => string
Parameters
NameTypeDescription
dirNamestringDirectory name that may contain a suffix
Returns — The normalized T#### epic ID

getRcasdBaseDir(cwd)

Get the absolute path to the .cleo/rcasd/ base directory. Signature
(cwd?: string | undefined) => string
Parameters
NameTypeDescription
cwd: string | undefinedOptional working directory override
Returns — Absolute path to the rcasd base directory

getEpicDir(epicId, cwd)

Get the absolute path to .cleo/rcasd/\{epicId\}/. Uses the normalized epic ID (without suffixes). Signature
(epicId: string, cwd?: string | undefined) => string
Parameters
NameTypeDescription
epicIdstringEpic identifier (e.g. T4881)
cwd: string | undefinedOptional working directory override
Returns — Absolute path to the epic directory

findEpicDir(epicId, cwd)

Search both rcasd/ and legacy rcsd/ for an existing epic directory. Also checks suffixed directory names (e.g. T4881_install-channels matches T4881). Signature
(epicId: string, cwd?: string | undefined) => string | null
Parameters
NameTypeDescription
epicIdstringEpic identifier to search for
cwd: string | undefinedOptional working directory override
Returns — Absolute path to the found directory, or null

getStagePath(epicId, stage, cwd)

Get the stage subdirectory path for an epic. Uses STAGE_SUBDIRS mapping, falling back to the raw stage name. Signature
(epicId: string, stage: string, cwd?: string | undefined) => string
Parameters
NameTypeDescription
epicIdstringEpic identifier
stagestringCanonical stage name (e.g. research, contribution)
cwd: string | undefinedOptional working directory override
Returns — Absolute path to the stage subdirectory

ensureStagePath(epicId, stage, cwd)

Get the stage subdirectory path, creating it if it does not exist. Signature
(epicId: string, stage: string, cwd?: string | undefined) => string
Parameters
NameTypeDescription
epicIdstringEpic identifier
stagestringCanonical stage name
cwd: string | undefinedOptional working directory override
Returns — Absolute path to the (now existing) stage subdirectory

getManifestPath(epicId, cwd)

Get the manifest path for an epic under the default rcasd directory. Signature
(epicId: string, cwd?: string | undefined) => string
Parameters
NameTypeDescription
epicIdstringEpic identifier
cwd: string | undefinedOptional working directory override
Returns — Absolute path to .cleo/rcasd/\{epicId\}/_manifest.json

findManifestPath(epicId, cwd)

Search both rcasd/ and rcsd/ for an existing manifest file. Checks suffixed directory names as well. Signature
(epicId: string, cwd?: string | undefined) => string | null
Parameters
NameTypeDescription
epicIdstringEpic identifier
cwd: string | undefinedOptional working directory override
Returns — Absolute path to the found manifest, or null

getLooseResearchFiles(cwd)

Scan the rcasd root directory for loose T####_*.md files that are not inside subdirectories. Signature
(cwd?: string | undefined) => { file: string; epicId: string; fullPath: string; }[]
Parameters
NameTypeDescription
cwd: string | undefinedOptional working directory override
Returns — Array of file info with extracted epic ID

listEpicDirs(cwd)

List all epic directories across rcasd/ and rcsd/. Signature
(cwd?: string | undefined) => { epicId: string; dirName: string; fullPath: string; }[]
Parameters
NameTypeDescription
cwd: string | undefinedOptional working directory override
Returns — Array of epic info with normalized IDs and original directory names

parseFrontmatter(content)

Parse YAML frontmatter from a markdown string. Finds the YAML block delimited by --- at the start of the file, parses key-value pairs, and returns the structured metadata plus the remaining body content. Signature
(content: string) => ParsedFrontmatter
Parameters
NameTypeDescription
contentstringFull markdown file content
Returns — Parsed frontmatter, body, and raw YAML block

serializeFrontmatter(metadata)

Convert a FrontmatterMetadata object to a YAML frontmatter string. Output format: Signature
(metadata: FrontmatterMetadata) => string
Parameters
NameTypeDescription
metadataFrontmatterMetadataThe frontmatter metadata to serialize
Returns — YAML frontmatter string including --- delimiters

addFrontmatter(content, metadata)

Add or replace YAML frontmatter in markdown content. If the content already has a frontmatter block, it is replaced. Otherwise the YAML block is prepended. Signature
(content: string, metadata: FrontmatterMetadata) => string
Parameters
NameTypeDescription
contentstringOriginal markdown content
metadataFrontmatterMetadataFrontmatter metadata to set
Returns — Updated content with new frontmatter

buildFrontmatter(epicId, stage, options)

Convenience builder for common frontmatter patterns. Auto-sets updated to the current ISO date string. Signature
(epicId: string, stage: string, options?: { task?: string | undefined; related?: RelatedLink[] | undefined; created?: string | undefined; } | undefined) => FrontmatterMetadata
Parameters
NameTypeDescription
epicIdstringEpic identifier (e.g. T4881)
stagestringRCASD stage name (e.g. research)
options: \{ task?: string | undefined; related?: RelatedLink[] | undefined; created?: string | undefined; \} | undefinedOptional fields: task, related links, created date
Returns — A FrontmatterMetadata object ready for serialization Scan all markdown files in .cleo/rcasd/ for files that reference the given epic+stage combination via their related frontmatter links. This enables “what links here?” queries (Obsidian-style backlinks). Signature
(epicId: string, stage: string, cwd?: string | undefined) => { file: string; link: RelatedLink; }[]
Parameters
NameTypeDescription
epicIdstringEpic identifier to search for
stagestringStage name to search for
cwd: string | undefinedOptional working directory override
Returns — Array of files with matching related links

getStageOrder(stage)

Get the order/index of a stage (1-based). Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => number
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to look up
Returns — The stage order (1-9) T4800

isStageBefore(stageA, stageB)

Check if stage A comes before stage B in the pipeline. Signature
(stageA: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", stageB: "research" | ... 7 more ... | "release") => boolean
Parameters
NameTypeDescription
stageA"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"First stage to compare
stageB"research" | ... 7 more ... | "release"Second stage to compare
Returns — True if stageA comes before stageB T4800

isStageAfter(stageA, stageB)

Check if stage A comes after stage B in the pipeline. Signature
(stageA: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", stageB: "research" | ... 7 more ... | "release") => boolean
Parameters
NameTypeDescription
stageA"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"First stage to compare
stageB"research" | ... 7 more ... | "release"Second stage to compare
Returns — True if stageA comes after stageB T4800

getNextStage(stage)

Get the next stage in the pipeline. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => "research" | ... 8 more ... | null
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"Current stage
Returns — The next stage, or null if at the end T4800

getPreviousStage(stage)

Get the previous stage in the pipeline. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => "research" | ... 8 more ... | null
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"Current stage
Returns — The previous stage, or null if at the start T4800

getStagesBetween(from, to)

Get all stages between two stages (inclusive). Signature
(from: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", to: "research" | "consensus" | ... 6 more ... | "release") => ("research" | ... 7 more ... | "release")[]
Parameters
NameTypeDescription
from"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"Starting stage
to"research" | "consensus" | ... 6 more ... | "release"Ending stage
Returns — Array of stages between from and to T4800

getPrerequisites(stage)

Get prerequisites for a stage. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => ("research" | ... 7 more ... | "release")[]
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to get prerequisites for
Returns — Array of prerequisite stages T4800

isPrerequisite(potentialPrereq, stage)

Check if one stage is a prerequisite of another. Signature
(potentialPrereq: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", stage: "research" | ... 7 more ... | "release") => boolean
Parameters
NameTypeDescription
potentialPrereq"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"Stage that might be a prerequisite
stage"research" | ... 7 more ... | "release"Stage to check against
Returns — True if potentialPrereq is required before stage T4800

getDependents(stage)

Get all stages that depend on a given stage. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => ("research" | ... 7 more ... | "release")[]
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to find dependents for
Returns — Array of stages that require this stage T4800

isValidStage(stage)

Check if a stage name is valid. Signature
(stage: string) => stage is "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"
Parameters
NameTypeDescription
stagestringStage name to validate
Returns — True if valid stage name T4800

validateStage(stage)

Validate a stage name and throw if invalid. Signature
(stage: string) => "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"
Parameters
NameTypeDescription
stagestringStage name to validate
Returns — The validated Stage T4800 Throws
  • Error If stage is invalid

isValidStageStatus(status)

Check if a stage status is valid. Signature
(status: string) => status is "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped"
Parameters
NameTypeDescription
statusstringStatus to validate
Returns — True if valid status T4800

getStagesByCategory(category)

Get stages by category. Signature
(category: StageCategory) => ("research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release")[]
Parameters
NameTypeDescription
categoryStageCategoryCategory to filter by
Returns — Array of stages in that category T4800

getSkippableStages()

Get skippable stages. Signature
() => ("research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release")[]
Returns — Array of stages that can be skipped T4800

checkTransition(from, to, force)

Check if a transition is allowed. Signature
(from: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", to: "research" | "consensus" | ... 6 more ... | "release", force?: boolean) => { ...; }
Parameters
NameTypeDescription
from"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"Source stage
to"research" | "consensus" | ... 6 more ... | "release"Target stage
force: booleanWhether to allow forced transitions
Returns — Object with allowed flag and reason T4800

ensureStageArtifact()

Ensure stage artifact exists and frontmatter/backlinks are up to date. Signature
(epicId: string, stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", cwd?: string | undefined) => Promise<...>

getLifecycleState()

Get the current lifecycle state for an epic. T4467 Signature
(epicId: string, cwd?: string | undefined) => Promise<RcasdManifest>

startStage()

Start a lifecycle stage. T4467 Signature
(epicId: string, stage: string, cwd?: string | undefined) => Promise<StageTransitionResult>

completeStage()

Complete a lifecycle stage. T4467 Signature
(epicId: string, stage: string, artifacts?: string[] | undefined, cwd?: string | undefined) => Promise<StageTransitionResult>

skipStage()

Skip a lifecycle stage. T4467 Signature
(epicId: string, stage: string, reason: string, cwd?: string | undefined) => Promise<StageTransitionResult>

checkGate()

Check lifecycle gate before starting a stage. T4467 Signature
(epicId: string, targetStage: string, cwd?: string | undefined) => Promise<GateCheckResult>

getLifecycleStatus()

Get lifecycle status for an epic from SQLite. Returns stage progress, current/next stage, and blockers. T4801 - SQLite-native implementation Signature
(epicId: string, cwd?: string | undefined) => Promise<{ epicId: string; title?: string | undefined; currentStage: "research" | "consensus" | "architecture_decision" | "specification" | ... 5 more ... | null; stages: { ...; }[]; nextStage: "research" | ... 8 more ... | null; blockedOn: string[]; initialized: boolean;...

getLifecycleHistory()

Get lifecycle history for an epic. Returns stage transitions and gate events sorted by timestamp. SQLite-native implementation - queries lifecycle_stages and lifecycle_gate_results tables. T4785 T4801 Signature
(epicId: string, cwd?: string | undefined) => Promise<{ epicId: string; history: LifecycleHistoryEntry[]; }>

getLifecycleGates()

Get all gate statuses for an epic. T4785 Signature
(epicId: string, cwd?: string | undefined) => Promise<Record<string, Record<string, GateData>>>

getStagePrerequisites()

Get prerequisites for a target stage. Pure data function, no I/O. T4785 Signature
(targetStage: string) => { prerequisites: string[]; stageInfo: { stage: string; name: string; description: string; order: number; } | undefined; }

checkStagePrerequisites()

Check if a stage’s prerequisites are met for an epic. T4785 Signature
(epicId: string, targetStage: string, cwd?: string | undefined) => Promise<{ epicId: string; targetStage: string; valid: boolean; canProgress: boolean; missingPrerequisites: string[]; issues: { ...; }[]; }>

recordStageProgress()

Record a stage status transition (progress/record). SQLite-native implementation - T4801 T4785 T4801 Signature
(epicId: string, stage: string, status: string, notes?: string | undefined, cwd?: string | undefined) => Promise<{ epicId: string; stage: string; status: string; timestamp: string; }>

skipStageWithReason()

Skip a stage with a reason (engine-compatible). T4785 Signature
(epicId: string, stage: string, reason: string, cwd?: string | undefined) => Promise<{ epicId: string; stage: string; reason: string; timestamp: string; }>

resetStage()

Reset a stage to pending (emergency). T4785 Signature
(epicId: string, stage: string, reason: string, cwd?: string | undefined) => Promise<{ epicId: string; stage: string; reason: string; }>

passGate()

Mark a gate as passed. SQLite-native implementation - T4801 T4785 T4801 Signature
(epicId: string, gateName: string, agent?: string | undefined, notes?: string | undefined, cwd?: string | undefined) => Promise<{ epicId: string; gateName: string; timestamp: string; }>

failGate()

Mark a gate as failed. SQLite-native implementation - T4801 T4785 T4801 Signature
(epicId: string, gateName: string, reason?: string | undefined, cwd?: string | undefined) => Promise<{ epicId: string; gateName: string; reason?: string | undefined; timestamp: string; }>

listEpicsWithLifecycle()

List all epic IDs that have lifecycle data. T4785 Signature
(cwd?: string | undefined) => Promise<string[]>

getCurrentSessionId()

Get the current session ID. Signature
(cwd?: string | undefined) => string | null

getContextStatePath()

Get context state file path for a session. Signature
(sessionId?: string | undefined, cwd?: string | undefined) => string

readContextState()

Read context state for a session. Returns null if stale or missing. Signature
(sessionId?: string | undefined, cwd?: string | undefined) => Record<string, unknown> | null

getThresholdLevel()

Determine the threshold level for a given percentage. Signature
(percentage: number) => AlertLevel | null

shouldAlert()

Determine if we should alert based on threshold crossing. Returns the alert level if a new threshold was crossed, null otherwise. Signature
(currentPct: number, lastAlertedPct?: number, minThreshold?: AlertLevel) => AlertLevel | null

getRecommendedAction()

Get recommended action for an alert level. Signature
(percentage: number) => string | null

checkContextAlert()

Main function to check and determine if an alert should fire. Non-blocking - always returns a result. Signature
(currentCommand?: string | undefined, cwd?: string | undefined) => AlertCheckResult

pushWarning()

Push a deprecation or informational warning into the current envelope. Warnings are drained (consumed) by the next formatSuccess/formatError call. T4669 T4663 Signature
(warning: Warning) => void

formatSuccess()

Format a successful result as a full LAFS-conformant envelope. Always produces the full LAFSEnvelope with $schema and _meta. When operation is omitted, defaults to ‘cli.output’. Supports optional page (T4668) and _extensions (T4670). T4672 T4668 T4670 T4663 Signature
<T>(data: T, message?: string | undefined, operationOrOpts?: string | FormatOptions | undefined) => string

formatError()

Format an error as a full LAFS-conformant envelope. Always produces the full LAFSEnvelope with $schema and _meta. When operation is omitted, defaults to ‘cli.output’. T4672 T4663 Signature
(error: CleoError, operation?: string | undefined) => string

formatOutput()

Format any result (success or error) as LAFS JSON. Signature
<T>(result: CleoError | T) => string

getRegistryEntry()

Look up a registry entry by CLEO exit code. T4671 T4663 Signature
(exitCode: ExitCode) => CleoRegistryEntry | undefined

getRegistryEntryByLafsCode()

Look up a registry entry by LAFS string code. T4671 T4663 Signature
(lafsCode: string) => CleoRegistryEntry | undefined

getCleoErrorRegistry()

Get the full CLEO error registry for conformance testing. T4671 T4663 Signature
() => CleoRegistryEntry[]

isCleoRegisteredCode()

Check if a LAFS code is registered in the CLEO error registry. T4671 T4663 Signature
(lafsCode: string) => boolean

createTestDb()

Create a temporary directory with an initialized tasks.db. Usage: Signature
() => Promise<TestDbEnv>

makeTaskFile()

Build a TaskFile structure from a list of task partials. Useful for seeding test data via accessor.upsertSingleTask(). Signature
(tasks: (Partial<Task> & { id: string; })[]) => TaskFile

seedTasks()

Seed tasks into the test database via the accessor. Uses a two-pass approach to avoid foreign key violations: 1. First pass: upsert all tasks without dependencies so FK targets exist 2. Second pass: upsert tasks again with dependencies (all FK targets now exist) 3. Initialize metadata for the test environment Signature
(accessor: DataAccessor, tasks: (Partial<Task> & { id: string; })[]) => Promise<void>

getChildren()

Get direct children of a task. Signature
(taskId: string, tasks: Task[]) => Task[]

getChildIds()

Get direct child IDs. Signature
(taskId: string, tasks: Task[]) => string[]

getDescendants()

Get all descendants of a task (recursive). Signature
(taskId: string, tasks: Task[]) => Task[]

getDescendantIds()

Get all descendant IDs (flat list). Signature
(taskId: string, tasks: Task[]) => string[]

getParentChain()

Get the parent chain (ancestors) from a task up to the root. Returns ordered from immediate parent to root. Signature
(taskId: string, tasks: Task[]) => Task[]

getParentChainIds()

Get the parent chain as IDs. Signature
(taskId: string, tasks: Task[]) => string[]

getDepth()

Calculate depth of a task in the hierarchy (0-based). Root tasks have depth 0, their children depth 1, etc. Signature
(taskId: string, tasks: Task[]) => number

getRootAncestor()

Get the root ancestor of a task. Signature
(taskId: string, tasks: Task[]) => Task | null

isAncestorOf()

Check if a task is an ancestor of another. Signature
(ancestorId: string, descendantId: string, tasks: Task[]) => boolean

isDescendantOf()

Check if a task is a descendant of another. Signature
(descendantId: string, ancestorId: string, tasks: Task[]) => boolean

getSiblings()

Get sibling tasks (same parent). Signature
(taskId: string, tasks: Task[]) => Task[]

validateHierarchy()

Signature
(parentId: string | null, tasks: Task[], policy?: { maxDepth?: number | undefined; maxSiblings?: number | undefined; } | undefined) => HierarchyValidation

wouldCreateCircle()

Detect circular reference if parentId were set. Signature
(taskId: string, newParentId: string, tasks: Task[]) => boolean

buildTree()

Signature
(tasks: Task[]) => TaskTreeNode[]

flattenTree()

Flatten a tree back to a list (depth-first). Signature
(nodes: TaskTreeNode[]) => Task[]

resolveHierarchyPolicy()

Resolve a full HierarchyPolicy from config, starting with a profile preset and overriding with any explicitly set config.hierarchy fields. Signature
(config: CleoConfig) => HierarchyPolicy

assertParentExists()

Assert that a parent task exists in the task list. Returns an error result if not found, null if OK. Signature
(parentId: string, tasks: Task[]) => HierarchyValidationResult | null

assertNoCycle()

Assert that re-parenting would not create a cycle. Returns an error result if a cycle is detected, null if OK. Signature
(taskId: string, newParentId: string, tasks: Task[]) => HierarchyValidationResult | null

countActiveChildren()

Count active (non-done, non-cancelled, non-archived) children of a parent. Signature
(parentId: string, tasks: Task[]) => number

validateHierarchyPlacement()

Validate whether a new task can be placed under the given parent according to the resolved hierarchy policy. Signature
(parentId: string | null, tasks: Task[], policy: HierarchyPolicy) => HierarchyValidationResult

loadConfig()

Load and merge configuration from all sources. Priority: defaults global config project config environment vars Signature
(cwd?: string | undefined) => Promise<CleoConfig>

getConfigValue()

Get a single config value with source tracking. Returns the value and which source it came from. Signature
<T>(path: string, cwd?: string | undefined) => Promise<ResolvedValue<T>>

getRawConfigValue()

Get a raw config value from the project config file only (no cascade). Returns undefined if the key is not found. Used by the engine layer for simple key lookups without source tracking. T4789 Signature
(key: string, cwd?: string | undefined) => Promise<unknown>

getRawConfig()

Get the full raw project config (no cascade). Returns null if no config file exists. T4789 Signature
(cwd?: string | undefined) => Promise<Record<string, unknown> | null>

parseConfigValue()

Parse a string value into its appropriate JS type. Handles booleans, null, integers, floats, and JSON. T4789 Signature
(value: unknown) => unknown

setConfigValue()

Set a config value in the project or global config file (dot-notation supported). Creates intermediate objects as needed. Parses string values into appropriate types (boolean, number, null, JSON). T4789 T4795 Signature
(key: string, value: unknown, cwd?: string | undefined, opts?: { global?: boolean | undefined; } | undefined) => Promise<{ key: string; value: unknown; scope: "global" | "project"; }>

validateTitle()

Validate a task title. T4460 Signature
(title: string) => void

validateStatus()

Validate task status. T4460 Signature
(status: string) => asserts status is "cancelled" | "pending" | "active" | "blocked" | "done" | "archived"

normalizePriority()

Normalize priority to canonical string format. Accepts both string names (“critical”,“high”,“medium”,“low”) and numeric (1-9). Returns the canonical string format per todo.schema.json. T4572 Signature
(priority: string | number) => TaskPriority

validatePriority()

Validate task priority. T4460 T4572 Signature
(priority: string) => asserts priority is TaskPriority

validateTaskType()

Validate task type. T4460 Signature
(type: string) => asserts type is TaskType

validateSize()

Validate task size. T4460 Signature
(size: string) => asserts size is TaskSize

validateLabels()

Validate label format. T4460 Signature
(labels: string[]) => void

validatePhaseFormat()

Validate phase slug format. T4460 Signature
(phase: string) => void

validateDepends()

Validate dependency IDs exist. T4460 Signature
(depends: string[], tasks: Task[]) => void

validateParent()

Validate parent hierarchy constraints. T4460 Signature
(parentId: string, tasks: Task[], maxDepth?: number, maxSiblings?: number) => void

getTaskDepth()

Get the depth of a task in the hierarchy. T4460 Signature
(taskId: string, tasks: Task[]) => number

inferTaskType()

Infer task type from parent context. T4460 Signature
(parentId: string | null | undefined, tasks: Task[]) => TaskType

getNextPosition()

Get the next position for a task within a parent scope. T4460 Signature
(parentId: string | null | undefined, tasks: Task[]) => number

logOperation()

Log an operation to the audit log. T4460 Signature
(operation: string, taskId: string, details: Record<string, unknown>, accessor?: DataAccessor | undefined) => Promise<void>

findRecentDuplicate()

Check for recent duplicate task. T4460 Signature
(title: string, phase: string | undefined, tasks: Task[], windowSeconds?: number) => Task | null

addTask()

Add a new task to the todo file. T4460 Signature
(options: AddTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<AddTaskResult>

listPhases()

List all phases with status summaries. T4464 Signature
(_cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ListPhasesResult>

showPhase()

Show the current phase details. T4464 Signature
(slug?: string | undefined, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ShowPhaseResult>

setPhase()

Set the current project phase. T4464 Signature
(options: SetPhaseOptions, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<SetPhaseResult>

startPhase()

Start a phase (pending - active). T4464 Signature
(slug: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ phase: string; startedAt: string; }>

completePhase()

Complete a phase (active - completed). T4464 Signature
(slug: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ phase: string; completedAt: string; }>

advancePhase()

Advance to the next phase. T4464 Signature
(force?: boolean, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<AdvancePhaseResult>

renamePhase()

Rename a phase and update all task references. T4464 Signature
(oldName: string, newName: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<RenamePhaseResult>

deletePhase()

Delete a phase with optional task reassignment. T4464 Signature
(slug: string, options?: { reassignTo?: string | undefined; force?: boolean | undefined; }, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<DeletePhaseResult>

pruneAuditLog(cleoDir, config)

Prune old audit_log rows from tasks.db. 1. If auditRetentionDays is 0 or undefined, skip age-based pruning. 2. Compute cutoff timestamp from auditRetentionDays. 3. If archiveBeforePrune, select rows older than cutoff and write to .cleo/backups/logs/audit-YYYY-MM-DD.jsonl.gz. 4. Delete rows older than cutoff from audit_log. Idempotent — safe to call multiple times. Never throws — returns zero counts on any error. Signature
(cleoDir: string, config: LoggingConfig) => Promise<PruneResult>
Parameters
NameTypeDescription
cleoDirstringAbsolute path to .cleo directory
configLoggingConfigLoggingConfig with auditRetentionDays and archiveBeforePrune

queryAudit()

Query audit entries from SQLite audit_log table. Used by session-grade.ts for behavioral analysis. Returns entries ordered chronologically (ASC) to preserve behavioral sequence for grading analysis. Signature
(options?: { sessionId?: string | undefined; domain?: string | undefined; operation?: string | undefined; taskId?: string | undefined; since?: string | undefined; limit?: number | undefined; } | undefined) => Promise<...>

generateProjectHash()

Canonical project identity hash. SHA-256 of absolute path, first 12 hex chars. Single source of truth — do not duplicate this function elsewhere. Signature
(projectPath: string) => string

validateAgainstSchema()

Validate data against a JSON Schema object. Throws CleoError on validation failure. Signature
(data: unknown, schema: Record<string, unknown>, schemaId?: string | undefined) => void

validateAgainstSchemaFile()

Load a JSON Schema file and validate data against it. Signature
(data: unknown, schemaPath: string) => Promise<void>

checkSchema()

Check if data is valid against a schema without throwing. Returns an array of error messages (empty if valid). Signature
(data: unknown, schema: Record<string, unknown>) => string[]

resolveSchemaPath(schemaName)

Resolve the absolute path to a schema file at runtime. Priority: 1. Global install: ~/.cleo/schemas/schemaName 2. Package bundled: /schemas/schemaName Signature
(schemaName: string) => string | null
Parameters
NameTypeDescription
schemaNamestringFilename of the schema (e.g. “config.schema.json”)
Returns — Absolute path to the schema file, or null if not found

getSchemaVersion(schemaName)

Read the schema version from a resolved schema file. Checks schemaVersion (top-level) and _meta.schemaVersion (canonical). Signature
(schemaName: string) => string | null
Parameters
NameTypeDescription
schemaNamestringFilename of the schema (e.g. “config.schema.json”)
Returns — The version string, or null if not found or unreadable

ensureGlobalSchemas(opts)

Copy ALL bundled schemas from package schemas/ to ~/.cleo/schemas/. - Creates the global schemas directory if it doesn’t exist. - Skips files that are already up-to-date (same version). - Overwrites stale files (version mismatch). Signature
(_opts?: Record<string, unknown> | undefined) => SchemaInstallResult
Parameters
NameTypeDescription
optsOptional settings (currently unused, reserved for future options)
Returns — Summary of installed, updated, and total schemas

checkGlobalSchemas()

Verify that global schemas are installed and not stale. Signature
() => CheckResult
Returns — Check result with counts and lists of issues

checkSchemaStaleness()

Compare global schema versions against bundled package versions. Signature
() => StalenessReport
Returns — Report of stale, current, and missing schemas

listInstalledSchemas()

List all schemas installed in ~/.cleo/schemas/. Signature
() => InstalledSchema[]
Returns — Array of installed schema details

cleanProjectSchemas(projectRoot)

Backup and remove deprecated .cleo/schemas/ directory from a project. Schemas should live in ~/.cleo/schemas/ (global) not in project directories. This function creates a backup before removal for safety. Signature
(projectRoot: string) => Promise<{ cleaned: boolean; }>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
Returns — Whether cleanup was performed

readSchemaVersionFromFile()

Read the top-level schemaVersion field from a schema file. Delegates to the centralized schema-management module. Returns null if the file cannot be read or has no such field. Signature
(schemaName: string) => string | null

checkSchemaIntegrity(cwd)

Check integrity of all active JSON files in a CLEO project. Signature
(cwd?: string | undefined) => Promise<SchemaIntegrityReport>
Parameters
NameTypeDescription
cwd: string | undefinedProject root (defaults to process.cwd())

detectProjectType()

Detect project type from directory contents. Returns a schema-compliant ProjectContext object. Signature
(projectDir: string) => ProjectContext

BrainDataAccessor

Signature
typeof BrainDataAccessor
Methods

addDecision()

(row: { id: string; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; confidence: "high" | "medium" | "low"; decision: string; rationale: string; createdAt?: string | undefined; ... 5 more ...; contextPhase?: string | ... 1 more ... | undefined; }) => Promise<...>

getDecision()

(id: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; confidence: "high" | "medium" | "low"; ... 6 more ...; contextPhase: string | null; } | null>

findDecisions()

(params?: { type?: "architecture" | "technical" | "process" | "strategic" | "tactical" | undefined; confidence?: "high" | "medium" | "low" | undefined; outcome?: "pending" | "success" | "failure" | "mixed" | undefined; contextTaskId?: string | undefined; limit?: number | undefined; }) => Promise<...>

updateDecision()

(id: string, updates: Partial<{ id: string; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; confidence: "high" | "medium" | "low"; decision: string; rationale: string; ... 6 more ...; contextPhase?: string | ... 1 more ... | undefined; }>) => Promise<...>

addPattern()

(row: { id: string; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; pattern: string; context: string; updatedAt?: string | null | undefined; frequency?: number | undefined; ... 5 more ...; extractedAt?: string | undefined; }) => Promise<...>

getPattern()

(id: string) => Promise<{ id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; pattern: string; context: string; frequency: number; ... 5 more ...; extractedAt: string; } | null>

findPatterns()

(params?: { type?: "success" | "workflow" | "failure" | "blocker" | "optimization" | undefined; impact?: "high" | "medium" | "low" | undefined; minFrequency?: number | undefined; limit?: number | undefined; }) => Promise<...>

updatePattern()

(id: string, updates: Partial<{ id: string; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; pattern: string; context: string; updatedAt?: string | null | undefined; frequency?: number | undefined; ... 5 more ...; extractedAt?: string | undefined; }>) => Promise<...>

addLearning()

(row: { id: string; source: string; confidence: number; insight: string; createdAt?: string | undefined; updatedAt?: string | null | undefined; actionable?: boolean | undefined; application?: string | ... 1 more ... | undefined; applicableTypesJson?: string | ... 1 more ... | undefined; }) => Promise<...>

getLearning()

(id: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; } | null>

findLearnings()

(params?: { minConfidence?: number | undefined; actionable?: boolean | undefined; limit?: number | undefined; }) => Promise<{ id: string; createdAt: string; updatedAt: string | null; source: string; ... 4 more ...; applicableTypesJson: string | null; }[]>

updateLearning()

(id: string, updates: Partial<{ id: string; source: string; confidence: number; insight: string; createdAt?: string | undefined; updatedAt?: string | null | undefined; actionable?: boolean | undefined; application?: string | ... 1 more ... | undefined; applicableTypesJson?: string | ... 1 more ... | undefined; }>) =...

addObservation()

(row: { id: string; title: string; type: "discovery" | "change" | "feature" | "bugfix" | "decision" | "refactor"; project?: string | null | undefined; createdAt?: string | undefined; updatedAt?: string | ... 1 more ... | undefined; ... 9 more ...; discoveryTokens?: number | ... 1 more ... | undefined; }) => Promise<...

getObservation()

(id: string) => Promise<{ project: string | null; id: string; createdAt: string; updatedAt: string | null; title: string; type: "discovery" | "change" | "feature" | "bugfix" | "decision" | "refactor"; ... 9 more ...; discoveryTokens: number | null; } | null>

findObservations()

(params?: { type?: "discovery" | "change" | "feature" | "bugfix" | "decision" | "refactor" | undefined; project?: string | undefined; sourceType?: "agent" | "manual" | "session-debrief" | "claude-mem" | undefined; sourceSessionId?: string | undefined; limit?: number | undefined; }) => Promise<...>

updateObservation()

(id: string, updates: Partial<{ id: string; title: string; type: "discovery" | "change" | "feature" | "bugfix" | "decision" | "refactor"; project?: string | null | undefined; createdAt?: string | undefined; ... 10 more ...; discoveryTokens?: number | ... 1 more ... | undefined; }>) => Promise<...>
(row: { taskId: string; linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts"; memoryType: "decision" | "pattern" | "learning" | "observation"; memoryId: string; createdAt?: string | undefined; }) => Promise<...>

getLinksForMemory()

(memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string) => Promise<{ createdAt: string; taskId: string; linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts"; memoryType: "decision" | ... 2 more ... | "observation"; memoryId: string; }[]>

getLinksForTask()

(taskId: string) => Promise<{ createdAt: string; taskId: string; linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts"; memoryType: "decision" | "pattern" | "learning" | "observation"; memoryId: string; }[]>
(memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string, taskId: string, linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts") => Promise<...>

addStickyNote()

(row: { id: string; content: string; createdAt?: string | undefined; updatedAt?: string | null | undefined; status?: "active" | "archived" | "converted" | undefined; priority?: "high" | "medium" | "low" | null | undefined; sourceType?: string | ... 1 more ... | undefined; tagsJson?: string | ... 1 more ... | undefin...

getStickyNote()

(id: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; status: "active" | "archived" | "converted"; priority: "high" | "medium" | "low" | null; content: string; sourceType: string | null; tagsJson: string | null; convertedToJson: string | null; color: "yellow" | ... 4 more ... | null; } |...

findStickyNotes()

(params?: { status?: "active" | "archived" | "converted" | undefined; color?: "yellow" | "blue" | "green" | "red" | "purple" | undefined; priority?: "high" | "medium" | "low" | undefined; limit?: number | undefined; }) => Promise<...>

updateStickyNote()

(id: string, updates: Partial<{ id: string; content: string; createdAt?: string | undefined; updatedAt?: string | null | undefined; status?: "active" | "archived" | "converted" | undefined; priority?: "high" | ... 3 more ... | undefined; sourceType?: string | ... 1 more ... | undefined; tagsJson?: string | ... 1 mor...

deleteStickyNote()

(id: string) => Promise<void>

addPageNode()

(node: { id: string; nodeType: "task" | "file" | "doc" | "concept"; label: string; createdAt?: string | undefined; metadataJson?: string | null | undefined; }) => Promise<{ id: string; createdAt: string; metadataJson: string | null; nodeType: "task" | ... 2 more ... | "concept"; label: string; }>

getPageNode()

(id: string) => Promise<{ id: string; createdAt: string; metadataJson: string | null; nodeType: "task" | "file" | "doc" | "concept"; label: string; } | null>

findPageNodes()

(params?: { nodeType?: "task" | "file" | "doc" | "concept" | undefined; limit?: number | undefined; }) => Promise<{ id: string; createdAt: string; metadataJson: string | null; nodeType: "task" | "file" | "doc" | "concept"; label: string; }[]>

removePageNode()

(id: string) => Promise<void>

addPageEdge()

(edge: { fromId: string; toId: string; edgeType: "depends_on" | "implements" | "relates_to" | "documents"; createdAt?: string | undefined; weight?: number | null | undefined; }) => Promise<...>

getPageEdges()

(nodeId: string, direction?: "both" | "out" | "in") => Promise<{ createdAt: string; fromId: string; toId: string; edgeType: "depends_on" | "implements" | "relates_to" | "documents"; weight: number | null; }[]>

getNeighbors()

(nodeId: string, edgeType?: "depends_on" | "implements" | "relates_to" | "documents" | undefined) => Promise<{ id: string; createdAt: string; metadataJson: string | null; nodeType: "task" | "file" | "doc" | "concept"; label: string; }[]>

removePageEdge()

(fromId: string, toId: string, edgeType: "depends_on" | "implements" | "relates_to" | "documents") => Promise<void>

getBrainAccessor()

Factory: get a BrainDataAccessor backed by the brain.db singleton. Signature
(cwd?: string | undefined) => Promise<BrainDataAccessor>

setEmbeddingProvider()

Register an embedding provider for the brain system. Validates that the provider’s dimensions match the vec0 table. Signature
(provider: EmbeddingProvider) => void
Throws
  • Error if provider dimensions do not match EMBEDDING_DIMENSIONS

getEmbeddingProvider()

Get the currently registered embedding provider, or null. Signature
() => EmbeddingProvider | null

clearEmbeddingProvider()

Clear the current embedding provider (useful for testing). Signature
() => void

embedText()

Embed text into a float vector using the registered provider. Returns null when no provider is set or not available (FTS5-only fallback). Signature
(text: string) => Promise<Float32Array<ArrayBufferLike> | null>

isEmbeddingAvailable()

Check whether embedding is currently available. Signature
() => boolean

searchSimilar(query, projectRoot, limit)

Search for entries similar to a query string using vector similarity. 1. Embeds the query text via the registered embedding provider. 2. Runs KNN query against brain_embeddings vec0 table. 3. Joins with observation/decision/pattern/learning tables for full entries. Returns empty array when embedding is unavailable (graceful fallback). Signature
(query: string, projectRoot: string, limit?: number | undefined) => Promise<SimilarityResult[]>
Parameters
NameTypeDescription
querystringText to find similar entries for
projectRootstringProject root directory
limit: number | undefinedMaximum results to return (default 10)
Returns — Array of similar entries ranked by distance (ascending)

ensureFts5Tables()

Create FTS5 virtual tables and content-sync triggers if they don’t exist. Uses content= to sync from main tables, so inserts to main tables auto-populate FTS. UPDATE/DELETE require triggers. T5130 Signature
(nativeDb: DatabaseSync) => boolean

rebuildFts5Index()

Rebuild FTS5 indexes from the content tables. Useful after bulk inserts that bypass triggers. T5130 Signature
(nativeDb: DatabaseSync) => void

searchBrain()

Unified search across all BRAIN memory tables. Uses FTS5 MATCH for full-text search with BM25 ranking when available, falls back to LIKE queries otherwise. T5130 Signature
(projectRoot: string, query: string, options?: BrainSearchOptions | undefined) => Promise<BrainSearchResult>

resetFts5Cache()

Reset the cached FTS5 availability flag. Used in tests to force re-detection. Signature
() => void

hybridSearch(query, projectRoot, options)

Hybrid search across FTS5, vector similarity, and graph neighbors. 1. Runs FTS5 search via existing searchBrain. 2. Runs vector similarity via searchSimilar (if available). 3. Runs graph neighbor expansion via getNeighbors (if query matches a node). 4. Normalizes scores to 0-1 using min-max normalization. 5. Combines with configurable weights. 6. Deduplicates by ID, keeping highest combined score. 7. Returns top-N sorted by score descending. Graceful fallback: if vec unavailable, redistributes weight to FTS5. Signature
(query: string, projectRoot: string, options?: HybridSearchOptions | undefined) => Promise<HybridResult[]>
Parameters
NameTypeDescription
querystringSearch query text
projectRootstringProject root directory
options: HybridSearchOptions | undefinedWeight and limit configuration
Returns — Array of hybrid results ranked by combined score

getInjectionTemplateContent()

Get the CLEO-INJECTION.md template content from the package templates/ directory. Returns null if the template file is not found. Signature
() => string | null

ensureInjection()

Full injection refresh: strip legacy blocks, inject CAAMP content, install global template, create hub. Replaces initInjection from init.ts with a ScaffoldResult return type. Target architecture: CLAUDE.md/GEMINI.md - AGENTS.md (via injectAll) AGENTS.md - ~/.cleo/templates/CLEO-INJECTION.md + .cleo/project-context.json T4682 Signature
(projectRoot: string) => Promise<ScaffoldResult>

buildContributorInjectionBlock()

Build a smart, contextual contributor block for AGENTS.md injection. Returns null if this is not a contributor project. The block is INFORMATIONAL, not prescriptive. It tells agents: - This is the CLEO source repo (contributor project) - cleo-dev is available (or not, with reason) - Prefer cleo-dev for unreleased features, but fall back to cleo if the dev build is broken or unavailable This avoids the trap where a hardcoded “ALWAYS use cleo-dev” instruction sends agents into a loop when the dev build has compile errors. Signature
(projectRoot: string) => string | null

checkInjection()

Verify injection health: AGENTS.md exists, has CAAMP markers, markers are balanced, and references resolve. Combines logic from doctor/checks.ts checkAgentsMdHub, checkCaampMarkerIntegrity, and checkAtReferenceTargetExists. Signature
(projectRoot: string) => InjectionCheckResult

fileExists()

Check if a file exists and is readable. Signature
(path: string) => Promise<boolean>

stripCLEOBlocks()

Strip legacy !— CLEO:START —…!— CLEO:END — blocks from a file. Called before CAAMP injection to prevent competing blocks. Signature
(filePath: string) => Promise<void>

removeCleoFromRootGitignore()

Remove .cleo/ or .cleo entries from the project root .gitignore. Signature
(projectRoot: string) => Promise<{ removed: boolean; }>

getPackageRoot()

Resolve the package root directory (where schemas/ and templates/ live). scaffold.ts lives in packages/core/src/, so 1 level up reaches the package root. Signature
() => string

getGitignoreContent()

Load the gitignore template from the package’s templates/ directory. Falls back to embedded content if file not found. Signature
() => string

getCleoVersion()

Read CLEO version from package.json. Signature
() => string

createDefaultConfig()

Signature
() => Record<string, unknown>

ensureCleoStructure()

Create .cleo/ directory and all required subdirectories. Idempotent: skips directories that already exist. Signature
(projectRoot: string) => Promise<ScaffoldResult>

ensureGitignore()

Create or repair .cleo/.gitignore from template. Idempotent: skips if file already exists with correct content. Signature
(projectRoot: string) => Promise<ScaffoldResult>

ensureConfig()

Create default config.json if missing. Idempotent: skips if file already exists. Signature
(projectRoot: string, opts?: { force?: boolean | undefined; } | undefined) => Promise<ScaffoldResult>

ensureProjectInfo()

Create or refresh project-info.json. Idempotent: skips if file already exists (unless force). Signature
(projectRoot: string, opts?: { force?: boolean | undefined; } | undefined) => Promise<ScaffoldResult>

ensureContributorMcp()

Ensure .mcp.json contains a cleo-dev server entry pointing to the local build. Only runs when isCleoContributorProject() is true (ADR-029). Writes the server entry: cleo-dev → node /dist/mcp/index.js This ensures Claude Code loads the LOCAL dev build MCP server for this project, not the published cleocode/cleolatest. Idempotent: preserves other entries. Signature
(projectRoot: string) => Promise<ScaffoldResult>

ensureProjectContext()

Detect and write project-context.json. Idempotent: skips if file exists and is less than staleDays old (default: 30). Signature
(projectRoot: string, opts?: { force?: boolean | undefined; staleDays?: number | undefined; } | undefined) => Promise<ScaffoldResult>

ensureCleoGitRepo()

Initialize isolated .cleo/.git checkpoint repository. Idempotent: skips if .cleo/.git already exists. Signature
(projectRoot: string) => Promise<ScaffoldResult>

ensureSqliteDb()

Create SQLite database if missing. Idempotent: skips if tasks.db already exists. Signature
(projectRoot: string) => Promise<ScaffoldResult>

checkCleoStructure()

Verify all required .cleo/ subdirectories exist. Signature
(projectRoot: string) => CheckResult

checkGitignore()

Verify .cleo/.gitignore exists and matches template. Signature
(projectRoot: string) => CheckResult

checkConfig()

Verify config.json exists and is valid JSON. Signature
(projectRoot: string) => CheckResult

checkProjectInfo()

Verify project-info.json exists with required fields. Signature
(projectRoot: string) => CheckResult

checkProjectContext()

Verify project-context.json exists and is not stale (default: 30 days). Signature
(projectRoot: string, staleDays?: number) => CheckResult

checkCleoGitRepo()

Verify .cleo/.git checkpoint repository exists. Signature
(projectRoot: string) => CheckResult

checkSqliteDb()

Verify .cleo/tasks.db exists and is non-empty. Signature
(projectRoot: string) => CheckResult

ensureBrainDb()

Create brain.db if missing. Idempotent: skips if brain.db already exists. Signature
(projectRoot: string) => Promise<ScaffoldResult>

checkBrainDb()

Verify .cleo/brain.db exists and is non-empty. Signature
(projectRoot: string) => CheckResult

checkMemoryBridge()

Verify .cleo/memory-bridge.md exists. Warning level if missing (not failure) — it is auto-generated. Signature
(projectRoot: string) => CheckResult

ensureGlobalHome()

Ensure the global ~/.cleo/ home directory and its required subdirectories exist. Idempotent: skips directories that already exist. This is the SSoT for global home scaffolding, replacing raw mkdirSync calls that were previously scattered across global-bootstrap.ts. Signature
() => Promise<ScaffoldResult>

ensureGlobalTemplates()

Ensure the global CLEO injection template is installed. Delegates to injection.ts for the template content, but owns the filesystem write to maintain SSoT for scaffolding. Idempotent: skips if the template already exists with correct content. Signature
() => Promise<ScaffoldResult>

ensureGlobalScaffold()

Perform a complete global scaffold operation: ensure home, schemas, and templates are all present and current. This is the single entry point for global infrastructure scaffolding. Used by: - MCP startup (via startupHealthCheck in health.ts) - init (for first-time global setup) - upgrade (for global repair) Signature
() => Promise<{ home: ScaffoldResult; schemas: { installed: number; updated: number; total: number; }; templates: ScaffoldResult; }>

checkGlobalHome()

Check that the global ~/.cleo/ home and its required subdirectories exist. Read-only: no side effects. Signature
() => CheckResult

checkGlobalTemplates()

Check that the global injection template is present and current. Read-only: no side effects. Signature
() => CheckResult

checkLogDir()

Check that the project log directory exists. Read-only: no side effects. Signature
(projectRoot: string) => CheckResult

getMcpServerName()

Resolve MCP server name by channel. Signature
(env: McpEnvMode) => string

detectEnvMode()

Detect the current CLEO environment mode by reading ~/.cleo/VERSION. The VERSION file format: Line 1: version number Lines 2+: key=value pairs (mode, source, etc.) T4584 Signature
() => McpEnvMode

generateMcpServerEntry()

Generate the MCP server entry for the cleo server based on env mode. Returns a config object compatible with CAAMP’s McpServerConfig: - dev-ts: command: ‘node’, args: [‘/dist/mcp/index.js’] - prod-npm stable: command: ‘npx’, args: [‘-y’, ‘cleocode/cleolatest’, ‘mcp’] - prod-npm beta: command: ‘npx’, args: [‘-y’, ‘cleocode/cleobeta’, ‘mcp’] T4584 Signature
(env: McpEnvMode) => Record<string, unknown>

ensureGitHooks()

Install or update managed git hooks from templates/git-hooks/ into .git/hooks/. Handles: - No .git directory (skips gracefully) - No source templates directory (skips gracefully) - Hooks already installed (skips unless force) - Sets executable permissions on installed hooks Signature
(projectRoot: string, opts?: EnsureGitHooksOptions | undefined) => Promise<ScaffoldResult>

checkGitHooks()

Verify managed hooks are installed and current. Compares installed hooks in .git/hooks/ against source templates in the package’s templates/git-hooks/ directory. Returns per-hook status including whether the hook is installed and whether its content matches the source. Signature
(projectRoot: string) => Promise<HookCheckResult[]>

toTaskFileExt()

Convert a TaskFile (from contracts) to the looser TaskFileExt shape. Accepts any object with at least the basic TaskFileExt structure. The runtime object is the same reference — this only changes the TS type. Signature
<T extends { _meta?: object; tasks?: unknown[]; focus?: object; lastUpdated?: string; }>(taskFile: T) => TaskFileExt

recordDecision()

Record a decision to the audit trail. Appends a JSON line to .cleo/audit/decisions.jsonl. Throws if required params are missing. Signature
(projectRoot: string, params: RecordDecisionParams) => Promise<DecisionRecord>

getDecisionLog()

Read the decision log, optionally filtered by sessionId and/or taskId. Signature
(projectRoot: string, params?: DecisionLogParams | undefined) => Promise<DecisionRecord[]>

computeHandoff()

Compute handoff data for a session. Gathers all session statistics and auto-computes structured state. Signature
(projectRoot: string, options: ComputeHandoffOptions) => Promise<HandoffData>

persistHandoff()

Persist handoff data to a session. Signature
(projectRoot: string, sessionId: string, handoff: HandoffData) => Promise<void>

getHandoff()

Get handoff data for a session. Signature
(projectRoot: string, sessionId: string) => Promise<HandoffData | null>

getLastHandoff()

Get handoff data for the most recent ended session. Filters by scope if provided. Signature
(projectRoot: string, scope?: { type: string; epicId?: string | undefined; rootTaskId?: string | undefined; } | undefined) => Promise<{ sessionId: string; handoff: HandoffData; } | null>

computeDebrief()

Compute rich debrief data for a session. Builds on computeHandoff() and adds decisions, git state, chain position. T4959 Signature
(projectRoot: string, options: ComputeDebriefOptions) => Promise<DebriefData>

generateMemoryBridgeContent()

Generate memory bridge content from brain.db. Returns the markdown string (does not write to disk). Signature
(projectRoot: string, config?: Partial<MemoryBridgeConfig> | undefined) => Promise<string>

writeMemoryBridge()

Write memory bridge content to .cleo/memory-bridge.md. Signature
(projectRoot: string, config?: Partial<MemoryBridgeConfig> | undefined) => Promise<{ path: string; written: boolean; }>

refreshMemoryBridge()

Best-effort refresh: call from session.end, tasks.complete, or memory.observe. Never throws. Signature
(projectRoot: string) => Promise<void>

detectLegacyAgentOutputs(projectRoot, cleoDir)

Detect legacy agent-output directories in a project. Read-only check — never modifies the filesystem. Signature
(projectRoot: string, cleoDir: string) => LegacyDetectionResult
Parameters
NameTypeDescription
projectRootstringAbsolute path to project root
cleoDirstringAbsolute path to .cleo/ directory

migrateAgentOutputs(projectRoot, cleoDir)

Run the full agent-outputs migration. Copies files from all legacy locations into .cleo/agent-outputs/, merges MANIFEST.jsonl entries with path rewriting and deduplication, updates config.json, and removes legacy directories. Safe to call when no legacy directories exist (returns early). Safe to call when canonical directory already exists (merges). Signature
(projectRoot: string, cleoDir: string) => AgentOutputsMigrationResult
Parameters
NameTypeDescription
projectRootstringAbsolute path to project root
cleoDirstringAbsolute path to .cleo/ directory

migrateJsonToSqlite()

Migrate projects from legacy JSON registry to nexus.db. For each project entry in projects-registry.json: - Reads target/.cleo/project-info.json for a stable UUID (projectId) - Falls back to randomUUID() if project-info.json is absent - Upserts into project_registry (on conflict by projectHash → update path/name/lastSeen) On success, renames the JSON file to .migrated. Signature
() => Promise<number>
Returns — Number of projects migrated.

getNexusHome()

Get path to the NEXUS home directory (cache, etc.). Signature
() => string

getNexusCacheDir()

Get path to the NEXUS cache directory. Signature
() => string

getRegistryPath()

Deprecated: Use nexus.db via getNexusDb() instead. Retained for JSON-to-SQLite migration.
Get path to the legacy projects registry JSON file. Signature
() => string

readRegistry()

Read all projects from nexus.db and return as a NexusRegistryFile. Compatibility wrapper for consumers that expect the legacy JSON shape. Returns null if nexus.db has not been initialized yet. Signature
() => Promise<NexusRegistryFile | null>

readRegistryRequired()

Read the global registry, throwing if not initialized. Signature
() => Promise<NexusRegistryFile>

nexusInit()

Initialize the NEXUS directory structure and nexus.db. Idempotent — safe to call multiple times. Migrates legacy JSON registry on first run if present. Signature
() => Promise<void>

nexusRegister()

Register a project in the global registry (nexus.db). Signature
(projectPath: string, name?: string | undefined, permissions?: NexusPermissionLevel) => Promise<string>
Returns — The project hash.

nexusUnregister()

Unregister a project from the global registry. Signature
(nameOrHash: string) => Promise<void>

nexusList()

List all registered projects. Signature
() => Promise<NexusProject[]>

nexusGetProject()

Get a project by name or hash. Returns null if not found. Signature
(nameOrHash: string) => Promise<NexusProject | null>

nexusProjectExists()

Check if a project exists in the registry. Signature
(nameOrHash: string) => Promise<boolean>

nexusSync()

Sync project metadata (task count, labels) for a registered project. Signature
(nameOrHash: string) => Promise<void>

nexusSyncAll()

Sync all registered projects. Signature
() => Promise<{ synced: number; failed: number; }>
Returns — Counts of synced and failed projects.

nexusSetPermission()

Update a project’s permission level in the registry. Used by permissions.ts to avoid direct JSON file writes. Signature
(nameOrHash: string, permission: NexusPermissionLevel) => Promise<void>

nexusReconcile()

Reconcile the current project’s identity with the global nexus registry. 4-scenario policy: 1. projectId in registry + path matches → update lastSeen, return status:‘ok’ 2. projectId in registry + path changed → update path+hash, return status:‘path_updated’ 3. projectId not in registry → auto-register, return status:‘auto_registered’ 4. projectHash matches but different projectId → throw CleoError (identity conflict) Uses projectId as the stable identifier across project moves, since projectHash is derived from the absolute path and changes when moved. T5368 Signature
(projectRoot: string) => Promise<{ status: "ok" | "path_updated" | "auto_registered"; oldPath?: string | undefined; newPath?: string | undefined; }>

analyzeStack()

Signature
(projectRoot: string, projectContext: ProjectContext) => StackAnalysis

analyzeArchitecture()

Signature
(projectRoot: string, _projectContext: ProjectContext) => ArchAnalysis

analyzeStructure()

Signature
(projectRoot: string) => StructureAnalysis

analyzeConventions()

Signature
(projectRoot: string, projectContext: ProjectContext) => ConventionAnalysis

analyzeTesting()

Signature
(projectRoot: string, projectContext: ProjectContext) => TestingAnalysis

analyzeIntegrations()

Signature
(projectRoot: string, _projectContext: ProjectContext) => IntegrationAnalysis

analyzeConcerns()

Signature
(projectRoot: string) => ConcernAnalysis

storePattern()

Store a new pattern. If a similar pattern already exists (same type + matching text), increments frequency. T4768, T5241 Signature
(projectRoot: string, params: StorePatternParams) => Promise<{ examples: any; id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; ... 8 more ...; extractedAt: string; }>

searchPatterns()

Search patterns by criteria. T4768, T5241 Signature
(projectRoot: string, params?: SearchPatternParams) => Promise<{ examples: any; id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; ... 8 more ...; extractedAt: string; }[]>

patternStats()

Get pattern statistics. T4768, T5241 Signature
(projectRoot: string) => Promise<{ total: number; byType: Record<string, number>; byImpact: Record<string, number>; highestFrequency: { pattern: string; frequency: number; } | null; }>

storeLearning()

Store a new learning. T4769, T5241 Signature
(projectRoot: string, params: StoreLearningParams) => Promise<{ applicableTypes: any; id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; }>

searchLearnings()

Search learnings by criteria. Results sorted by confidence (highest first). T4769, T5241 Signature
(projectRoot: string, params?: SearchLearningParams) => Promise<{ applicableTypes: any; id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; }[]>

learningStats()

Get learning statistics. T4769, T5241 Signature
(projectRoot: string) => Promise<{ total: number; actionable: number; averageConfidence: number; bySource: Record<string, number>; highConfidence: number; lowConfidence: number; }>

searchBrainCompact(projectRoot, params)

Token-efficient compact search across BRAIN tables. Returns index-level hits (~50 tokens per result). Delegates to searchBrain() from brain-search.ts for FTS5/LIKE search, then projects results to a compact format with optional date filtering. Signature
(projectRoot: string, params: SearchBrainCompactParams) => Promise<SearchBrainCompactResult>
Parameters
NameTypeDescription
projectRootstringProject root directory
paramsSearchBrainCompactParamsSearch parameters
Returns — Compact search results with token estimate

timelineBrain(projectRoot, params)

Get chronological context around an anchor entry. Fetches the anchor’s full data, then queries all 4 BRAIN tables via UNION ALL to find chronological neighbors. Signature
(projectRoot: string, params: TimelineBrainParams) => Promise<TimelineBrainResult>
Parameters
NameTypeDescription
projectRootstringProject root directory
paramsTimelineBrainParamsTimeline parameters with anchor ID and depth
Returns — Anchor entry data with surrounding chronological entries

fetchBrainEntries(projectRoot, params)

Batch-fetch full details by IDs. Groups IDs by prefix to query the correct tables via BrainDataAccessor. Signature
(projectRoot: string, params: FetchBrainEntriesParams) => Promise<FetchBrainEntriesResult>
Parameters
NameTypeDescription
projectRootstringProject root directory
paramsFetchBrainEntriesParamsFetch parameters with IDs
Returns — Full entry data for each found ID, plus not-found list

observeBrain(projectRoot, params)

Save an observation to the BRAIN observations table. Replaces the external claude-mem save_observation pattern. Auto-classifies type from text if not provided. Generates a unique ID with O- prefix + base36 timestamp. Signature
(projectRoot: string, params: ObserveBrainParams) => Promise<ObserveBrainResult>
Parameters
NameTypeDescription
projectRootstringProject root directory
paramsObserveBrainParamsObservation data
Returns — Created observation ID, type, and timestamp

populateEmbeddings(projectRoot, options)

Backfill embeddings for existing observations that lack them. Iterates through observations not yet in brain_embeddings and generates vectors using the registered embedding provider. Processes in batches to avoid memory pressure. Signature
(projectRoot: string, options?: { batchSize?: number | undefined; } | undefined) => Promise<PopulateEmbeddingsResult>
Parameters
NameTypeDescription
projectRootstringProject root directory
options: \{ batchSize?: number | undefined; \} | undefinedOptional batch size configuration
Returns — Count of processed and skipped observations

storeMapToBrain()

Signature
(projectRoot: string, result: CodebaseMapResult) => Promise<{ patternsStored: number; learningsStored: number; observationsStored: number; }>

mapCodebase()

Signature
(projectRoot: string, options?: MapCodebaseOptions | undefined) => Promise<CodebaseMapResult>

isValidAdapter()

Validate that a loaded module export implements the CLEOProviderAdapter interface. Checks for required methods and properties without relying on instanceof. Signature
(adapter: unknown) => adapter is CLEOProviderAdapter

loadAdapterFromManifest(manifest)

Dynamically load and instantiate an adapter from its manifest. Uses the manifest’s packagePath to resolve the adapter module, then looks for a createAdapter() factory or a default export class. Signature
(manifest: AdapterManifest) => Promise<CLEOProviderAdapter>
Parameters
NameTypeDescription
manifestAdapterManifestThe adapter manifest with a resolved packagePath
Returns — A CLEOProviderAdapter instance Throws
  • If the module cannot be loaded or does not export a valid adapter

discoverAdapterManifests()

Scan the packages/adapters/ directory for adapter packages. Each adapter must have a manifest.json at its root. Signature
(projectRoot: string) => AdapterManifest[]

detectProvider()

Detect whether a provider is active in the current environment by checking its detection patterns. Signature
(patterns: DetectionPattern[]) => boolean

AdapterManager

Central adapter manager. Singleton per process. Lifecycle: 1. discover() — scan for adapter packages and their manifests 2. activate(id) — load, initialize, and set as active adapter 3. getActive() — return the current active adapter 4. dispose() — clean up all initialized adapters Signature
typeof AdapterManager
Methods

getInstance()

(projectRoot: string) => AdapterManager

resetInstance()

Reset singleton (for testing).
() => void

discover()

Discover adapter manifests from packages/adapters/. Returns manifests found (does not load adapter code yet).
() => AdapterManifest[]

detectActive()

Auto-detect which adapters match the current environment and return their manifest IDs.
() => string[]

activate()

Load and initialize an adapter by manifest ID. Dynamically imports from the manifest’s packagePath — no hardcoded adapters.
(adapterId: string) => Promise<CLEOProviderAdapter>

getActive()

Get the currently active adapter, or null if none.
() => CLEOProviderAdapter | null

getActiveId()

Get the active adapter’s ID, or null.
() => string | null

get()

Get a specific adapter by ID.
(adapterId: string) => CLEOProviderAdapter | null

getManifest()

Get the manifest for a specific adapter.
(adapterId: string) => AdapterManifest | null

listAdapters()

List all known adapters with summary info.
() => AdapterInfo[]

healthCheckAll()

Run health check on all initialized adapters.
() => Promise<Map<string, AdapterHealthStatus>>

healthCheck()

Health check a single adapter.
(adapterId: string) => Promise<AdapterHealthStatus>

dispose()

Dispose all initialized adapters.
() => Promise<void>

disposeAdapter()

Dispose a single adapter.
(adapterId: string) => Promise<void>

wireAdapterHooks()

Wire an adapter’s hook event map into CLEO’s HookRegistry. Creates bridging handlers at priority 50 for each mapped event.
(adapterId: string, adapter: CLEOProviderAdapter) => Promise<void>

cleanupAdapterHooks()

Clean up hook registrations for an adapter.
(adapterId: string, adapter: CLEOProviderAdapter) => Promise<void>

initAgentDefinition()

Install cleo-subagent agent definition to ~/.agents/agents/. T4685 Signature
(created: string[], warnings: string[]) => Promise<void>

initMcpServer()

Install MCP server config to all detected providers via CAAMP. T4706 Signature
(projectRoot: string, created: string[], warnings: string[]) => Promise<void>

initCoreSkills()

Install CLEO core skills to the canonical skills directory via CAAMP. T4707 T4689 Signature
(created: string[], warnings: string[]) => Promise<void>

initNexusRegistration()

Register/reconcile project with NEXUS. Uses nexusReconcile for idempotent handshake — auto-registers if new, updates path if moved, confirms identity if unchanged. T4684 T5368 Signature
(projectRoot: string, created: string[], warnings: string[]) => Promise<void>

installGitHubTemplates(projectRoot, created, skipped)

Install GitHub issue and PR templates to .github/ if a git repo exists but .github/ISSUE_TEMPLATE/ is not yet present. Idempotent: skips files that already exist. Never overwrites existing templates — the project owner’s customisations take precedence. Signature
(projectRoot: string, created: string[], skipped: string[]) => Promise<void>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root.
createdstring[]Array to push “created: …” log entries into.
skippedstring[]Array to push “skipped: …” log entries into.

updateDocs()

Run update-docs only: refresh all injections without reinitializing. Re-injects CLEO-INJECTION.md into all detected agent instruction files. T4686 Signature
() => Promise<InitResult>

initProject()

Run full project initialization. Creates the .cleo/ directory structure, installs schemas, templates, agent definitions, MCP server configs, skills, and registers with NEXUS. T4681 T4682 T4684 T4685 T4686 T4687 T4689 T4706 T4707 Signature
(opts?: InitOptions) => Promise<InitResult>

isAutoInitEnabled()

Check if auto-init is enabled via environment variable. T4789 Signature
() => boolean

ensureInitialized()

Check if a project is initialized and auto-init if configured. Returns initialized: true if ready, throws otherwise. T4789 Signature
(projectRoot?: string | undefined) => Promise<{ initialized: boolean; }>

getVersion()

Get the current CLEO/project version. Checks VERSION file, then package.json. T4789 Signature
(projectRoot?: string | undefined) => Promise<{ version: string; }>

bootstrapGlobalCleo()

Bootstrap the global CLEO directory structure and install templates. Creates: - ~/.cleo/templates/CLEO-INJECTION.md (from bundled template or injection content) - ~/.agents/AGENTS.md with CAAMP injection block This is idempotent — safe to call multiple times. Signature
(options?: BootstrapOptions | undefined) => Promise<BootstrapContext>

installMcpToProviders()

Install the CLEO MCP server config to all detected providers. Signature
(ctx: BootstrapContext) => Promise<void>

installSkillsGlobally()

Install CLEO core skills globally via CAAMP. Signature
(ctx: BootstrapContext) => Promise<void>

bootstrapCaamp()

Signature
() => void

exportTasks()

Export tasks to a portable format. Returns the formatted content and metadata. Signature
(params: ExportParams) => Promise<ExportResult>

importTasks()

Import tasks from an export file. Signature
(params: ImportParams) => Promise<ImportResult>

validateSyntax()

Validate a query string matches expected syntax. Signature
(query: string) => boolean

parseQuery()

Parse a query string into its components. Signature
(query: string, currentProject?: string | undefined) => NexusParsedQuery
Throws
  • CleoError with NEXUS_INVALID_SYNTAX for bad format.

getCurrentProject()

Get the current project name from context. Reads .cleo/project-info.json or falls back to directory name. Signature
() => string

resolveProjectPath()

Resolve a project name to its filesystem path. Handles special cases: ”.” (current), ”*” (wildcard marker). Signature
(projectName: string) => Promise<string>

resolveTask()

Resolve a query to task data. For wildcard queries, returns an array of matches from all projects. For named projects, returns a single task with project context. Signature
(query: string, currentProject?: string | undefined) => Promise<NexusResolvedTask | NexusResolvedTask[]>

getProjectFromQuery()

Extract the project name from a query without full resolution. Useful for permission checks before task lookup. Signature
(query: string, currentProject?: string | undefined) => string

extractKeywords()

Extract meaningful keywords from text (filters stop words and short tokens). Signature
(text: string) => string[]

discoverRelated()

Discover tasks related to a given task query across projects. Returns a structured result or throws on unrecoverable errors. Validation errors (bad syntax, wildcard) are returned as error objects so callers can wrap them in an appropriate engine error response. Signature
(taskQuery: string, method?: string, limit?: number) => Promise<NexusDiscoverResult | { error: { code: string; message: string; }; }>

searchAcrossProjects()

Search for tasks across all registered projects. Returns a structured result or throws on unrecoverable errors. Validation errors (bad pattern) are returned as error objects. Signature
(pattern: string, projectFilter?: string | undefined, limit?: number) => Promise<NexusSearchResult | { error: { code: string; message: string; }; }>

permissionLevel()

Convert a permission string to its numeric level. Returns 0 for invalid/unknown permissions. Signature
(permission: string) => number

getPermission()

Get the permission level for a registered project. Returns ‘read’ as default if the project has no explicit permission. Signature
(nameOrHash: string) => Promise<NexusPermissionLevel>

checkPermission()

Check if a project has sufficient permissions (non-throwing). Uses hierarchical comparison: execute = write = read. Signature
(nameOrHash: string, required: NexusPermissionLevel) => Promise<boolean>
Returns — true if the granted permission meets or exceeds the required level.

requirePermission()

Require a permission level or throw CleoError. Used as a guard at the start of cross-project operations. Signature
(nameOrHash: string, required: NexusPermissionLevel, operationName?: string) => Promise<void>

checkPermissionDetail()

Full permission check returning a structured result. Signature
(nameOrHash: string, required: NexusPermissionLevel) => Promise<PermissionCheckResult>

setPermission()

Set the permission level for a project. Validates the permission value and updates the registry. T4574 Signature
(nameOrHash: string, permission: NexusPermissionLevel) => Promise<void>

canRead()

Convenience: check read access. Signature
(nameOrHash: string) => Promise<boolean>

canWrite()

Convenience: check write access. Signature
(nameOrHash: string) => Promise<boolean>

canExecute()

Convenience: check execute access. Signature
(nameOrHash: string) => Promise<boolean>

matchesPattern()

Match a file path against a glob-like pattern. Supports: ’*’ (single segment wildcard), ’**’ (recursive wildcard), and trailing ’/’ for directory matching. T4883 Signature
(filePath: string, pattern: string) => boolean

getSharingStatus()

Get the sharing status: which .cleo/ files are tracked vs ignored. T4883 Signature
(cwd?: string | undefined) => Promise<SharingStatus>

syncGitignore()

Sync the project .gitignore to match the sharing config. Adds/updates a managed section between CLEO markers. T4883 Signature
(cwd?: string | undefined) => Promise<{ updated: boolean; entriesCount: number; }>

invalidateDepsCache()

Invalidate the cached TaskFile (call after writes). T4659 T4654 Signature
() => void

buildGraph()

Build an adjacency graph from task dependencies. T4464 Signature
(tasks: Task[]) => Map<string, DepNode>

getDepsOverview()

Get dependency overview for all tasks. T4464 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<DepsOverviewResult>

getTaskDeps()

Get dependencies for a specific task. T4464 Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskDepsResult>

topologicalSort()

Topological sort of tasks respecting dependencies. Returns tasks in execution order. Throws on cycles. T4464 Signature
(tasks: Task[]) => Task[]

getExecutionWaves()

Group tasks into parallelizable execution waves. T4464 Signature
(epicId?: string | undefined, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ExecutionWave[]>

getCriticalPath()

Find the critical path (longest dependency chain) from a task. T4464 Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CriticalPathResult>

getImpact()

Find all tasks affected by changes to a given task. T4464 Signature
(taskId: string, maxDepth?: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<string[]>

detectCycles()

Detect circular dependencies in the task graph. T4464 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CycleResult>

getTaskTree()

Build task hierarchy tree. T4464 Signature
(rootId?: string | undefined, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TreeNode[]>

addRelation()

Manage task relationships (relates/blocks). T4464 Signature
(taskId: string, relatedId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ taskId: string; relatedId: string; }>

buildDependencyGraph()

Build a dependency graph for a set of tasks. Returns a Map from task ID to the set of task IDs it depends on. Signature
(tasks: Task[]) => Map<string, Set<string>>

detectCircularDependencies(tasks, graph)

Detect circular dependencies using DFS traversal. Signature
(tasks: Task[], graph?: Map<string, Set<string>> | undefined) => CircularDependency[]
Parameters
NameTypeDescription
tasksTask[]The set of tasks to analyze
graph: Map&lt;stringPre-built dependency graph (optional; built from tasks if not provided)
Returns — Array of circular dependency cycles (each cycle is an array of task IDs)

findMissingDependencies(children, allTasks)

Find missing dependencies — deps that reference tasks outside the epic that are not yet completed. Signature
(children: Task[], allTasks: Task[]) => MissingDependency[]
Parameters
NameTypeDescription
childrenTask[]Child tasks of the epic
allTasksTask[]All tasks in the project (to check if deps are completed elsewhere)
Returns — Array of missing dependency references

analyzeDependencies(children, allTasks)

Perform full dependency analysis for an epic’s children. Combines dependency graph building, circular detection, and missing dep identification into a single analysis result. Signature
(children: Task[], allTasks: Task[]) => DependencyAnalysis
Parameters
NameTypeDescription
childrenTask[]Child tasks of the epic
allTasksTask[]All tasks in the project
Returns — Complete dependency analysis

countManifestEntries(projectRoot)

Count manifest entries from MANIFEST.jsonl. Signature
(projectRoot: string) => number
Parameters
NameTypeDescription
projectRootstringThe project root directory
Returns — Number of manifest entries

estimateContext(taskCount, projectRoot, epicId)

Estimate context usage for orchestration. Signature
(taskCount: number, projectRoot: string, epicId?: string | undefined) => ContextEstimation
Parameters
NameTypeDescription
taskCountnumberNumber of tasks to estimate for
projectRootstringThe project root directory
epicId: string | undefinedOptional epic ID for scoped estimation
Returns — Context estimation with recommendations

computeWaves()

Compute execution waves using topological sort. Signature
(tasks: Task[]) => Wave[]

getEnrichedWaves()

Get enriched wave data for an epic. Signature
(epicId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; waves: EnrichedWave[]; totalWaves: number; totalTasks: number; }>

countByStatus()

Count tasks by status. Signature
(tasks: Task[]) => StatusCounts

computeEpicStatus(epicId, epicTitle, children)

Compute epic-specific status. Signature
(epicId: string, epicTitle: string, children: Task[]) => EpicStatus
Parameters
NameTypeDescription
epicIdstringThe epic task ID
epicTitlestringThe epic title
childrenTask[]Child tasks of the epic
Returns — Epic status with wave information

computeOverallStatus(tasks)

Compute overall orchestration status across all tasks. Signature
(tasks: Task[]) => OverallStatus
Parameters
NameTypeDescription
tasksTask[]All tasks in the project
Returns — Overall status with epic count

computeProgress(tasks)

Compute progress metrics for all tasks. Signature
(tasks: Task[]) => ProgressMetrics
Parameters
NameTypeDescription
tasksTask[]All tasks to measure
Returns — Progress metrics with completion percentage

computeStartupSummary(epicId, epicTitle, children, readyCount)

Compute startup summary for an epic. Signature
(epicId: string, epicTitle: string, children: Task[], readyCount: number) => StartupSummary
Parameters
NameTypeDescription
epicIdstringThe epic task ID
epicTitlestringThe epic title
childrenTask[]Child tasks of the epic
readyCountnumberNumber of ready tasks
Returns — Startup summary with wave information

startOrchestration()

Start an orchestrator session for an epic. T4466 Signature
(epicId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<OrchestratorSession>

analyzeEpic()

Analyze an epic’s dependency structure. T4466 Signature
(epicId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<AnalysisResult>

getReadyTasks()

Get parallel-safe ready tasks for an epic. T4466 Signature
(epicId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskReadiness[]>

getNextTask()

Get the next task to work on for an epic. T4466 Signature
(epicId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskReadiness | null>

prepareSpawn()

Prepare a spawn context for a subagent. T4466 Signature
(taskId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<SpawnContext>

validateSpawnOutput()

Validate a subagent’s output. T4466 Signature
(_taskId: string, output: { file?: string | undefined; manifestEntry?: boolean | undefined; }) => Promise<{ valid: boolean; errors: string[]; }>

getOrchestratorContext()

Get orchestrator context summary. T4466 Signature
(epicId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; epicTitle: string; totalTasks: number; completed: number; inProgress: number; blocked: number; pending: number; completionPercent: number; }>

autoDispatch()

Auto-dispatch: determine the protocol for a task based on metadata. T4466 Signature
(task: Task) => string

resolveTokens()

Resolve tokens in a prompt string. T4466 Signature
(prompt: string, context: Record<string, string>) => { resolved: string; unresolved: string[]; }

bridgeSessionToMemory(projectRoot, sessionData)

Bridge session end data to brain.db as an observation. Builds a summary text from the session metadata and saves it as a ‘change’ observation with source_type ‘agent’. Signature
(projectRoot: string, sessionData: SessionBridgeData) => Promise<void>
Parameters
NameTypeDescription
projectRootstringProject root directory for brain.db resolution
sessionDataSessionBridgeDataSession metadata to record

storeDecision()

Store a new decision or update an existing one if a duplicate is found. Duplicate detection: same decision text (case-insensitive). T5155 Signature
(projectRoot: string, params: StoreDecisionParams) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }>

recallDecision()

Recall a specific decision by ID. T5155 Signature
(projectRoot: string, id: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; confidence: "high" | ... 1 more ... | "low"; ... 6 more ...; contextPhase: string | null; } | null>

searchDecisions()

Search decisions by type, confidence, outcome, and/or free-text query. Query searches across decision + rationale fields using LIKE. T5155 Signature
(projectRoot: string, params?: SearchDecisionParams) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }[]>

listDecisions()

List decisions with pagination. T5155 Signature
(projectRoot: string, params?: ListDecisionParams) => Promise<{ decisions: { id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }[]; total: number; }>

updateDecisionOutcome()

Update the outcome of a decision after learning from results. T5155 Signature
(projectRoot: string, id: string, outcome: "pending" | "success" | "failure" | "mixed" | null) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }>

extractTaskCompletionMemory()

Extract and store memory entries when a task is completed. - Always stores a learning for the completed task. - Stores a second learning if the task had dependencies. - Detects recurring label patterns across recent completed tasks and stores a success pattern when any label appears 3+ times. Signature
(projectRoot: string, task: Task, _parentTask?: Task | undefined) => Promise<void>

extractSessionEndMemory()

Extract and store memory entries when a session ends. - Stores a process decision summarising the session. - Stores a per-task learning for each completed task. - Stores a workflow pattern when 2+ completed tasks share a label. Signature
(projectRoot: string, sessionData: SessionBridgeData, taskDetails: Task[]) => Promise<void>

resolveTaskDetails()

Resolve an array of task IDs to their full Task objects. Tasks that cannot be found are silently excluded. Signature
(projectRoot: string, taskIds: string[]) => Promise<Task[]>

completeTask()

Complete a task by ID. Handles dependency checking and optional auto-completion of epics. T4461 Signature
(options: CompleteTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CompleteTaskResult>

updateTask()

Update a task’s fields. T4461 Signature
(options: UpdateTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<UpdateTaskResult>

getLinksByProvider()

Find all links for a given provider. Signature
(providerId: string, cwd?: string | undefined) => Promise<ExternalTaskLink[]>

getLinkByExternalId()

Find a link by provider + external ID. Signature
(providerId: string, externalId: string, cwd?: string | undefined) => Promise<ExternalTaskLink | null>

getLinksByTaskId()

Find all links for a given CLEO task. Signature
(taskId: string, cwd?: string | undefined) => Promise<ExternalTaskLink[]>
Create a new external task link. Signature
(params: { taskId: string; providerId: string; externalId: string; externalUrl?: string | undefined; externalTitle?: string | undefined; linkType: ExternalLinkType; syncDirection?: SyncDirection | undefined; metadata?: Record<...> | undefined; }, cwd?: string | undefined) => Promise<...>
Update the lastSyncAt and optionally the title/metadata for an existing link. Signature
(linkId: string, updates?: { externalTitle?: string | undefined; metadata?: Record<string, unknown> | undefined; } | undefined, cwd?: string | undefined) => Promise<void>

removeLinksByProvider()

Remove all links for a provider (used during provider deregistration). Signature
(providerId: string, cwd?: string | undefined) => Promise<number>

reconcile(externalTasks, options, accessor)

Reconcile external task state with CLEO’s authoritative task store. Signature
(externalTasks: ExternalTask[], options: ReconcileOptions, accessor?: DataAccessor | undefined) => Promise<ReconcileResult>
Parameters
NameTypeDescription
externalTasksExternalTask[]Normalized tasks from a provider adapter.
optionsReconcileOptionsReconciliation options.
accessor: DataAccessor | undefinedOptional DataAccessor override (for testing).
Returns — Reconciliation result with actions taken.

getArtifactHandler()

Get handler for an artifact type. T4552 Signature
(artifactType: ArtifactType) => ArtifactHandler | null

hasArtifactHandler()

Check if a handler is registered for an artifact type. T4552 Signature
(artifactType: string) => artifactType is ArtifactType

buildArtifact()

Build an artifact using the appropriate handler. T4552 Signature
(config: ArtifactConfig, dryRun?: boolean) => Promise<ArtifactResult>

validateArtifact()

Validate an artifact using the appropriate handler. T4552 Signature
(config: ArtifactConfig) => Promise<ArtifactResult>

publishArtifact()

Publish an artifact using the appropriate handler. T4552 Signature
(config: ArtifactConfig, dryRun?: boolean) => Promise<ArtifactResult>

getSupportedArtifactTypes()

Get all supported artifact types. T4552 Signature
() => ArtifactType[]

parseChangelogBlocks()

Parse [custom-log]…[/custom-log] blocks from a CHANGELOG section. Returns the extracted block content (tags stripped) and the content with tags+content removed. Signature
(content: string) => { customBlocks: string[]; strippedContent: string; }

writeChangelogSection()

Write or update a CHANGELOG.md section for a specific version. - If ## [VERSION] section exists: replaces it in-place. - If not: prepends as new section after any top-level # heading. - Custom block content (from [custom-log] blocks) is appended after generated content. - Section header format: ’## [VERSION] (YYYY-MM-DD)’ Signature
(version: string, generatedContent: string, customBlocks: string[], changelogPath: string) => Promise<void>

loadReleaseConfig()

Load release configuration with defaults. Signature
(cwd?: string | undefined) => ReleaseConfig

validateReleaseConfig()

Validate release configuration. Signature
(config: ReleaseConfig) => { valid: boolean; errors: string[]; warnings: string[]; }

getArtifactType()

Get artifact type from config. Signature
(cwd?: string | undefined) => string

getReleaseGates()

Get release gates from config. Signature
(cwd?: string | undefined) => ReleaseGate[]

getChangelogConfig()

Get changelog configuration. Signature
(cwd?: string | undefined) => { format: string; file: string; }

getDefaultGitFlowConfig()

Return the default GitFlow branch configuration. Signature
() => GitFlowConfig

getGitFlowConfig()

Merge caller-supplied GitFlow config with defaults. Signature
(config: ReleaseConfig) => GitFlowConfig

getDefaultChannelConfig()

Return the default channel configuration. Signature
() => ChannelConfig

getChannelConfig()

Merge caller-supplied channel config with defaults. Signature
(config: ReleaseConfig) => ChannelConfig

getPushMode()

Return the configured push mode, defaulting to ‘auto’. Signature
(config: ReleaseConfig) => PushMode

getDefaultChannelConfig()

Return the default branch-to-channel mapping. Signature
() => ChannelConfig

resolveChannelFromBranch()

Resolve the release channel for a given Git branch name. Resolution order: 1. Exact match in config.custom 2. Prefix match in config.custom 3. Exact match against config.main → ‘latest’ 4. Exact match against config.develop → ‘beta’ 5. Starts with ‘feature/’, ‘hotfix/’, ‘release/’, or config.feature → ‘alpha’ 6. Fallback → ‘alpha’ Signature
(branch: string, config?: ChannelConfig | undefined) => ReleaseChannel

channelToDistTag()

Map a release channel to its npm dist-tag string. Kept as an explicit function (rather than a direct cast) so that callers remain decoupled from the string values and the mapping can be extended without changing call sites. Signature
(channel: ReleaseChannel) => string

validateVersionChannel()

Validate that a version string satisfies the pre-release conventions for the given channel. Rules: - ‘latest’: version must NOT contain ’-’ (no pre-release suffix) - ‘beta’: version must contain ‘-beta’ or ‘-rc’ - ‘alpha’: version must contain ‘-alpha’, ‘-dev’, ‘-rc’, or ‘-beta’ Signature
(version: string, channel: ReleaseChannel) => ChannelValidationResult

describeChannel()

Return a human-readable description of the given release channel. Signature
(channel: ReleaseChannel) => string

getPlatformPath()

Get the output path for a CI platform. Signature
(platform: CIPlatform) => string

detectCIPlatform()

Detect the CI platform from the project. Signature
(projectDir?: string | undefined) => CIPlatform | null

generateCIConfig()

Generate CI config for a platform. Signature
(platform: CIPlatform, cwd?: string | undefined) => string

writeCIConfig()

Write CI config to the appropriate path. Signature
(platform: CIPlatform, options?: { projectDir?: string | undefined; dryRun?: boolean | undefined; }) => { action: string; path: string; content: string; }

validateCIConfig()

Validate an existing CI config. Signature
(platform: CIPlatform, projectDir?: string | undefined) => { valid: boolean; exists: boolean; errors: string[]; }

isGhCliAvailable()

Check if the gh CLI is available by attempting to run gh --version. Does NOT use which to remain cross-platform. Signature
() => boolean

extractRepoOwnerAndName()

Parse a GitHub remote URL (HTTPS or SSH) into owner and repo components. Returns null if the URL cannot be parsed. Supported formats: https://github.com/owner/repo.git https://github.com/owner/repo gitgithub.com:owner/repo.git gitgithub.com:owner/repo Signature
(remote: string) => RepoIdentity | null

detectBranchProtection()

Detect whether a branch has protection rules enabled. Strategy 1 (preferred): use gh api to query GitHub branch protection. Strategy 2 (fallback): use git push --dry-run and inspect stderr. Signature
(branch: string, remote: string, projectRoot?: string | undefined) => Promise<BranchProtectionResult>

buildPRBody()

Build the markdown body for a GitHub pull request. Signature
(opts: PRCreateOptions) => string

formatManualPRInstructions()

Format human-readable instructions for creating a PR manually. Signature
(opts: PRCreateOptions) => string

createPullRequest()

Create a GitHub pull request using the gh CLI, or return manual instructions if the CLI is unavailable or the operation fails. Signature
(opts: PRCreateOptions) => Promise<PRResult>

checkEpicCompleteness()

Check epic completeness for a set of release task IDs. Verifies all children of each referenced epic are included. Signature
(releaseTaskIds: string[], cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<EpicCompletenessResult>

checkDoubleListing()

Check if any tasks are listed in multiple releases. Signature
(releaseTaskIds: string[], existingReleases: { version: string; tasks: string[]; }[]) => DoubleListingResult

validateVersionFormat()

Validate version format (semver X.Y.Z or CalVer YYYY.M.patch, with optional pre-release). Signature
(version: string) => boolean

isCalVer()

Check if a version string is CalVer format. Signature
(version: string) => boolean

calculateNewVersion()

Calculate new version from current + bump type. Signature
(current: string, bump: string) => string

getVersionBumpConfig()

Get version bump configuration, mapping config field names to VersionBumpTarget. Signature
(cwd?: string | undefined) => VersionBumpTarget[]

isVersionBumpConfigured()

Check if version bump is configured. Signature
(cwd?: string | undefined) => boolean

bumpVersionFromConfig()

Bump version in all configured files. Signature
(newVersion: string, options?: { dryRun?: boolean | undefined; }, cwd?: string | undefined) => { results: BumpResult[]; allSuccess: boolean; }

prepareRelease()

Prepare a release (create a release manifest entry). T4788 Signature
(version: string, tasks: string[] | undefined, notes: string | undefined, loadTasksFn: () => Promise<ReleaseTaskRecord[]>, cwd?: string | undefined) => Promise<...>

generateReleaseChangelog()

Generate changelog for a release. T4788 Signature
(version: string, loadTasksFn: () => Promise<ReleaseTaskRecord[]>, cwd?: string | undefined) => Promise<{ version: string; changelog: string; taskCount: number; sections: Record<...>; }>

listManifestReleases()

List all releases. T4788 Signature
(optionsOrCwd?: string | ReleaseListOptions | undefined, cwd?: string | undefined) => Promise<{ releases: { version: string; status: string; createdAt: string; taskCount: number; }[]; total: number; filtered: number; latest?: string | undefined; page: LAFSPage; }>

showManifestRelease()

Show release details. T4788 Signature
(version: string, cwd?: string | undefined) => Promise<ReleaseManifest>

commitRelease()

Mark release as committed (metadata only). T4788 Signature
(version: string, cwd?: string | undefined) => Promise<{ version: string; status: string; committedAt: string; }>

tagRelease()

Mark release as tagged (metadata only). T4788 Signature
(version: string, cwd?: string | undefined) => Promise<{ version: string; status: string; taggedAt: string; }>

runReleaseGates()

Run release validation gates. T4788 T5586 Signature
(version: string, loadTasksFn: () => Promise<ReleaseTaskRecord[]>, cwd?: string | undefined, opts?: { dryRun?: boolean | undefined; } | undefined) => Promise<...>

cancelRelease()

Cancel and remove a release in draft or prepared state. Only releases that have not yet been committed to git can be cancelled. For committed/tagged/pushed releases, use rollbackRelease() instead. T5602 Signature
(version: string, projectRoot?: string | undefined) => Promise<{ success: boolean; message: string; version: string; }>

rollbackRelease()

Rollback a release. T4788 Signature
(version: string, reason?: string | undefined, cwd?: string | undefined) => Promise<{ version: string; previousStatus: string; status: string; reason: string; }>

pushRelease()

Push release to remote via git. Respects config.release.push policy: - remote: override default remote (fallback to ‘origin’) - requireCleanTree: verify git working tree is clean before push - allowedBranches: verify current branch is in the allowed list - enabled: if false and no explicit push flag, caller should skip T4788 T4276 Signature
(version: string, remote?: string | undefined, cwd?: string | undefined, opts?: { explicitPush?: boolean | undefined; mode?: PushMode | undefined; prBase?: string | undefined; epicId?: string | undefined; guided?: boolean | undefined; } | undefined) => Promise<...>

markReleasePushed()

Update release status after push, with optional provenance fields. T4788 T5580 Signature
(version: string, pushedAt: string, cwd?: string | undefined, provenance?: { commitSha?: string | undefined; gitTag?: string | undefined; } | undefined) => Promise<void>

migrateReleasesJsonToSqlite()

One-time migration: read .cleo/releases.json and insert each release into the release_manifests table. Renames the file to releases.json.migrated on success. T5580 Signature
(projectRoot?: string | undefined) => Promise<{ migrated: number; }>

gradeSession()

Grade a session by sessionId using the 5-dimension behavioral rubric. Signature
(sessionId: string, cwd?: string | undefined) => Promise<GradeResult>

readGrades()

Read past grade results from .cleo/metrics/GRADES.jsonl Signature
(sessionId?: string | undefined, cwd?: string | undefined) => Promise<GradeResult[]>

handleSessionStart()

Handle onSessionStart - capture initial session context Signature
(projectRoot: string, payload: OnSessionStartPayload) => Promise<void>

handleSessionEnd()

Handle onSessionEnd - capture session summary Signature
(projectRoot: string, payload: OnSessionEndPayload) => Promise<void>

handleToolStart()

Handle onToolStart (maps to task.start in CLEO) Signature
(projectRoot: string, payload: OnToolStartPayload) => Promise<void>

handleToolComplete()

Handle onToolComplete (maps to task.complete in CLEO) Signature
(projectRoot: string, payload: OnToolCompletePayload) => Promise<void>

handleError()

Handle onError - capture operation errors to BRAIN Includes infinite-loop guard: if the payload has _fromHook marker, the handler skips to prevent onError - observeBrain - onError loops. Additionally, ALL observeBrain errors are silently suppressed to prevent re-entrant hook firing. Signature
(projectRoot: string, payload: OnErrorPayload) => Promise<void>

handleFileChange()

Handle onFileChange - capture file changes to BRAIN Gated behind CLEO_BRAIN_CAPTURE_FILES=true env var. Deduplicates rapid writes to the same file within a 5-second window. Filters out .cleo/ internal files and test temp directories. Converts absolute paths to project-relative paths. Signature
(projectRoot: string, payload: OnFileChangePayload) => Promise<void>

handlePromptSubmit()

Handle onPromptSubmit - optionally capture prompt events to BRAIN No-op by default. Set CLEO_BRAIN_CAPTURE_MCP=true to enable. Signature
(projectRoot: string, payload: OnPromptSubmitPayload) => Promise<void>

handleResponseComplete()

Handle onResponseComplete - optionally capture response events to BRAIN No-op by default. Set CLEO_BRAIN_CAPTURE_MCP=true to enable. Signature
(projectRoot: string, payload: OnResponseCompletePayload) => Promise<void>

recordAssumption()

Record an assumption made during a session. Appends to .cleo/audit/assumptions.jsonl (creates dir if needed). Throws if required params are missing or invalid. Signature
(projectRoot: string, params: RecordAssumptionParams) => Promise<Omit<AssumptionRecord, "validatedAt"> & { timestamp: string; }>

linkMemoryToTask()

Link a memory entry to a task. T5156 Signature
(projectRoot: string, memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string, taskId: string, linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts") => Promise<...>

unlinkMemoryFromTask()

Remove a link between a memory entry and a task. T5156 Signature
(projectRoot: string, memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string, taskId: string, linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts") => Promise<...>
Get all memory entries linked to a specific task. T5156 Signature
(projectRoot: string, taskId: string) => Promise<{ createdAt: string; taskId: string; linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts"; memoryType: "decision" | "pattern" | "learning" | "observation"; memoryId: string; }[]>
Get all tasks linked to a specific memory entry. T5156 Signature
(projectRoot: string, memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string) => Promise<{ createdAt: string; taskId: string; linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts"; memoryType: "decision" | ... 2 more ... | "observation"; memoryId: string; }[]>
Batch create multiple links at once. T5156 Signature
(projectRoot: string, links: BulkLinkEntry[]) => Promise<{ created: number; skipped: number; }>

getLinkedDecisions()

Get all decisions linked to a task. Convenience method that fetches full decision rows. T5156 Signature
(projectRoot: string, taskId: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; confidence: "high" | ... 1 more ... | "low"; ... 6 more ...; contextPhase: string | null; }[]>

getLinkedPatterns()

Get all patterns linked to a task. Convenience method that fetches full pattern rows. T5156 Signature
(projectRoot: string, taskId: string) => Promise<{ id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; pattern: string; context: string; ... 6 more ...; extractedAt: string; }[]>

getLinkedLearnings()

Get all learnings linked to a task. Convenience method that fetches full learning rows. T5156 Signature
(projectRoot: string, taskId: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; }[]>

extractMemoryItems()

Extract memory-worthy items from debrief data. Pure function — no side effects. Items extracted: - Decisions (from debrief.decisions[]) - observations with type=‘decision’ - Tasks completed summary - observation with type=‘change’ - Session-level note (if present) - observation with type=‘discovery’ Signature
(sessionId: string, debrief: DebriefData | null | undefined) => MemoryItem[]

persistSessionMemory(projectRoot, sessionId, debrief)

Main entry point — called from session.end handler. Extracts memory-worthy content from debrief data and persists to brain.db. ALL errors are caught and accumulated in result.errors — never throws. Signature
(projectRoot: string, sessionId: string, debrief: DebriefData | null | undefined) => Promise<SessionMemoryResult>
Parameters
NameTypeDescription
projectRootstringProject root directory
sessionIdstringThe session that just ended
debriefDebriefData | null | undefinedRich debrief data from sessionComputeDebrief()
Returns — Summary of what was persisted

getSessionMemoryContext(projectRoot, scope, options)

Retrieve session memory for a given scope. Used by briefing/handoff to enrich response with brain context. Signature
(projectRoot: string, scope?: { type: string; epicId?: string | undefined; rootTaskId?: string | undefined; } | undefined, options?: { limit?: number | undefined; includeDecisions?: boolean | undefined; includePatterns?: boolean | undefined; } | undefined) => Promise<...>
Parameters
NameTypeDescription
projectRootstringProject root directory
scope: \{ type: string; epicId?: string | undefined; rootTaskId?: string | undefined; \} | undefinedSession scope for filtering (epic:T### or global)
options: \{ limit?: number | undefined; includeDecisions?: boolean | undefined; includePatterns?: boolean | undefined; \} | undefinedRetrieval options
Returns — Relevant brain memory entries

depsReady(depends, taskLookup)

Check if all dependencies of a task are satisfied. Signature
(depends: string[] | undefined, taskLookup: ReadonlyMap<string, unknown>) => boolean
Parameters
NameTypeDescription
dependsstring[] | undefinedArray of dependency task IDs (may be undefined/empty)
taskLookupReadonlyMap&lt;stringMap from task ID to a task-like object with at least status: string
Returns — true if all dependencies are done/cancelled, or if no dependencies exist

computeBriefing()

Compute the complete session briefing. Aggregates data from all 6+ sources. Signature
(projectRoot: string, options?: BriefingOptions) => Promise<SessionBriefing>

findSessions(accessor, params)

Find sessions with minimal field projection. Loads all sessions, applies filters, then projects to minimal fields. This is cheaper for agents that only need discovery-level data. Signature
(accessor: DataAccessor, params?: FindSessionsParams | undefined) => Promise<MinimalSessionRecord[]>
Parameters
NameTypeDescription
accessorDataAccessorDataAccessor for loading sessions
params: FindSessionsParams | undefinedOptional filters (status, scope, query, limit)
Returns — Array of minimal session records

archiveSessions()

Archive old/ended sessions. Identifies ended and suspended sessions older than the threshold. With SQLite, all sessions live in a single table — “archiving” marks them as identified for potential cleanup rather than moving between arrays. Signature
(projectRoot: string, olderThan?: string | undefined) => Promise<{ archived: string[]; count: number; }>

cleanupSessions()

Remove orphaned sessions, auto-end stale active sessions, and clean up stale data. Stale active sessions (no activity beyond the configured threshold) are transitioned to ‘ended’ with an auto-end note. The threshold is read from retention.autoEndActiveAfterDays in the project config (default: 7 days). T2304 Signature
(projectRoot: string) => Promise<{ removed: string[]; autoEnded: string[]; cleaned: boolean; }>

getContextDrift()

Compute context drift score for the current session. Compares session progress against original scope by counting completed vs total tasks in scope, and detecting out-of-scope work. Signature
(projectRoot: string, params?: { sessionId?: string | undefined; } | undefined) => Promise<ContextDriftResult>

getSessionHistory()

List session history with focus changes and completed tasks. If sessionId is provided, returns history for that specific session. Otherwise, returns history across all sessions. Signature
(projectRoot: string, params?: SessionHistoryParams | undefined) => Promise<{ sessions: SessionHistoryEntry[]; }>

showSession()

Show a specific session. Looks in active sessions first, then session history. Throws CleoError if not found. Signature
(projectRoot: string, sessionId: string) => Promise<Session>

getSessionStats()

Compute session statistics, optionally for a specific session. Throws CleoError if a specific session is requested but not found. Signature
(projectRoot: string, sessionId?: string | undefined) => Promise<SessionStatsResult>

suspendSession()

Suspend an active session. Sets status to ‘suspended’ and records the reason. Throws if session not found or not active. Signature
(projectRoot: string, sessionId: string, reason?: string | undefined) => Promise<Session>

switchSession()

Switch to a different session. Suspends the current active session and activates the target. Throws if session not found or archived. Signature
(projectRoot: string, sessionId: string) => Promise<Session>

SessionView

Signature
typeof SessionView
Methods

from()

Create a SessionView from a Session array.
(sessions: Session[]) => SessionView

findActive()

Find the currently active session (if any).
() => Session | undefined

findById()

Find a session by ID.
(id: string) => Session | undefined

filterByStatus()

Filter sessions by one or more statuses.
(...statuses: ("active" | "ended" | "orphaned" | "suspended")[]) => Session[]

findByScope()

Find sessions matching a scope type and optional rootTaskId.
(type: string, rootTaskId?: string | undefined) => Session[]

sortByDate()

Sort sessions by a date field. Returns a new array (does not mutate).
(field: "startedAt" | "endedAt", descending?: boolean) => Session[]

mostRecent()

Get the most recently started session.
() => Session | undefined

toArray()

Convert back to a plain Session array (shallow copy).
() => Session[]

Symbol.iterator

Support for-of iteration.
() => Iterator<Session, any, any>

selectRuntimeProviderContext()

Signature
(detections: DetectionResult[], snapshot?: RuntimeProviderSnapshot) => RuntimeProviderContext

detectRuntimeProviderContext()

Signature
(snapshot?: RuntimeProviderSnapshot) => RuntimeProviderContext

resetRuntimeProviderContextCache()

Signature
() => void

parseScope()

Parse a scope string into a SessionScope. T4463 Signature
(scopeStr: string) => SessionScope

readSessions()

Read sessions from accessor or JSON file. T4463 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session[]>

saveSessions()

Save sessions via accessor or JSON file. T4463 Signature
(sessions: Session[], cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<void>

startSession()

Start a new session. T4463 Signature
(options: StartSessionOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session>

endSession()

End a session. T4463 Signature
(options?: EndSessionOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session>

sessionStatus()

Get current session status. T4463 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session | null>

resumeSession()

Resume an existing session. T4463 Signature
(sessionId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session>

listSessions()

List sessions with optional filtering. T4463 Signature
(options?: ListSessionsOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session[]>

gcSessions()

Garbage collect old sessions. Marks orphaned sessions that have been active too long. T4463 Signature
(maxAgeHours?: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ orphaned: string[]; removed: string[]; }>

archiveSticky(id, projectRoot)

Archive a sticky note. Signature
(id: string, projectRoot: string) => Promise<StickyNote | null>
Parameters
NameTypeDescription
idstringSticky note ID
projectRootstringProject root path
Returns — The archived sticky note or null if not found

convertStickyToTask(stickyId, taskTitle, projectRoot)

Convert a sticky note to a task. Signature
(stickyId: string, taskTitle: string | undefined, projectRoot: string) => Promise<{ success: boolean; taskId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
Parameters
NameTypeDescription
stickyIdstringSticky note ID
taskTitlestring | undefinedOptional task title (defaults to sticky content)
projectRootstringProject root path
Returns — Result with new task ID

convertStickyToMemory(stickyId, memoryType, projectRoot)

Convert a sticky note to a memory observation. Signature
(stickyId: string, memoryType: string | undefined, projectRoot: string) => Promise<{ success: boolean; memoryId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
Parameters
NameTypeDescription
stickyIdstringSticky note ID
memoryTypestring | undefinedOptional memory type
projectRootstringProject root path
Returns — Result with new memory entry ID

convertStickyToTaskNote(stickyId, taskId, projectRoot)

Convert a sticky note to a task note. Signature
(stickyId: string, taskId: string, projectRoot: string) => Promise<{ success: boolean; taskId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
Parameters
NameTypeDescription
stickyIdstringSticky note ID
taskIdstringTarget task ID
projectRootstringProject root path
Returns — Result with updated task ID

convertStickyToSessionNote(stickyId, sessionId, projectRoot)

Convert a sticky note to a session note. Signature
(stickyId: string, sessionId: string | undefined, projectRoot: string) => Promise<{ success: boolean; sessionId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
Parameters
NameTypeDescription
stickyIdstringSticky note ID
sessionIdstring | undefinedOptional target session ID (defaults to current active session)
projectRootstringProject root path
Returns — Result with session ID

generateStickyId(projectRoot)

Generate the next sticky note ID. Finds the highest existing SN-XXX ID and increments. Signature
(projectRoot: string) => Promise<string>
Parameters
NameTypeDescription
projectRootstringProject root path
Returns — Next sticky note ID (e.g., “SN-042”)

addSticky(params, projectRoot)

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

listStickies(params, projectRoot)

List sticky notes with optional filters. Signature
(params: ListStickiesParams, projectRoot: string) => Promise<StickyNote[]>
Parameters
NameTypeDescription
paramsListStickiesParamsFilter parameters
projectRootstringProject root path
Returns — Array of sticky notes

purgeSticky(id, projectRoot)

Purge (permanently delete) a sticky note. Signature
(id: string, projectRoot: string) => Promise<StickyNote | null>
Parameters
NameTypeDescription
idstringSticky note ID
projectRootstringProject root path
Returns — The deleted sticky note or null if not found

getSticky(id, projectRoot)

Get a sticky note by ID. Signature
(id: string, projectRoot: string) => Promise<StickyNote | null>
Parameters
NameTypeDescription
idstringSticky note ID (e.g., “SN-042”)
projectRootstringProject root path
Returns — The sticky note or null if not found

archiveTasks()

Archive completed (and optionally cancelled) tasks. Moves them from active task data to archive. T4461 Signature
(options?: ArchiveTasksOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ArchiveTasksResult>

deleteTask()

Delete a task (soft delete - moves to archive). T4461 Signature
(options: DeleteTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<DeleteTaskResult>

Cleo

Signature
typeof Cleo
Methods

init()

(projectRoot: string, options?: CleoInitOptions | undefined) => Promise<Cleo>

forProject()

(projectRoot: string) => Cleo

calculateExportChecksum()

Calculate SHA-256 checksum for export integrity (truncated to 16 hex chars). Signature
(tasksJson: string) => string

verifyExportChecksum()

Verify export package checksum. Signature
(pkg: ExportPackage) => boolean

buildIdMap()

Build ID map from tasks. Signature
(tasks: Task[]) => Record<string, IdMapEntry>

buildRelationshipGraph()

Build relationship graph from tasks. Signature
(tasks: Task[]) => RelationshipGraph

buildExportPackage()

Build a complete export package. Signature
(tasks: Task[], taskData: TaskFile, options: { mode: string; rootTaskIds: string[]; includeChildren: boolean; cleoVersion?: string | undefined; filters?: unknown; }) => ExportPackage

exportSingle()

Export a single task. Signature
(taskId: string, taskData: TaskFile) => ExportPackage | null

exportSubtree()

Export a subtree (task + all descendants). Signature
(rootId: string, taskData: TaskFile) => ExportPackage | null

exportTasksPackage()

Export tasks to a portable cross-project package. Signature
(params: ExportTasksParams) => Promise<ExportTasksResult>

getCostHint()

Determine cost hint for an operation based on domain and operation name. Signature
(domain: string, operation: string) => CostHint

groupOperationsByDomain(ops)

Group operations by domain into a compact format. Signature
(ops: HelpOperationDef[]) => GroupedOperations
Parameters
NameTypeDescription
opsHelpOperationDef[]Operations filtered to the requested tier
Returns — Domain-grouped operations with query and mutate arrays

buildVerboseOperations(ops)

Build verbose operation entries with cost hints. Signature
(ops: HelpOperationDef[]) => VerboseOperation[]
Parameters
NameTypeDescription
opsHelpOperationDef[]Operations filtered to the requested tier
Returns — Array of verbose operation objects

computeHelp(allOperations, tier, verbose)

Compute the help result for the admin.help operation. Accepts the full OPERATIONS registry and filters/formats based on tier and verbosity. This is pure business logic with no dispatch or engine dependencies. Signature
(allOperations: HelpOperationDef[], tier: number, verbose: boolean) => HelpResult
Parameters
NameTypeDescription
allOperationsHelpOperationDef[]The full operation registry
tiernumberThe tier level to filter to (0, 1, or 2)
verbosebooleanWhether to return full operation objects or compact grouped format
Returns — The computed help result

getNextAvailableId()

Get the next available task ID number from existing tasks. Signature
(tasks: Task[]) => number

generateRemapTable()

Generate a remap table for importing tasks. Maps source task IDs to new sequential IDs starting from nextAvailable. Signature
(sourceTaskIds: string[], existingTasks: Task[]) => RemapTable

validateRemapTable()

Validate that a remap table is complete and consistent. Signature
(table: RemapTable, expectedSourceIds: string[]) => { valid: boolean; errors: string[]; }

remapTaskId()

Remap a single task ID, returning original if not in table. Signature
(taskId: string | null, table: RemapTable) => string | null

remapTaskReferences()

Remap all ID references in a task. Signature
(task: Task, table: RemapTable, existingTaskIds: Set<string>, missingDepStrategy?: "fail" | "strip") => Task

detectDuplicateTitles()

Detect duplicate titles between import and target. Signature
(importTasks: Task[], existingTasks: Task[]) => { sourceId: string; title: string; existingId: string; }[]

resolveDuplicateTitle()

Resolve duplicate title by appending suffix. Signature
(title: string, existingTitles: Set<string>) => string

importTasksPackage()

Import tasks from a cross-project export package with ID remapping. Signature
(params: ImportTasksParams) => Promise<ImportTasksResult>

findAdrs()

Signature
(projectRoot: string, query: string, opts?: { topics?: string | undefined; keywords?: string | undefined; status?: string | undefined; } | undefined) => Promise<AdrFindResult>

listAdrs()

List ADRs from .cleo/adrs/ directory with optional status filter Signature
(projectRoot: string, opts?: { status?: string | undefined; since?: string | undefined; limit?: number | undefined; offset?: number | undefined; } | undefined) => Promise<AdrListResult>

showAdr()

Retrieve a single ADR by ID (e.g., ‘ADR-007’) Signature
(projectRoot: string, adrId: string) => Promise<AdrRecord | null>

validateAllAdrs()

Validate all ADRs in .cleo/adrs/ against the schema Signature
(projectRoot: string) => Promise<ValidationResult>

providerList()

List all registered providers. T4332 Signature
() => EngineResult<Provider[]>

providerGet()

Get a single provider by ID or alias. T4332 Signature
(idOrAlias: string) => EngineResult<Provider>

providerDetect()

Detect all providers installed on the system. T4332 Signature
() => EngineResult<DetectionResult[]>

providerInstalled()

Get providers that are installed on the system. T4332 Signature
() => EngineResult<Provider[]>

providerCount()

Get count of registered providers. T4332 Signature
() => EngineResult<{ count: number; }>

registryVersion()

Get CAAMP registry version. T4332 Signature
() => EngineResult<{ version: string; }>

mcpList()

List MCP servers for a specific provider. T4332 Signature
(providerId: string, scope: "global" | "project", projectDir?: string | undefined) => Promise<EngineResult<{ servers: unknown[]; }>>

mcpListAll()

List MCP servers across all installed providers. T4332 Signature
(scope: "global" | "project", projectDir?: string | undefined) => Promise<EngineResult<{ servers: unknown[]; }>>

mcpInstall()

Install an MCP server to a provider’s config. T4332 Signature
(providerId: string, serverName: string, config: McpServerConfig, scope?: "global" | "project" | undefined, projectDir?: string | undefined) => Promise<EngineResult<InstallResult>>

mcpRemove()

Remove an MCP server from a provider’s config. T4332 Signature
(providerId: string, serverName: string, scope: "global" | "project", projectDir?: string | undefined) => Promise<EngineResult<{ removed: boolean; }>>

mcpConfigPath()

Resolve the config file path for a provider. T4332 Signature
(providerId: string, scope: "global" | "project", projectDir?: string | undefined) => EngineResult<{ path: string | null; }>

injectionCheck()

Check injection status for a single file. T4332 Signature
(filePath: string, expectedContent?: string | undefined) => Promise<EngineResult<InjectionStatus>>

injectionCheckAll()

Check injection status across all providers. T4332 Signature
(projectDir: string, scope: "global" | "project", expectedContent?: string | undefined) => Promise<EngineResult<{ results: unknown[]; }>>

injectionUpdate()

Inject or update content in a single file. T4332 Signature
(filePath: string, content: string) => Promise<EngineResult<{ action: string; }>>

injectionUpdateAll()

Inject content to all providers’ instruction files. T4332 Signature
(projectDir: string, scope: "global" | "project", content: string) => Promise<EngineResult<{ results: Record<string, string>; }>>

batchInstallWithRollback()

Install multiple MCP servers atomically with rollback on failure. Supports Wave 4 init rewrite which needs to install multiple skills/configs as a single atomic operation. T4705 T4663 Signature
(options: BatchInstallOptions) => Promise<EngineResult<BatchInstallResult>>

dualScopeConfigure()

Configure a provider at both global and project scope simultaneously. Used during init to set up MCP configs in both scopes atomically. T4705 T4663 Signature
(providerId: string, options: DualScopeConfigureOptions) => Promise<EngineResult<DualScopeConfigureResult>>

checkProviderCapability(provider, capabilityPath)

Check if provider supports a specific capability Signature
(provider: string | Provider, capabilityPath: string) => boolean
Parameters
NameTypeDescription
providerstring | ProviderProvider object or ID
capabilityPathstringDot notation path (e.g., ‘spawn.supportsSubagents’)
Returns — boolean Examples: - providerSupports(provider, ‘spawn.supportsSubagents’) - providerSupports(provider, ‘hooks.supported’) - providerSupportsById(‘claude-code’, ‘spawn.supportsParallelSpawn’) - providerSupportsById(‘gemini-cli’, ‘skills.precedence’)

checkProviderCapabilities()

Check multiple capabilities at once Signature
(providerId: string, capabilities: string[]) => Record<string, boolean>

getComplianceJsonlPath()

Resolve COMPLIANCE.jsonl path for a project root. Signature
(projectRoot: string) => string

readComplianceJsonl()

Read COMPLIANCE.jsonl entries. Invalid JSON lines are skipped to preserve append-only log resilience. Signature
(projectRoot: string) => ComplianceJsonlEntry[]

appendComplianceJsonl()

Append one entry to COMPLIANCE.jsonl, creating directories as needed. Signature
(projectRoot: string, entry: ComplianceJsonlEntry) => void

getComplianceSummary()

Get compliance summary. Signature
(opts: { since?: string | undefined; agent?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

listComplianceViolations()

List compliance violations. Signature
(opts: { severity?: string | undefined; since?: string | undefined; agent?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

getComplianceTrend()

Get compliance trend. Signature
(days?: number, cwd?: string | undefined) => Promise<Record<string, unknown>>

auditEpicCompliance()

Audit epic compliance. Signature
(epicId: string, opts: { since?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

syncComplianceMetrics()

Sync compliance metrics to a summary file. Signature
(opts: { force?: boolean | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

getSkillReliability()

Get skill reliability stats. Signature
(opts: { global?: boolean | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

getValueMetrics()

Get value metrics (T2833). Signature
(days?: number, cwd?: string | undefined) => Promise<Record<string, unknown>>

getContextStatus()

Get context status. Signature
(opts: { session?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

checkContextThreshold()

Check context threshold (returns exit code info). Signature
(opts: { session?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown> & { exitCode?: number | undefined; }>

listContextSessions()

List all context state files. Signature
(cwd?: string | undefined) => Promise<Record<string, unknown>>

injectTasks()

Inject tasks for external consumption. Signature
(opts: { maxTasks?: number | undefined; focusedOnly?: boolean | undefined; phase?: string | undefined; output?: string | undefined; saveState?: boolean | undefined; dryRun?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<...>

collectDiagnostics()

Collect system diagnostics for bug reports. Signature
() => Record<string, string>

formatDiagnosticsTable()

Format diagnostics as markdown table. Signature
(diag: Record<string, string>) => string

parseIssueTemplates()

Parse all issue templates from available sources. Priority: 1. Packaged templates in the CLEO installation (for npm-installed users) 2. Project’s .github/ISSUE_TEMPLATE/ (for contributors working on CLEO) Signature
(projectDir?: string | undefined) => IssueTemplate[]

getTemplateConfig()

Get template configuration - tries live parse, cache, then fallback. Signature
(cwd?: string | undefined) => IssueTemplate[]

getTemplateForSubcommand()

Get the template for a specific subcommand (bug, feature, etc.). Signature
(subcommand: string, cwd?: string | undefined) => IssueTemplate | null

cacheTemplates()

Cache parsed templates to .cleo/issue-templates.json. Signature
(templates: IssueTemplate[], cwd?: string | undefined) => void

validateLabelsExist()

Validate that required labels exist (informational). Signature
(_templates: IssueTemplate[]) => { valid: boolean; missingLabels: string[]; }

buildIssueBody()

Build structured issue body with template sections. Signature
(subcommand: string, rawBody: string, severity?: string | undefined, area?: string | undefined) => string

checkGhCli()

Check that gh CLI is installed and authenticated. Signature
() => void

addIssue()

Add a GitHub issue for a given type (bug, feature, help). Returns structured result. Does not handle CLI output or process.exit. Note: Named ‘add’ per VERB-STANDARDS.md (canonical verb for “Create new entity”) Signature
(params: AddIssueParams) => AddIssueResult

applyTemporalDecay(projectRoot, options)

Apply temporal decay to brain_learnings confidence values. Entries older than olderThanDays have their confidence reduced by an exponential decay factor based on the number of days since their last update (or creation if never updated). Formula: new_confidence = confidence * (decayRate ^ daysSinceUpdate) Signature
(projectRoot: string, options?: { decayRate?: number | undefined; olderThanDays?: number | undefined; } | undefined) => Promise<DecayResult>
Parameters
NameTypeDescription
projectRootstringProject root directory for brain.db resolution
options: \{ decayRate?: number | undefined; olderThanDays?: number | undefined; \} | undefinedDecay configuration
Returns — Count of updated rows and tables processed

consolidateMemories(projectRoot, options)

Consolidate old observations by keyword similarity. Groups observations older than olderThanDays by FTS5 keyword overlap. For groups with at least minClusterSize entries, creates one summary observation and marks originals as archived (updated_at set, narrative prefixed with [ARCHIVED]). Signature
(projectRoot: string, options?: { olderThanDays?: number | undefined; minClusterSize?: number | undefined; } | undefined) => Promise<ConsolidationResult>
Parameters
NameTypeDescription
projectRootstringProject root directory for brain.db resolution
options: \{ olderThanDays?: number | undefined; minClusterSize?: number | undefined; \} | undefinedConsolidation configuration
Returns — Counts of grouped, merged, and archived observations

migrateBrainData()

Migrate BRAIN memory data from JSONL files to brain.db. Reads: - .cleo/memory/patterns.jsonl - brain_patterns table - .cleo/memory/learnings.jsonl - brain_learnings table Skips entries where the ID already exists in the database (idempotent). T5129 Signature
(projectRoot: string) => Promise<BrainMigrationResult>

addResearch()

Add a research entry. T4465 Signature
(options: AddResearchOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ResearchEntry>

showResearch()

Show a specific research entry. T4465 Signature
(researchId: string, cwd?: string | undefined) => Promise<ResearchEntry>

listResearch()

List research entries with optional filtering. T4465 Signature
(options?: ListResearchOptions, cwd?: string | undefined) => Promise<ResearchEntry[]>

pendingResearch()

List pending research entries. T4465 Signature
(cwd?: string | undefined) => Promise<ResearchEntry[]>

linkResearch()

Link a research entry to a task. T4465 Signature
(researchId: string, taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ researchId: string; taskId: string; }>

updateResearch()

Update research findings. T4465 Signature
(researchId: string, updates: { findings?: string[] | undefined; sources?: string[] | undefined; status?: "complete" | "pending" | "partial" | undefined; }, cwd?: string | undefined) => Promise<...>

statsResearch()

Get research statistics. T4474 Signature
(cwd?: string | undefined) => Promise<{ total: number; byStatus: Record<string, number>; byTopic: Record<string, number>; }>

linksResearch()

Get research entries linked to a specific task. T4474 Signature
(taskId: string, cwd?: string | undefined) => Promise<ResearchEntry[]>

archiveResearch()

Archive old research entries by status. Moves ‘complete’ entries older than a threshold to an archive, or returns summary of archivable entries. T4474 Signature
(cwd?: string | undefined) => Promise<{ action: string; entriesArchived: number; entriesRemaining: number; }>

readManifest()

Read manifest entries from MANIFEST.jsonl. T4465 Signature
(cwd?: string | undefined) => Promise<ManifestEntry[]>

appendManifest()

Append a manifest entry. T4465 Signature
(entry: ManifestEntry, cwd?: string | undefined) => Promise<void>

queryManifest()

Query manifest entries. T4465 Signature
(options?: ManifestQueryOptions, cwd?: string | undefined) => Promise<ManifestEntry[]>

readExtendedManifest()

Read all manifest entries as extended entries. T4787 Signature
(cwd?: string | undefined) => Promise<ExtendedManifestEntry[]>

filterManifestEntries()

Filter manifest entries by criteria. T4787 Signature
(entries: ExtendedManifestEntry[], filter: ResearchFilter) => ExtendedManifestEntry[]

showManifestEntry()

Show a manifest entry by ID with optional file content. T4787 Signature
(researchId: string, cwd?: string | undefined) => Promise<ExtendedManifestEntry & { fileContent: string | null; fileExists: boolean; }>

searchManifest()

Search manifest entries by text with relevance scoring. T4787 Signature
(query: string, options?: { confidence?: number | undefined; limit?: number | undefined; } | undefined, cwd?: string | undefined) => Promise<(ExtendedManifestEntry & { ...; })[]>

pendingManifestEntries()

Get pending manifest entries (partial, blocked, or needing followup). T4787 Signature
(epicId?: string | undefined, cwd?: string | undefined) => Promise<{ entries: ExtendedManifestEntry[]; total: number; byStatus: { partial: number; blocked: number; needsFollowup: number; }; }>

manifestStats()

Get manifest-based research statistics. T4787 Signature
(epicId?: string | undefined, cwd?: string | undefined) => Promise<{ total: number; byStatus: Record<string, number>; byType: Record<string, number>; actionable: number; needsFollowup: number; averageFindings: number; }>

linkManifestEntry()

Link a manifest entry to a task (adds taskId to linked_tasks array). T4787 Signature
(taskId: string, researchId: string, cwd?: string | undefined) => Promise<{ taskId: string; researchId: string; alreadyLinked: boolean; }>

appendExtendedManifest()

Append an extended manifest entry. Validates required fields before appending. T4787 Signature
(entry: ExtendedManifestEntry, cwd?: string | undefined) => Promise<{ entryId: string; file: string; }>

archiveManifestEntries()

Archive manifest entries older than a date. T4787 Signature
(beforeDate: string, cwd?: string | undefined) => Promise<{ archived: number; remaining: number; archiveFile: string; }>

findContradictions()

Find manifest entries with overlapping topics but conflicting key_findings. T4787 Signature
(cwd?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<ContradictionDetail[]>

findSuperseded()

Identify research entries replaced by newer work on same topic. T4787 Signature
(cwd?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<SupersededDetail[]>

readProtocolInjection()

Read protocol injection content for a given protocol type. T4787 Signature
(protocolType: string, params?: { taskId?: string | undefined; variant?: string | undefined; } | undefined, cwd?: string | undefined) => Promise<{ protocolType: string; content: string; ... 4 more ...; variant: string | null; }>

compactManifest()

Compact MANIFEST.jsonl by removing duplicate/stale entries. T4787 Signature
(cwd?: string | undefined) => Promise<{ compacted: boolean; originalLines: number; malformedRemoved: number; duplicatesRemoved: number; remainingEntries: number; }>

validateManifestEntries()

Validate research entries for a task. T4787 Signature
(taskId: string, cwd?: string | undefined) => Promise<{ taskId: string; valid: boolean; entriesFound: number; issues: { entryId: string; issue: string; severity: "error" | "warning"; }[]; errorCount: number; warningCount: number; }>

ensureMetricsDir()

Ensure metrics directory exists, returning its path. Signature
(metricsDir?: string | undefined) => Promise<string>

getCompliancePath()

Get compliance log path. Signature
(metricsDir?: string | undefined) => string

getViolationsPath()

Get violations log path. Signature
(metricsDir?: string | undefined) => string

getSessionsMetricsPath()

Get sessions metrics log path. Signature
(metricsDir?: string | undefined) => string

isoTimestamp()

Generate ISO 8601 UTC timestamp. Signature
() => string

isoDate()

Generate ISO 8601 date only. Signature
() => string

readJsonlFile()

Read a JSONL file into an array of parsed objects. Signature
(filePath: string) => Record<string, unknown>[]

getComplianceSummaryBase()

Get compliance summary from log file. Signature
(compliancePath?: string | undefined) => ComplianceSummary

isOtelEnabled()

Check if OTel telemetry is enabled. Signature
() => boolean

getOtelSetupCommands()

Get environment variable commands for OTel capture setup. Signature
(mode?: OtelCaptureMode, cwd?: string | undefined) => string

parseTokenMetrics()

Parse OTel token metrics from collected data. Signature
(inputFile?: string | undefined, cwd?: string | undefined) => OtelTokenDataPoint[]

getSessionTokens()

Get aggregated token counts from OTel data. Signature
(sessionId?: string | undefined, cwd?: string | undefined) => AggregatedTokens

recordSessionStart()

Record token counts at session start. Signature
(sessionId: string, cwd?: string | undefined) => Promise<Record<string, unknown>>

recordSessionEnd()

Record token counts at session end. Signature
(sessionId: string, cwd?: string | undefined) => Promise<Record<string, unknown>>

compareSessions()

Compare token usage between two sessions. Signature
(sessionA: string, sessionB: string, cwd?: string | undefined) => Record<string, unknown>

getTokenStats()

Get statistics about token usage across sessions. Signature
(cwd?: string | undefined) => Record<string, unknown>

logABEvent()

Log an A/B test event. Signature
(eventType: ABEventType, testName: string, variant: ABVariant, context?: string | Record<string, unknown> | undefined, cwd?: string | undefined) => Promise<...>

startABTest()

Start an A/B test session. Signature
(testName: string, variant: ABVariant, description?: string | undefined, cwd?: string | undefined) => Promise<void>

endABTest()

End an A/B test session with summary. Signature
(options?: { tasksCompleted?: number | undefined; validationPasses?: number | undefined; validationFailures?: number | undefined; notes?: string | undefined; }, cwd?: string | undefined) => Promise<...>

getABTestResults()

Get results for a specific test variant. Signature
(testName: string, variant: ABVariant, cwd?: string | undefined) => Record<string, unknown> | null

listABTests()

List all A/B tests. Signature
(filter?: string | undefined, cwd?: string | undefined) => Record<string, unknown>[]

compareABTest()

Compare two variants of the same test. Signature
(testName: string, cwd?: string | undefined) => Record<string, unknown>

getABTestStats()

Get aggregate statistics of all A/B tests. Signature
(cwd?: string | undefined) => Record<string, unknown>

syncMetricsToGlobal()

Sync project metrics to global aggregation file. Signature
(options?: { force?: boolean | undefined; }, cwd?: string | undefined) => Promise<Record<string, unknown>>

getProjectComplianceSummary()

Get compliance summary for the current project. Signature
(options?: { since?: string | undefined; agent?: string | undefined; category?: string | undefined; }, cwd?: string | undefined) => Record<string, unknown>

getGlobalComplianceSummary()

Get compliance summary across all projects. Signature
(options?: { since?: string | undefined; project?: string | undefined; }) => Record<string, unknown>

getComplianceTrend()

Get compliance trend over time. Signature
(days?: number, options?: { project?: string | undefined; global?: boolean | undefined; }, cwd?: string | undefined) => Record<string, unknown>

getSkillReliability()

Get reliability stats per skill/agent. Signature
(options?: { since?: string | undefined; global?: boolean | undefined; }, cwd?: string | undefined) => Record<string, unknown>

logSessionMetrics()

Log session metrics to SESSIONS.jsonl. Signature
(metricsJson: Record<string, unknown>, cwd?: string | undefined) => Promise<Record<string, unknown>>

getSessionMetricsSummary()

Get summary of session metrics. Signature
(options?: { since?: string | undefined; }, cwd?: string | undefined) => Record<string, unknown>

isValidEnumValue()

Validate that a value is a member of a given enum. Signature
<T extends Record<string, string>>(enumObj: T, value: string) => value is T[keyof T]

estimateTokens()

Estimate token count from text. ~4 characters per token. Signature
(text: string) => number

estimateTokensFromFile()

Estimate token count from a file. Signature
(filePath: string) => number

logTokenEvent()

Log a token usage event to the JSONL file. Signature
(eventType: TokenEventType, tokens: number, source: string, taskId?: string | undefined, context?: Record<string, unknown> | undefined, cwd?: string | undefined) => Promise<...>

trackFileRead()

Track a file read with token estimate. Signature
(filePath: string, purpose: string, taskId?: string | undefined, cwd?: string | undefined) => Promise<number>

trackManifestQuery()

Track a manifest query (partial read). Signature
(queryType: string, resultCount: number, taskId?: string | undefined, cwd?: string | undefined) => Promise<number>

trackSkillInjection()

Track skill injection with tokens. Signature
(skillName: string, tier: number, tokens: number, taskId?: string | undefined, cwd?: string | undefined) => Promise<void>

trackPromptBuild()

Track final prompt size. Signature
(prompt: string, taskId: string, skillsUsed: string, cwd?: string | undefined) => Promise<number>

trackSpawnOutput()

Track subagent output tokens. Signature
(taskId: string, outputText: string, sessionId?: string | undefined, cwd?: string | undefined) => Promise<number>

trackSpawnComplete()

Track complete spawn cycle (prompt + output). Signature
(taskId: string, promptTokens: number, outputTokens: number, sessionId?: string | undefined, cwd?: string | undefined) => Promise<number>

startTokenSession()

Start tracking tokens for a session. Signature
(sessionId: string, cwd?: string | undefined) => Promise<void>

endTokenSession()

End token tracking session with summary. Signature
(cwd?: string | undefined) => Promise<TokenSessionSummary | null>

getTokenSummary()

Get token usage summary for a time period. Signature
(days?: number, cwd?: string | undefined) => Record<string, unknown>

compareManifestVsFull()

Compare manifest vs full file token usage strategies. Signature
(manifestEntries: number) => Record<string, unknown>

getTrackingStatus()

Get tracking status. Signature
() => { tracking_enabled: boolean; env_var: string; }

computeChecksum(filePath)

Compute SHA-256 checksum of a file. Signature
(filePath: string) => Promise<string>
Parameters
NameTypeDescription
filePathstringPath to the file
Returns — Hex-encoded SHA-256 checksum T4728

verifyBackup(sourcePath, backupPath)

Verify that a backup file matches the source file and is a valid SQLite database. Performs three checks: 1. Computes SHA-256 checksum of both files 2. Compares checksums to detect any content differences 3. Verifies the backup can be opened as a valid SQLite database Signature
(sourcePath: string, backupPath: string) => Promise<VerificationResult>
Parameters
NameTypeDescription
sourcePathstringPath to the source database file
backupPathstringPath to the backup file
Returns — VerificationResult with checksums and validity status T4728

compareChecksums(filePath1, filePath2)

Quick checksum comparison without SQLite verification. Use when you only need to compare file contents. Signature
(filePath1: string, filePath2: string) => Promise<boolean>
Parameters
NameTypeDescription
filePath1stringFirst file path
filePath2stringSecond file path
Returns — true if checksums match, false otherwise T4728

MigrationLogger

Structured logger for migration operations Signature
typeof MigrationLogger
Methods

getLevelPriority()

Get numeric priority for log level comparison.
(level: LogLevel) => number

shouldLog()

Check if a log level should be recorded.
(level: LogLevel) => boolean

log()

Write a log entry.
(level: LogLevel, phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void

info()

Log an info-level message.
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void

warn()

Log a warning-level message.
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void

error()

Log an error-level message.
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void

debug()

Log a debug-level message.
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void

logFileOperation()

Log file operation with size information.
(phase: string, operation: "read" | "write" | "delete" | "rename" | "backup", sourcePath: string, targetPath?: string | undefined, additionalData?: Record<string, unknown> | undefined) => void

logValidation()

Log validation result.
(phase: string, target: string, valid: boolean, details?: Record<string, unknown> | undefined, errors?: string[] | undefined) => void

logImportProgress()

Log import progress.
(phase: string, entityType: string, imported: number, total: number, additionalData?: Record<string, unknown> | undefined) => void

phaseStart()

Log phase start.
(phase: string, data?: Record<string, unknown> | undefined) => void

phaseComplete()

Log phase completion.
(phase: string, data?: Record<string, unknown> | undefined) => void

phaseFailed()

Log phase failure.
(phase: string, error: string | Error, data?: Record<string, unknown> | undefined) => void

cleanupOldLogs()

Clean up old log files, keeping only the most recent ones.
() => void

getLogPath()

Get the absolute path to the log file.
() => string

getRelativeLogPath()

Get the path to the log file relative to cleoDir.
() => string

getEntries()

Get all logged entries.
() => MigrationLogEntry[]

getEntriesByLevel()

Get entries filtered by level.
(level: LogLevel) => MigrationLogEntry[]

getEntriesByPhase()

Get entries for a specific phase.
(phase: string) => MigrationLogEntry[]

getDurationMs()

Get the total duration of the migration so far.
() => number

getSummary()

Get summary statistics for the migration.
() => { totalEntries: number; durationMs: number; errors: number; warnings: number; info: number; debug: number; phases: string[]; }

createMigrationLogger()

Create a migration logger for the given cleo directory. Convenience function for functional programming style. Signature
(cleoDir: string, config?: MigrationLoggerConfig | undefined) => MigrationLogger

readMigrationLog()

Read and parse a migration log file. Signature
(logPath: string) => MigrationLogEntry[]

logFileExists()

Check if a log file exists and is readable. Signature
(logPath: string) => boolean

getLatestMigrationLog()

Get the most recent migration log file for a cleo directory. Signature
(cleoDir: string) => string | null

checkStorageMigration()

Check whether legacy JSON data needs to be migrated to SQLite. Returns a diagnostic result that callers can use to warn users. This function is read-only and never modifies any files. Signature
(cwd?: string | undefined) => PreflightResult

createMigrationState(cleoDir, sourceFiles)

Create initial migration state at the start of migration. Captures source file checksums and initializes progress tracking. Uses atomic write pattern to ensure state is never in an inconsistent state. Signature
(cleoDir: string, sourceFiles?: { todoJson?: SourceFileInfo | undefined; sessionsJson?: SourceFileInfo | undefined; archiveJson?: SourceFileInfo | undefined; } | undefined) => Promise<...>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
sourceFiles: \{ todoJson?: SourceFileInfo | undefined; sessionsJson?: SourceFileInfo | undefined; archiveJson?: SourceFileInfo | undefined; \} | undefinedOptional pre-computed source file info
Returns — The created migration state T4726

updateMigrationState(cleoDir, updates)

Update migration state with partial updates. Merges updates with existing state and writes atomically. Automatically adds timestamp to phase transitions. Signature
(cleoDir: string, updates: Partial<MigrationState>) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
updatesPartial&lt;MigrationState&gt;Partial state updates to apply
Returns — The updated migration state T4726

updateMigrationPhase(cleoDir, phase)

Update just the migration phase. Convenience wrapper for common phase transition. Signature
(cleoDir: string, phase: MigrationPhase) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
phaseMigrationPhaseNew phase
Returns — The updated migration state T4726

updateMigrationProgress(cleoDir, progress)

Update progress counters during import. Signature
(cleoDir: string, progress: Partial<MigrationProgress>) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
progressPartial&lt;MigrationProgress&gt;Progress updates (only changed counters needed)
Returns — The updated migration state T4726

addMigrationError(cleoDir, error)

Add an error to the migration state. Signature
(cleoDir: string, error: string) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
errorstringError message
Returns — The updated migration state T4726

addMigrationWarning(cleoDir, warning)

Add a warning to the migration state. Signature
(cleoDir: string, warning: string) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
warningstringWarning message
Returns — The updated migration state T4726

loadMigrationState(cleoDir)

Load existing migration state. Signature
(cleoDir: string) => Promise<MigrationState | null>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
Returns — Migration state, or null if no state file exists T4726

isMigrationInProgress(cleoDir)

Check if a migration is in progress. Signature
(cleoDir: string) => Promise<boolean>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
Returns — true if migration state exists and is not complete/failed T4726

canResumeMigration(cleoDir)

Check if migration can be resumed. Signature
(cleoDir: string) => Promise<{ canResume: boolean; phase: MigrationPhase; progress: MigrationProgress; errors: string[]; } | null>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
Returns — Object with resume info, or null if cannot resume T4726

completeMigration(cleoDir)

Mark migration as complete. Signature
(cleoDir: string) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
Returns — The completed migration state T4726

failMigration(cleoDir, error)

Mark migration as failed with error details. Signature
(cleoDir: string, error: string) => Promise<MigrationState>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
errorstringPrimary error message
Returns — The failed migration state T4726

clearMigrationState(cleoDir)

Clear migration state file. Safe to call even if state doesn’t exist. Signature
(cleoDir: string) => Promise<void>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory T4726

getMigrationSummary(cleoDir)

Get a summary of migration state for display. Signature
(cleoDir: string) => Promise<string | null>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
Returns — Human-readable summary, or null if no state T4726

verifySourceIntegrity(cleoDir)

Verify source files haven’t changed since migration started. Compares current checksums with stored checksums to detect if source files were modified during migration. Signature
(cleoDir: string) => Promise<{ valid: boolean; changed: string[]; missing: string[]; }>
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
Returns — Object with verification results T4726

validateSourceFiles(cleoDir)

Validate all JSON source files before migration. This function MUST be called BEFORE any destructive database operations. It checks that all JSON files are parseable and contain expected data. Signature
(cleoDir: string) => JsonValidationResult
Parameters
NameTypeDescription
cleoDirstringPath to the .cleo directory
Returns — Validation result with details for each file T4725

formatValidationResult(result)

Format validation result for human-readable output. Signature
(result: JsonValidationResult) => string
Parameters
NameTypeDescription
resultJsonValidationResultValidation result
Returns — Formatted string

checkTaskCountMismatch(cleoDir, jsonTaskCount)

Check for task count mismatch between existing database and JSON. This helps detect cases where the database has data but JSON is empty (indicating a potential configuration or path issue). Signature
(cleoDir: string, jsonTaskCount: number) => string | null
Parameters
NameTypeDescription
cleoDirstringPath to .cleo directory
jsonTaskCountnumberNumber of tasks found in JSON
Returns — Warning message if mismatch detected, null otherwise

detectVersion()

Detect schema version from a data file. T4468 Signature
(data: unknown) => string

compareSemver()

Compare two version strings (X.Y.Z format, works for both semver and CalVer). Returns -1 if a b, 0 if equal, 1 if a b. T4468 Signature
(a: string, b: string) => number

getMigrationStatus()

Get migration status for all data files. T4468 Signature
(cwd?: string | undefined) => Promise<MigrationStatus>

runMigration()

Run migrations on a data file. T4468 Signature
(fileType: string, options?: { dryRun?: boolean | undefined; }, cwd?: string | undefined) => Promise<MigrationResult>

runAllMigrations()

Run all pending migrations. T4468 Signature
(options?: { dryRun?: boolean | undefined; }, cwd?: string | undefined) => Promise<MigrationResult[]>

invalidateGraphCache()

Invalidate the in-memory graph cache. Signature
() => void

buildGlobalGraph()

Build the global dependency graph from all registered projects. Uses checksum-based caching to avoid unnecessary rebuilds. Signature
() => Promise<NexusGlobalGraph>

nexusDeps()

Show dependencies for a task across projects. Supports forward (what this depends on) and reverse (what depends on this) lookups. Signature
(taskQuery: string, direction?: "forward" | "reverse") => Promise<DepsResult>

resolveCrossDeps()

Resolve an array of dependencies (local or cross-project). Signature
(depsArray: string[], sourceProject: string) => Promise<DepsEntry[]>

criticalPath()

Calculate the critical path across project boundaries. Returns the longest dependency chain in the global graph. Signature
() => Promise<CriticalPathResult>

blockingAnalysis()

Analyze the blocking impact of a task across all projects. Uses BFS to find all direct and transitive dependents. Signature
(taskQuery: string) => Promise<BlockingAnalysisResult>

orphanDetection()

Detect orphaned cross-project dependencies. Finds tasks with dependency references to projects or tasks that don’t exist. Signature
() => Promise<OrphanEntry[]>

compareLevels()

Compare two pino levels numerically. Returns negative if a b, 0 if equal, positive if a b. Signature
(a: PinoLevel, b: PinoLevel) => number

matchesFilter()

Check if a single entry matches the filter criteria. All specified fields must match (AND logic). Signature
(entry: PinoLogEntry, filter: LogFilter) => boolean

filterEntries()

Filter an array of parsed log entries against criteria. Returns entries matching ALL specified criteria (AND logic). Does not apply pagination (limit/offset) — use paginate() for that. Signature
(entries: PinoLogEntry[], filter: LogFilter) => PinoLogEntry[]

paginate()

Apply pagination (limit/offset) to a result set. Signature
(entries: PinoLogEntry[], limit?: number | undefined, offset?: number | undefined) => PinoLogEntry[]

isValidLevel()

Validate that a string is a valid PinoLevel. Signature
(level: string) => level is PinoLevel

parseLogLine()

Parse a single JSONL line into a PinoLogEntry. Returns null for empty lines, non-JSON, or lines missing required fields. Signature
(line: string) => PinoLogEntry | null

parseLogLines()

Parse multiple JSONL lines into PinoLogEntry array. Skips malformed lines. Signature
(lines: string[]) => PinoLogEntry[]

getProjectLogDir()

Get the project log directory path. Uses getLogDir() from logger if available, falls back to config-based resolution. Signature
(cwd?: string | undefined) => string | null

getGlobalLogDir()

Get the global log directory path (~/.cleo/logs/). Signature
() => string

discoverLogFiles()

Discover all log files in the specified scope. Returns file info sorted by date (newest first). Signature
(options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => LogFileInfo[]

readLogFileLines()

Read all lines from a log file synchronously. Returns raw JSON strings (one per line). Suitable for small-to-medium files. Signature
(filePath: string) => string[]

streamLogFileLines()

Create an async iterable over lines of a log file. Suitable for large files — does not load entire file into memory. Signature
(filePath: string) => AsyncGenerator<string, any, any>

queryLogs()

High-level query: discover files, parse, filter, paginate. Convenience wrapper combining all three layers. Signature
(filter?: LogFilter | undefined, options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => LogQueryResult

streamLogs()

Stream-based query for large log datasets. Yields matching entries one at a time. Respects limit. Does not support offset (streaming is forward-only). Signature
(filter?: LogFilter | undefined, options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => AsyncGenerator<PinoLogEntry, any, any>

getLogSummary()

Get a summary of log activity (counts by level, date range, subsystems). Reads all discovered files but does not return individual entries. Signature
(options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => LogSummary

getOtelStatus()

Get token tracking status. Signature
() => Promise<Record<string, unknown>>

getOtelSummary()

Get combined token usage summary. Signature
() => Promise<Record<string, unknown>>

getOtelSessions()

Get session-level token data. Signature
(opts: { session?: string | undefined; task?: string | undefined; }) => Promise<Record<string, unknown>>

getOtelSpawns()

Get spawn-level token data. Signature
(opts: { task?: string | undefined; epic?: string | undefined; }) => Promise<Record<string, unknown>>

getRealTokenUsage()

Get real token usage from Claude Code API. Signature
(_opts: { session?: string | undefined; since?: string | undefined; }) => Promise<Record<string, unknown>>

clearOtelData()

Clear token tracking data with backup. Signature
() => Promise<Record<string, unknown>>

listPhases()

List all phases with status summaries. T5326 Signature
(projectRoot: string, accessor?: DataAccessor | undefined) => Promise<{ success: boolean; data?: ListPhasesResult | undefined; error?: { code: string; message: string; } | undefined; }>

showPhase()

Show phase details by slug or current phase. T5326 Signature
(projectRoot: string, phaseId?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ success: boolean; data?: ShowPhaseResult | undefined; error?: { ...; } | undefined; }>

getCurrentBranch()

Get the current branch name in .cleo/.git. T4884 Signature
(cwd?: string | undefined) => Promise<string>

addRemote()

Add a git remote to .cleo/.git. T4884 Signature
(url: string, name?: string, cwd?: string | undefined) => Promise<void>

removeRemote()

Remove a git remote from .cleo/.git. T4884 Signature
(name?: string, cwd?: string | undefined) => Promise<void>

listRemotes()

List configured remotes in .cleo/.git. T4884 Signature
(cwd?: string | undefined) => Promise<RemoteInfo[]>

push()

Push .cleo/.git to a remote. T4884 Signature
(remote?: string, options?: { force?: boolean | undefined; setUpstream?: boolean | undefined; } | undefined, cwd?: string | undefined) => Promise<PushResult>

pull()

Pull from a remote into .cleo/.git. Uses rebase strategy to maintain clean history. T4884 Signature
(remote?: string, cwd?: string | undefined) => Promise<PullResult>

getSyncStatus()

Get the sync status between local .cleo/.git and remote. T4884 Signature
(remote?: string, cwd?: string | undefined) => Promise<{ ahead: number; behind: number; branch: string; remote: string; }>

getRoadmap()

Get roadmap from pending epics and CHANGELOG history. Signature
(opts: { includeHistory?: boolean | undefined; upcomingOnly?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

getOperationMode()

Lookup the execution mode for a specific operation Signature
(domain: string, operation: string, gateway: GatewayType) => ExecutionMode | undefined

canRunNatively()

Check if an operation can run natively (without CLI) Signature
(domain: string, operation: string, gateway: GatewayType) => boolean

requiresCLI()

Check if an operation requires CLI Signature
(domain: string, operation: string, gateway: GatewayType) => boolean

getNativeOperations()

Get all native-capable operations for a domain Signature
(domain: string) => OperationCapability[]

generateCapabilityReport()

Generate a capability report for system.doctor Signature
() => CapabilityReport

getCapabilityMatrix()

Get the full capability matrix (for testing/introspection) Signature
() => readonly OperationCapability[]

findHighestId()

Find the highest existing task ID number Signature
(existingIds: Set<string>) => number

generateNextIdFromSet()

Generate the next ID given an explicit set of existing IDs. Useful when caller has already loaded task data. Signature
(existingIds: Set<string>) => string

isValidTaskId()

Validate that a task ID matches the expected format Signature
(id: string) => boolean

normalizeTaskId()

Normalize a task ID input to canonical T#### format. Accepts various loose formats (lowercase prefix, bare digits, underscore-suffixed descriptors) and returns the canonical form, or null if the input cannot be parsed as a task ID. Signature
(input: unknown) => string | null

SecurityError

Security validation error thrown when input fails sanitization Signature
typeof SecurityError

sanitizeTaskId()

Sanitize and validate a task ID Signature
(value: unknown) => string

sanitizePath()

Sanitize and validate a file path Signature
(path: string, projectRoot: string) => string

sanitizeContent()

Sanitize content string Signature
(content: string, maxLength?: number) => string

validateEnum()

Validate that a value is in an allowed enum set Signature
(value: string, allowed: string[], fieldName: string) => string

RateLimiter

In-memory sliding window rate limiter Signature
typeof RateLimiter
Methods

check()

(key: string) => RateLimitResult

record()

(key: string) => void

consume()

(key: string) => RateLimitResult

reset()

(key?: string | undefined) => void

getConfig()

(key: string) => RateLimitConfig | undefined

setConfig()

(key: string, config: RateLimitConfig) => void

ensureArray()

Normalize a value to an array of strings. Handles MCP clients sending comma-separated strings where arrays are expected. Signature
(value: unknown, separator?: string) => string[] | undefined

sanitizeParams()

Sanitize all params in a request before routing Signature
(params: Record<string, unknown> | undefined, projectRoot?: string | undefined, context?: { domain?: string | undefined; operation?: string | undefined; } | undefined) => Record<...> | undefined

ClaudeCodeTransport

Claude Code transport — wraps the current provider-specific messaging. Registration and deregistration are no-ops because the Claude Code Agent SDK manages agent identity internally. Message sending is logged but actual delivery happens through the SDK’s SendMessage tool at the agent level. Signature
typeof ClaudeCodeTransport
Methods

register()

(name: string, agentClass: AgentClass, privacyTier: PrivacyTier) => Promise<AgentRegistration>

deregister()

(agentId: string) => Promise<void>

send()

(fromAgentId: string, toAgentId: string, content: string, conversationId?: string | undefined) => Promise<MessageResult>

poll()

(agentId: string, since?: string | undefined) => Promise<Message[]>

heartbeat()

(agentId: string) => Promise<void>

createConversation()

(participants: string[], visibility?: ConversationVisibility | undefined) => Promise<Conversation>

getAgent()

(agentId: string) => Promise<Agent | null>

SignalDockTransport

SignalDock HTTP transport implementation. Communicates with a SignalDock server via its REST API to provide provider-neutral inter-agent messaging with delivery guarantees. Signature
typeof SignalDockTransport
Methods

register()

(name: string, agentClass: AgentClass, privacyTier: PrivacyTier) => Promise<AgentRegistration>

deregister()

(agentId: string) => Promise<void>

send()

(fromAgentId: string, toAgentId: string, content: string, conversationId?: string | undefined) => Promise<MessageResult>

poll()

(agentId: string, _since?: string | undefined) => Promise<Message[]>

heartbeat()

(agentId: string) => Promise<void>

createConversation()

(participants: string[], visibility?: ConversationVisibility) => Promise<Conversation>

getAgent()

(agentId: string) => Promise<Agent | null>

request()

Make an HTTP request to the SignalDock API.
<T>(method: string, path: string, body?: unknown, agentId?: string | undefined) => Promise<T>

createTransport()

Create an AgentTransport instance based on configuration. Returns SignalDockTransport if signaldock is enabled, otherwise returns ClaudeCodeTransport as the default. Signature
(config?: TransportFactoryConfig | undefined) => AgentTransport

getSkillSearchPaths()

Build the CAAMP skill search paths in priority order. Uses CAAMP’s canonical path functions for standard locations. T4516 Signature
(cwd?: string | undefined) => SkillSearchPath[]

getSkillsDir()

Get the primary skills directory (app-embedded). T4516 Signature
(cwd?: string | undefined) => string

getSharedDir()

Get the shared skills resources directory. T4516 Signature
(cwd?: string | undefined) => string

mapSkillName()

Map a user-friendly skill name to the canonical ct-prefixed directory name. Supports: UPPER-CASE, lower-case, with/without ct- prefix. T4516 Signature
(input: string) => { canonical: string; mapped: boolean; }

listCanonicalSkillNames()

List all known canonical skill names (unique values from the map). T4516 Signature
() => string[]

parseFrontmatter()

Parse YAML-like frontmatter from a SKILL.md file. Handles the --- delimited header with key: value pairs. T4516 Signature
(content: string) => SkillFrontmatter

discoverSkill()

Discover a single skill from a directory. Tries CAAMP’s parseSkillFile first, falls back to local parsing. T4516 Signature
(skillDir: string) => Skill | null

discoverSkillsInDir()

Discover all skills in a single directory. Scans for subdirectories containing SKILL.md. T4516 Signature
(dir: string) => Skill[]

discoverAllSkills()

Discover all skills across CAAMP search paths. Returns skills in priority order (earlier paths take precedence). T4516 Signature
(cwd?: string | undefined) => Skill[]

findSkill()

Find a specific skill by name across all search paths. T4516 Signature
(name: string, cwd?: string | undefined) => Skill | null

toSkillSummary()

Convert a Skill to a lightweight SkillSummary. T4516 Signature
(skill: Skill) => SkillSummary

generateManifest()

Generate a skill manifest from discovered skills. T4516 Signature
(cwd?: string | undefined) => SkillManifest

resolveTemplatePath()

Resolve a skill template path (SKILL.md) by name. T4516 Signature
(name: string, cwd?: string | undefined) => string | null

getAgentsDir()

Get the agents directory path. T4518 Signature
(cwd?: string | undefined) => string

parseAgentConfig()

Parse an AGENT.md file into an AgentConfig. AGENT.md uses the same YAML frontmatter format as SKILL.md. T4518 Signature
(agentDir: string) => AgentConfig | null

loadAgentConfig()

Load agent configuration by name. Searches in the agents/ directory. T4518 Signature
(agentName: string, cwd?: string | undefined) => AgentConfig | null

getSubagentConfig()

Get the cleo-subagent configuration (universal executor). T4518 Signature
(cwd?: string | undefined) => AgentConfig | null

agentExists()

Check if an agent definition exists. T4518 Signature
(agentName: string, cwd?: string | undefined) => boolean

installAgent()

Install a single agent via symlink. T4518 Signature
(agentDir: string) => { installed: boolean; path: string; error?: string | undefined; }

installAllAgents()

Install all agents from the project agents/ directory. T4518 Signature
(cwd?: string | undefined) => { name: string; installed: boolean; error?: string | undefined; }[]

uninstallAgent()

Uninstall a single agent by removing its symlink. T4518 Signature
(agentName: string) => boolean

getRegistryPath()

Get the agent registry file path. T4518 Signature
() => string

readRegistry()

Read the agent registry, creating if needed. T4518 Signature
() => AgentRegistry

saveRegistry()

Save the agent registry. T4518 Signature
(registry: AgentRegistry) => void

registerAgent()

Register an agent in the registry. T4518 Signature
(name: string, path: string, config: AgentConfig) => AgentRegistryEntry

unregisterAgent()

Unregister an agent from the registry. T4518 Signature
(name: string) => boolean

getAgent()

Get an agent from the registry by name. T4518 Signature
(name: string) => AgentRegistryEntry | null

listAgents()

List all registered agents. T4518 Signature
() => AgentRegistryEntry[]

syncRegistry()

Scan the agents/ directory and register all found agents. T4518 Signature
(cwd?: string | undefined) => { added: string[]; removed: string[]; unchanged: string[]; }

loadPlaceholders()

Load token definitions from placeholders.json. T4521 Signature
(cwd?: string | undefined) => PlaceholdersConfig | null

buildDefaults()

Build the full default values map (merging placeholders.json with hardcoded defaults). T4521 Signature
(cwd?: string | undefined) => TokenValues

validateTokenValue()

Validate a single token value against its pattern. T4521 Signature
(token: string, value: string) => { valid: boolean; error?: string | undefined; }

validateRequired()

Validate all required tokens are present and valid. T4521 Signature
(values: TokenValues) => { valid: boolean; missing: string[]; invalid: { token: string; error: string; }[]; }

validateAllTokens()

Validate all tokens in a values map (required + optional). T4521 Signature
(values: TokenValues) => { valid: boolean; errors: { token: string; error: string; }[]; }

injectTokens()

Inject token values into a template string. Replaces all TOKEN_NAME patterns with corresponding values. Unresolved tokens are left as-is (for debugging). T4521 Signature
(template: string, values: TokenValues) => string

hasUnresolvedTokens()

Check if a template has unresolved tokens after injection. T4521 Signature
(content: string) => string[]

loadAndInject()

Load a skill template and inject tokens. T4521 Signature
(templatePath: string, values: TokenValues) => { content: string; unresolvedTokens: string[]; }

setFullContext()

Build a complete TokenValues map from a task, resolving all standard tokens. Ports ti_set_full_context from lib/skills/token-inject.sh. This is the primary entry point for orchestrators to prepare token values before spawning subagents. It populates: TASK_ID, DATE, TOPIC_SLUG, EPIC_ID, TITLE, TASK_TITLE, TASK_DESCRIPTION, TOPICS_JSON, DEPENDS_LIST, RESEARCH_ID, OUTPUT_DIR, MANIFEST_PATH, and all command defaults. T4712 T4663 Signature
(task: { id: string; title: string; description?: string | undefined; parentId?: string | undefined; labels?: string[] | undefined; depends?: string[] | undefined; }, options?: { date?: string | undefined; topicSlug?: string | undefined; outputDir?: string | undefined; manifestPath?: string | undefined; } | undefine...

autoDispatch()

Auto-dispatch a task to the most appropriate skill. Tries strategies in priority order: label - catalog - type - keyword - fallback. T4517 Signature
(task: Task, cwd?: string | undefined) => DispatchResult

dispatchExplicit()

Dispatch with explicit skill override. Verifies the skill exists before returning. T4517 Signature
(skillName: string, cwd?: string | undefined) => DispatchResult | null

getProtocolForDispatch()

Get the protocol type for a dispatch result. T4517 Signature
(result: DispatchResult) => SkillProtocolType | null

prepareSpawnContext()

Prepare spawn context for a dispatched skill. Returns the skill name and protocol needed for token injection. T4517 Signature
(task: Task, overrideSkill?: string | undefined, cwd?: string | undefined) => { skill: string; protocol: SkillProtocolType | null; dispatch: DispatchResult; }

prepareSpawnMulti()

Compose multiple skills into a single prompt with progressive disclosure. Ports skill_prepare_spawn_multi from lib/skills/skill-dispatch.sh. The first skill is loaded fully (primary). Secondary skills use progressive disclosure (frontmatter + first section only) to save context budget. T4712 T4663 Signature
(skillNames: string[], tokenValues: Record<string, string>, cwd?: string | undefined) => MultiSkillComposition

loadProtocolBase()

Load the subagent protocol base content. T4521 Signature
(cwd?: string | undefined) => string | null

buildTaskContext()

Build task context block for injection into a subagent prompt. T4521 Signature
(taskId: string, cwd?: string | undefined) => string

filterProtocolByTier()

Filter protocol content by MVI tier. Extracts sections based on !— TIER:X — markers. - tier 0: header + minimal only + footer - tier 1: header + minimal + standard + footer - tier 2: header + all tiers + footer (full content) Header = content before first TIER marker. Footer = content after last /TIER marker. T5155 Signature
(content: string, tier: 0 | 1 | 2) => string

injectProtocol()

Inject the subagent protocol into skill content. Composes: skill content + protocol base + task context. T4521 Signature
(skillContent: string, taskId: string, tokenValues: TokenValues, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => string

orchestratorSpawnSkill()

Full orchestrator spawn workflow (skill-based). High-level function that loads the skill, injects protocol, and returns the prompt. T4521 Signature
(taskId: string, skillName: string, tokenValues: TokenValues, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => string

prepareTokenValues()

Prepare standard token values for a task spawn. T4521 Signature
(taskId: string, topicSlug: string, epicId?: string | undefined, _cwd?: string | undefined) => TokenValues

installSkill()

Install a single skill via CAAMP. Signature
(skillName: string, projectDir?: string | undefined) => Promise<{ installed: boolean; path: string; error?: string | undefined; }>

generateContributionId()

Generate a unique contribution ID. T4520 Signature
(taskId: string) => string

validateContributionTask()

Validate that a task is suitable for contribution protocol. T4520 Signature
(taskId: string, cwd?: string | undefined) => { valid: boolean; issues: string[]; }

getContributionInjection()

Generate the contribution injection block for a subagent prompt. T4520 Signature
(taskId: string, protocolPath?: string | undefined, _cwd?: string | undefined) => string

detectConflicts()

Detect conflicts between two sets of decisions. T4520 Signature
(decisions1: ContributionDecision[], decisions2: ContributionDecision[]) => ContributionConflict[]

computeConsensus()

Compute weighted consensus from multiple agent decisions. T4520 Signature
(decisions: ContributionDecision[], weights?: Record<string, number> | undefined) => ConsensusResult

createContributionManifestEntry()

Create a manifest entry for a contribution. T4520 Signature
(taskId: string, contributionId: string, decisions: ContributionDecision[]) => ManifestEntry

ensureOutputs()

Ensure agent outputs directory and manifest file exist. T4520 Signature
(cwd?: string | undefined) => { created: string[]; }

readManifest()

Read all manifest entries. T4520 Signature
(cwd?: string | undefined) => ManifestEntry[]

appendManifest()

Append a manifest entry (atomic JSONL append). T4520 Signature
(entry: ManifestEntry, cwd?: string | undefined) => void

findEntry()

Find a manifest entry by ID. T4520 Signature
(id: string, cwd?: string | undefined) => ManifestEntry | null

filterEntries()

Filter manifest entries by criteria. T4520 Signature
(criteria: { status?: string | undefined; agentType?: string | undefined; topic?: string | undefined; linkedTask?: string | undefined; actionable?: boolean | undefined; }, cwd?: string | undefined) => ManifestEntry[]

getPendingFollowup()

Get entries with pending follow-ups. T4520 Signature
(cwd?: string | undefined) => ManifestEntry[]

getFollowupTaskIds()

Get unique follow-up task IDs from all manifest entries. T4520 Signature
(cwd?: string | undefined) => string[]

taskHasResearch()

Check if a task has linked research. T4520 Signature
(taskId: string, cwd?: string | undefined) => { hasResearch: boolean; count: number; }

archiveEntry()

Archive a manifest entry (move to archive status). T4520 Signature
(entryId: string, cwd?: string | undefined) => boolean

rotateManifest()

Rotate manifest by archiving old entries. T4520 Signature
(maxEntries?: number, cwd?: string | undefined) => number

isCacheFresh()

Check if the cached manifest is fresh (within TTL). T4520 Signature
(cachePath?: string | undefined) => boolean

invalidateCache()

Invalidate the cache (delete the cached manifest). T4520 Signature
() => void

resolveManifest()

Resolve the skills manifest. Returns a cached version if fresh, otherwise generates a new one. Graceful degradation: 1. Fresh cached manifest (within TTL) 2. Stale cached manifest (expired but valid) 3. Embedded project manifest (skills/manifest.json) 4. Freshly generated manifest T4520 Signature
(cwd?: string | undefined) => SkillManifest

regenerateCache()

Force regenerate the cache. T4520 Signature
(cwd?: string | undefined) => SkillManifest

loadConfig()

Load SkillsMP configuration from skillsmp.json. T4521 Signature
(cwd?: string | undefined) => SkillsMpConfig | null

searchSkills()

Search the skills marketplace. Delegates to CAAMP’s searchSkills for the actual API call. T4521 Signature
(query: string, _config?: SkillsMpConfig | undefined) => Promise<MarketplaceSkill[]>

getSkill()

Get a specific skill from the marketplace. Uses CAAMP’s MarketplaceClient for retrieval. T4521 Signature
(skillId: string, _config?: SkillsMpConfig | undefined) => Promise<MarketplaceSkill | null>

isEnabled()

Check if the marketplace is enabled and reachable. T4521 Signature
(cwd?: string | undefined) => boolean

buildPrompt()

Build a fully-resolved prompt for spawning a subagent. T4519 Signature
(taskId: string, templateName?: string, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => SpawnPromptResult

spawn()

Generate full spawn command with metadata. T4519 Signature
(taskId: string, templateName?: string, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => SpawnPromptResult & { spawnTimestamp: string; }

canParallelize()

Check if tasks can be spawned in parallel (no inter-dependencies). T4519 Signature
(taskIds: string[], cwd?: string | undefined) => { canParallelize: boolean; conflicts: (Pick<Task, "id"> & { dependsOn: string[]; })[]; safeToSpawn: string[]; }

spawnBatch()

Spawn prompts for multiple tasks in a batch. Ports orchestrator_spawn_batch from lib/skills/orchestrator-spawn.sh. Iterates over task IDs, building spawn prompts for each. Individual failures are captured per-entry rather than aborting the entire batch. T4712 T4663 Signature
(taskIds: string[], templateName?: string | undefined, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => BatchSpawnResult

getThresholds()

Get orchestrator context thresholds from config or defaults. T4519 Signature
(config?: Record<string, unknown> | undefined) => OrchestratorThresholds

getContextState()

Read the current context state from session-aware files. T4519 Signature
(sessionId?: string | undefined, cwd?: string | undefined) => ContextState

sessionInit()

Initialize orchestrator session state. Determines the recommended action based on current state. T4519 Signature
(_epicId?: string | undefined, cwd?: string | undefined) => Promise<SessionInitResult>

shouldPause()

Check if orchestrator should pause based on context usage. T4519 Signature
(config?: Record<string, unknown> | undefined, sessionId?: string | undefined, cwd?: string | undefined) => PauseStatus

analyzeDependencies()

Analyze dependency graph and compute execution waves. T4519 Signature
(epicId: string, cwd?: string | undefined) => Promise<DependencyAnalysis>

getNextTask()

Get the next task ready to spawn for an epic. T4519 Signature
(epicId: string, cwd?: string | undefined) => Promise<{ task: Task | null; readyCount: number; }>

getReadyTasks()

Get all tasks ready to spawn in parallel (no inter-dependencies). T4519 Signature
(epicId: string, cwd?: string | undefined) => Promise<TaskRefPriority[]>

generateHitlSummary()

Generate a Human-in-the-Loop summary for session handoff. T4519 Signature
(epicId?: string | undefined, stopReason?: string, cwd?: string | undefined) => Promise<HitlSummary>

validateSubagentOutput()

Validate a subagent’s manifest entry for protocol compliance. T4519 Signature
(researchId: string, cwd?: string | undefined) => { passed: boolean; issues: string[]; checkedRules: string[]; }

validateManifestIntegrity()

Validate the entire manifest file integrity. T4519 Signature
(cwd?: string | undefined) => ManifestValidationResult

verifyCompliance()

Verify previous agent completed protocol compliance before spawning next. T4519 Signature
(previousTaskId: string, researchId?: string | undefined, cwd?: string | undefined) => ComplianceResult

validateOrchestratorCompliance()

Validate orchestrator compliance (post-hoc behavioral checks). T4519 Signature
(epicId?: string | undefined, cwd?: string | undefined) => { compliant: boolean; violations: string[]; warnings: string[]; }

getSkillSearchPaths()

Get ordered skill search paths based on configuration. Priority: 1. CLEO_SKILL_PATH entries (colon-separated, explicit overrides) 2. Source-determined paths based on CLEO_SKILL_SOURCE CLEO_SKILL_SOURCE modes: - auto: CAAMP canonical + embedded (default) - caamp: CAAMP canonical only - embedded: Project embedded only T4552 Signature
(projectRoot?: string | undefined) => SkillSearchPath[]

resolveSkillPath()

Resolve a skill directory containing SKILL.md. Searches all paths from getSkillSearchPaths() in priority order. First match wins. T4552 Signature
(skillName: string, projectRoot?: string | undefined) => string | null

resolveProtocolPath()

Resolve a protocol .md file. Search order per base path: 1. base/_ct-skills-protocols/protocol_name.md (Strategy B shared dir) 2. PROJECT_ROOT/src/protocols/protocol_name.md (legacy embedded fallback) T4552 Signature
(protocolName: string, projectRoot?: string | undefined) => string | null

resolveSharedPath()

Resolve a shared resource .md file. Search order per base path: 1. base/_ct-skills-shared/resource_name.md (Strategy B shared dir) 2. base/_shared/resource_name.md (legacy embedded layout) T4552 Signature
(resourceName: string, projectRoot?: string | undefined) => string | null

getSkillSourceType()

Classify the source of a skill directory. Determines where a skill directory lives in the search hierarchy: - “embedded”: Within the project’s skills/ directory - “caamp”: Within the CAAMP canonical directory (~/.agents/skills) - “project-link”: Symlink pointing to project directory - “global-link”: Symlink pointing to CAAMP or external location T4552 Signature
(skillDir: string, projectRoot?: string | undefined) => SkillSourceType | null

formatIsoDate(inputDate)

Format a date string in ISO 8601 format. Converts a YYYY-MM-DD date string to a full ISO 8601 timestamp. Signature
(inputDate: string) => string
Parameters
NameTypeDescription
inputDatestringDate string in YYYY-MM-DD format
Returns — ISO 8601 formatted string (e.g., “2026-02-03T00:00:00Z”) Throws
  • Error if date format is invalid or missing T4552

getCurrentTimestamp()

Get current timestamp in ISO 8601 format. Returns the current UTC time as an ISO 8601 string. Signature
() => string
Returns — Current timestamp (e.g., “2026-02-16T14:30:00Z”) T4552

isValidIsoDate()

Validate that a string is a valid ISO 8601 date. T4552 Signature
(dateStr: string) => boolean

formatDateYMD()

Format a Date object to a YYYY-MM-DD string. T4552 Signature
(date: Date) => string

validateSkill()

Validate a skill directory structure and content. T4517 Signature
(skillDir: string) => SkillValidationResult

validateSkills()

Validate multiple skills at once. T4517 Signature
(skillDirs: string[]) => SkillValidationResult[]

validateReturnMessage()

Validate a return message against protocol-compliant patterns. T4517 Signature
(message: string) => { valid: boolean; error?: string | undefined; }

getInstalledVersionAsync()

Get the installed version of a skill from CAAMP lock state. Signature
(name: string) => Promise<string | null>

checkSkillUpdateAsync()

Check if a specific skill needs an update via CAAMP. Signature
(name: string) => Promise<{ needsUpdate: boolean; currentVersion?: string | undefined; latestVersion?: string | undefined; }>

checkAllSkillUpdatesAsync()

Check all installed skills for available updates via CAAMP. Signature
() => Promise<{ name: string; installedVersion: string; availableVersion: string; needsUpdate: boolean; }[]>

exportSnapshot()

Export current task state to a snapshot. T4882 Signature
(cwd?: string | undefined) => Promise<Snapshot>

writeSnapshot()

Write a snapshot to a file. T4882 Signature
(snapshot: Snapshot, outputPath: string) => Promise<void>

readSnapshot()

Read a snapshot from a file. T4882 Signature
(inputPath: string) => Promise<Snapshot>

getDefaultSnapshotPath()

Generate a default snapshot file path. T4882 Signature
(cwd?: string | undefined) => string

importSnapshot()

Import a snapshot into the local task database. Uses last-write-wins strategy: if a task exists locally and in the snapshot, the snapshot version wins only if its updatedAt is newer. T4882 Signature
(snapshot: Snapshot, cwd?: string | undefined) => Promise<ImportResult>

SpawnAdapterRegistry

Registry to manage spawn adapters. Maintains mappings between adapter IDs, provider IDs, and adapter instances. Supports registration, lookup, and capability-based filtering. Signature
typeof SpawnAdapterRegistry
Methods

register()

Register an adapter with the registry.
(adapter: CLEOSpawnAdapter) => void

get()

Get an adapter by its unique ID.
(adapterId: string) => CLEOSpawnAdapter | undefined

getForProvider()

Get the adapter registered for a specific provider.
(providerId: string) => CLEOSpawnAdapter | undefined

hasAdapterForProvider()

Check if an adapter is registered for a given provider.
(providerId: string) => boolean

list()

List all registered adapters.
() => CLEOSpawnAdapter[]

listSpawnCapable()

List adapters for providers that have spawn capability. Queries CAAMP for spawn-capable providers and returns the corresponding registered adapters.
() => Promise<CLEOSpawnAdapter[]>

canProviderSpawn()

Check if a provider can spawn subagents. Uses providerSupportsById to check if the provider supports the spawn.supportsSubagents capability.
(providerId: string) => Promise<boolean>

clear()

Clear all adapter registrations. Removes all adapters and provider mappings from the registry.
() => void

getProvidersWithSpawnCapability(capability)

Get providers by specific spawn capability Queries CAAMP for providers that support a specific spawn capability. Signature
(capability: SpawnCapability) => Provider[]
Parameters
NameTypeDescription
capabilitySpawnCapabilityThe spawn capability to filter by
Returns — Array of providers with the specified capability

hasParallelSpawnProvider()

Check if any provider supports parallel spawn Signature
() => boolean
Returns — True if at least one provider supports parallel spawn

initializeSpawnAdapters(manifests)

Initialize spawn adapters dynamically from discovered adapter manifests. Scans all discovered manifests for adapters with capabilities.supportsSpawn, dynamically imports their spawn provider, and bridges it into the spawn registry. Zero hardcoded adapter names — everything derives from manifests. Signature
(manifests: AdapterManifest[]) => Promise<void>
Parameters
NameTypeDescription
manifestsAdapterManifest[]Discovered adapter manifests (from AdapterManager.discover())
Returns — Promise that resolves when initialization is complete

initializeDefaultAdapters()

Initialize the registry with default adapters. Legacy entry point that discovers adapters from the project root and delegates to initializeSpawnAdapters(). Maintains backward compatibility for callers that don’t have manifests handy. Signature
() => Promise<void>
Returns — Promise that resolves when initialization is complete

getProjectStats()

Get project statistics. Signature
(opts: { period?: string | undefined; verbose?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

rankBlockedTask()

Compute a ranking score for a blocked task. Higher score = more urgent = sort first. Signature
(task: Task, allTasks: Task[], focusTask: Task | null) => number

getDashboard()

Get project dashboard data. Signature
(opts: { compact?: boolean | undefined; period?: number | undefined; showCharts?: boolean | undefined; sections?: string[] | undefined; verbose?: boolean | undefined; quiet?: boolean | undefined; cwd?: string | undefined; blockedTasksLimit?: number | undefined; }, accessor?: DataAccessor | undefined) => Promise<...>

getCompletionHistory()

Get completion history data. Signature
(opts: { days?: number | undefined; since?: string | undefined; until?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>

filterByDate()

Filter tasks by date range on archivedAt. Signature
(tasks: AnalyticsTask[], since?: string | undefined, until?: string | undefined) => AnalyticsTask[]

summaryReport()

Generate summary statistics. Signature
(tasks: AnalyticsTask[]) => SummaryReportData

byPhaseReport()

Group tasks by phase with cycle time averages. Signature
(tasks: AnalyticsTask[]) => PhaseGroupEntry[]

byLabelReport()

Group tasks by label frequency. Signature
(tasks: AnalyticsTask[]) => LabelFrequencyEntry[]

byPriorityReport()

Group tasks by priority with cycle time averages. Signature
(tasks: AnalyticsTask[]) => PriorityGroupEntry[]

cycleTimesReport()

Compute cycle time statistics with distribution buckets. Signature
(tasks: AnalyticsTask[]) => CycleTimesReportData

trendsReport()

Compute archive trends by day and month. Signature
(tasks: AnalyticsTask[]) => TrendsReportData

analyzeArchive()

Analyze archived tasks and produce a report. This is the primary entry point for archive analytics. It loads archive data from the DataAccessor, normalizes task records, applies date filters, and delegates to the appropriate report function. Signature
(opts: AnalyzeArchiveOptions, accessor?: DataAccessor | undefined) => Promise<ArchiveAnalyticsResult<ArchiveReportType>>

getArchiveStats()

Get archive statistics. Signature
(opts: { period?: number | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<ArchiveStatsResult>

auditData()

Audit data integrity. Signature
(projectRoot: string, opts?: { scope?: string | undefined; fix?: boolean | undefined; } | undefined) => Promise<AuditResult>

createBackup()

Create a backup of CLEO data files. Signature
(projectRoot: string, opts?: { type?: string | undefined; note?: string | undefined; } | undefined) => BackupResult

restoreBackup()

Restore from a backup. Signature
(projectRoot: string, params: { backupId: string; force?: boolean | undefined; }) => RestoreResult

cleanupSystem()

Cleanup stale data (sessions, backups, logs). Signature
(projectRoot: string, params: { target: string; olderThan?: string | undefined; dryRun?: boolean | undefined; }) => Promise<CleanupResult>

writeJsonFileAtomic(filePath, data, indent)

Write a JSON file atomically with backup rotation. Pattern: write temp - backup original - rename temp to target Signature
<T>(filePath: string, data: T, indent?: number) => void
Parameters
NameTypeDescription
filePathstringTarget file path
dataTData to serialize as JSON
indent: numberJSON indentation (default: 2 spaces)

readJsonFile(filePath)

Read a JSON file, returning parsed content or null if not found. Signature
<T = unknown>(filePath: string) => T | null
Parameters
NameTypeDescription
filePathstringPath to the JSON file

getDataPath(projectRoot, filename)

Get the path to a CLEO data file within a project root. Signature
(projectRoot: string, filename: string) => string
Parameters
NameTypeDescription
projectRootstringRoot directory of the project
filenamestringFilename within .cleo/ directory

resolveProjectRoot()

Resolve the project root directory. Checks CLEO_ROOT env, then falls back to cwd. Signature
() => string

withLock(filePath, transform)

Read and write a JSON file with exclusive locking. Acquires a cross-process lock, reads current state, applies the transform function, validates, and writes back atomically. Signature
<T>(filePath: string, transform: (current: T | null) => T) => Promise<T>
Parameters
NameTypeDescription
filePathstringFile to lock and modify
transform(current: T | nullFunction that receives current data and returns new data
Returns — The transformed data

withFileLock()

Acquire a file lock and execute an operation. Unlike withLock, this doesn’t read/write the file - caller manages I/O. The return type R is independent of the file content type. Signature
<R>(filePath: string, operation: () => R | Promise<R>) => Promise<R>

withMultiLock(filePaths, operation)

Acquire locks on multiple files in correct order. Used for operations that need to modify multiple files atomically (e.g., coordinated updates across task data and config). Signature
<T>(filePaths: string[], operation: () => T | Promise<T>) => Promise<T>
Parameters
NameTypeDescription
filePathsstring[]Files to lock
operation(Function to execute while locks are held

isProjectInitialized()

Check if a CLEO project directory exists at the given path Signature
(projectRoot: string) => boolean

listBackups()

List backup files for a given data file Signature
(filePath: string) => string[]

detectPlatform()

Detect the current platform. Signature
() => Platform

commandExists()

Check if a command exists on PATH. Signature
(command: string) => boolean

requireTool()

Require a tool to be available, returning an error message if missing. Signature
(tool: string, installHint?: string | undefined) => { available: boolean; error?: string | undefined; }

checkRequiredTools()

Check all required tools. Signature
(tools: { name: string; installHint?: string | undefined; }[]) => { allAvailable: boolean; missing: string[]; }

getIsoTimestamp()

Get ISO 8601 UTC timestamp. Signature
() => string

isoToEpoch()

Convert ISO timestamp to epoch seconds. Signature
(isoTimestamp: string) => number

dateDaysAgo()

Get ISO date for N days ago. Signature
(days: number) => string

getFileSize()

Get file size in bytes. Signature
(filePath: string) => number

getFileMtime()

Get file modification time as ISO string. Signature
(filePath: string) => string | null

generateRandomHex()

Generate N random hex characters. Signature
(bytes?: number) => string

sha256()

Compute SHA-256 checksum of a string. Signature
(data: string) => string

createTempFilePath()

Create a temporary file path. Signature
(prefix?: string, suffix?: string) => string

getNodeVersionInfo()

Get Node.js version info. Signature
() => { version: string; major: number; minor: number; patch: number; meetsMinimum: boolean; }

getNodeUpgradeInstructions()

Get platform-specific Node.js upgrade instructions. Returns actionable install/upgrade guidance based on OS and available tools. Signature
() => { platform: Platform; arch: string; instructions: string[]; recommended: string; }

getSystemInfo()

Gather a snapshot of the host system. This is the SSoT for system information. Use this instead of scattering process.platform / os.type() calls throughout the codebase. Use cases: - Logger base context (every log entry carries platform info) - Error reports and issue submission - Doctor diagnostics - Startup health check results Signature
() => SystemInfo

checkCliInstallation()

T4525 Signature
(cleoHome?: string) => CheckResult

checkCliVersion()

T4525 Signature
(cleoHome?: string) => CheckResult

checkDocsAccessibility()

T4525 Signature
(cleoHome?: string) => CheckResult

checkAtReferenceResolution()

T4525 Signature
(cleoHome?: string) => CheckResult

checkAgentsMdHub()

Check that AGENTS.md exists in project root and contains the CAAMP:START marker, indicating it serves as the injection hub for CLEO protocol content. Signature
(projectRoot?: string | undefined) => CheckResult

checkRootGitignore()

Check if project root .gitignore is blocking the entire .cleo/ directory. This prevents core CLEO data from being tracked by git. T4641 T4637 Signature
(projectRoot?: string | undefined) => CheckResult

checkCleoGitignore()

Check if .cleo/.gitignore exists and matches the template. T4700 Signature
(projectRoot?: string | undefined) => CheckResult

checkVitalFilesTracked()

Check that vital CLEO configuration files are tracked by git. Only checks config files (config.json, .gitignore, project-info.json, project-context.json). SQLite databases are excluded per ADR-013. T4700 Signature
(projectRoot?: string | undefined) => CheckResult

checkCoreFilesNotIgnored()

Check that core CLEO files are not being ignored by .gitignore. Uses git check-ignore to detect files that would be excluded by any gitignore rule (root, .cleo/, or global). Returns critical status if any protected file is gitignored. Signature
(projectRoot?: string | undefined) => CheckResult

checkSqliteNotTracked()

Check that SQLite databases (.cleo/tasks.db) are NOT tracked by project git. Tracked SQLite files cause data loss from merge conflicts (ADR-013). Warns if tasks.db is currently tracked so the user can untrack it. T5160 Signature
(projectRoot?: string | undefined) => CheckResult

checkLegacyAgentOutputs()

Check if any legacy output directories still exist. Delegates detection to the migration/agent-outputs utility. T4700 Signature
(projectRoot?: string | undefined) => CheckResult

checkCaampMarkerIntegrity()

Verify balanced CAAMP:START/END markers in CLAUDE.md and AGENTS.md. T5153 Signature
(projectRoot?: string | undefined) => CheckResult

checkAtReferenceTargetExists()

Parse references from AGENTS.md CAAMP block and verify each target file exists. T5153 Signature
(projectRoot?: string | undefined) => CheckResult

checkTemplateFreshness()

Compare templates/CLEO-INJECTION.md vs ~/.cleo/templates/CLEO-INJECTION.md. T5153 Signature
(projectRoot?: string | undefined, cleoHome?: string | undefined) => CheckResult

checkTierMarkersPresent()

Verify all 3 tier markers exist with matching close tags in deployed template. T5153 Signature
(cleoHome?: string | undefined) => CheckResult

checkNodeVersion()

Check that Node.js meets the minimum required version. Provides OS-specific upgrade instructions when below minimum. Signature
() => CheckResult

checkGlobalSchemaHealth()

Check that global schemas at ~/.cleo/schemas/ are installed and not stale. Delegates to checkGlobalSchemas() from schema-management.ts. Signature
(_projectRoot?: string | undefined) => CheckResult

checkNoLocalSchemas()

Warn if deprecated .cleo/schemas/ directory still exists in the project. Schemas should live in ~/.cleo/schemas/ (global), not in project directories. Signature
(projectRoot?: string | undefined) => CheckResult

checkJsonSchemaIntegrity()

Check that active JSON files (config.json, project-info.json, etc.) are valid against their schemas and have current schema versions. Maps JsonFileIntegrityResult[] from checkSchemaIntegrity() into CheckResult[], then returns a single rolled-up CheckResult for the doctor summary. Signature
(projectDir: string) => Promise<CheckResult>

runAllGlobalChecks()

Run all global health checks and return results array. T4525 Signature
(cleoHome?: string | undefined, projectRoot?: string | undefined) => CheckResult[]

calculateHealthStatus()

Calculate overall status from check results. Returns: 0=passed, 50=warning, 52=critical. T4525 Signature
(checks: CheckResult[]) => number

getSystemHealth()

Run system health checks (SQLite-first per ADR-006). Signature
(projectRoot: string, opts?: { detailed?: boolean | undefined; } | undefined) => HealthResult

getSystemDiagnostics()

Run extended diagnostics with fix suggestions. Signature
(projectRoot: string, opts?: { checks?: string[] | undefined; } | undefined) => Promise<DiagnosticsResult>

coreDoctorReport()

Run comprehensive doctor diagnostics combining dependency checks, directory checks, data file checks, gitignore checks, and environment info. T4795 Signature
(projectRoot: string) => Promise<DoctorReport>

runDoctorFixes()

Run auto-fix for failed doctor checks by calling the corresponding ensure* functions. Returns a list of fix results for each attempted repair. Signature
(projectRoot: string) => Promise<FixResult[]>

startupHealthCheck(projectRoot)

Unified startup health check for MCP server and CLI entry points. This is the single entry point for startup diagnostics. It follows a three-phase approach: Phase 1: Global scaffold (~/.cleo/) — always auto-repaired. The global home is CLEO infrastructure, not project data. It is safe to create/repair unconditionally on every startup. Phase 2: Project detection — determines if this is an initialized project. Uses isProjectInitialized() from paths.ts as the SSoT for detection. Phase 3: Project health — lightweight checks on the project scaffold. If the project is initialized, runs check* functions to detect drift. Auto-repairs safe items (missing subdirs via ensureCleoStructure). Flags items requiring full upgrade (missing DB, config issues). Design principles: - SSoT: All checks delegate to scaffold.ts check* functions - DRY: No duplicated health-check logic - SRP: This function only diagnoses and does safe auto-repair - Graceful: Never throws. All errors are captured as check results. - Logged: Returns structured results for the caller to log via pino Signature
(projectRoot?: string | undefined) => Promise<StartupHealthResult>
Parameters
NameTypeDescription
projectRoot: string | undefinedAbsolute path to the project root (defaults to cwd)

generateInjection()

Generate Minimum Viable Injection (MVI) markdown. Signature
(projectRoot: string, accessor?: DataAccessor | undefined) => Promise<InjectGenerateResult>

getLabels()

Get all labels with counts and task IDs per label. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<LabelsResult>

getSystemMetrics()

Get system metrics: token usage, compliance summary, session counts. Signature
(projectRoot: string, opts?: { scope?: string | undefined; since?: string | undefined; } | undefined, accessor?: DataAccessor | undefined) => Promise<SystemMetricsResult>

getMigrationStatus()

Check/report schema migration status. Signature
(projectRoot: string, opts?: { target?: string | undefined; dryRun?: boolean | undefined; } | undefined) => Promise<MigrateResult>

getRuntimeDiagnostics()

Signature
(options?: { detailed?: boolean | undefined; } | undefined) => Promise<RuntimeDiagnostics>

safestop()

Safe stop: signal clean shutdown for agents. Signature
(projectRoot: string, opts?: { reason?: string | undefined; commit?: boolean | undefined; handoff?: string | undefined; noSessionEnd?: boolean | undefined; dryRun?: boolean | undefined; } | undefined) => SafestopResult

uncancelTask()

Uncancel a cancelled task (restore to pending). Signature
(projectRoot: string, params: { taskId: string; cascade?: boolean | undefined; notes?: string | undefined; dryRun?: boolean | undefined; }) => Promise<UncancelResult>

detectCircularDeps()

Detect circular dependencies using DFS. Returns the cycle path if found, empty array otherwise. Signature
(taskId: string, tasks: Task[]) => string[]

wouldCreateCycle()

Check if adding a dependency would create a cycle. Signature
(fromId: string, toId: string, tasks: Task[]) => boolean

getBlockedTasks()

Get tasks that are blocked (have unmet dependencies). Signature
(tasks: Task[]) => Task[]

getReadyTasks()

Get tasks that are ready (all dependencies met). Signature
(tasks: Task[]) => Task[]

getDependents()

Get tasks that depend on a given task. Signature
(taskId: string, tasks: Task[]) => Task[]

getDependentIds()

Get dependent IDs. Signature
(taskId: string, tasks: Task[]) => string[]

getUnresolvedDeps()

Get unresolved dependencies for a task (deps that are not done/cancelled). Signature
(taskId: string, tasks: Task[]) => string[]

validateDependencyRefs()

Validate dependencies for missing references. Signature
(tasks: Task[]) => DependencyError[]

validateDependencies()

Full dependency graph validation. Signature
(tasks: Task[]) => DependencyCheckResult

topologicalSort()

Topological sort of tasks by dependencies. Returns sorted task IDs or null if cycle detected. Signature
(tasks: Task[]) => string[] | null

getTransitiveBlockers()

Walk upstream recursively through a task’s dependency chain. Returns all non-done/non-cancelled dependency IDs (deduplicated). Uses a visited set for cycle protection. Signature
(taskId: string, tasks: Task[]) => string[]

getLeafBlockers()

From the transitive blockers, return only “leaf” blockers — those whose own dependencies are all resolved (done/cancelled) or that have no dependencies at all. These are the root-cause tasks that need action first. Signature
(taskId: string, tasks: Task[]) => string[]

currentTask()

Show current task work state. T4462 T4750 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskCurrentResult>

startTask()

Start working on a specific task. T4462 T4750 Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskStartResult>

stopTask()

Stop working on the current task. T4462 T4750 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ previousTask: string | null; }>

getWorkHistory()

Get task work history from session notes. T4462 T4750 Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskWorkHistoryEntry[]>

parseIssueTemplates()

Parse all templates from the repo’s .github/ISSUE_TEMPLATE/ directory. Reads YAML files directly (live parse, no caching). Excludes config.yml which is the GitHub template chooser config. Signature
(projectRoot: string) => TemplateResult<TemplateConfig>

getTemplateForSubcommand()

Get template config for a specific subcommand (bug/feature/help). Performs a live parse and filters to the matching template. Signature
(projectRoot: string, subcommand: string) => TemplateResult<IssueTemplate>

generateTemplateConfig()

Generate and cache the config as .cleo/issue-templates.json. Performs a live parse, then writes the result using writeJsonFileAtomic. Signature
(projectRoot: string) => Promise<TemplateResult<TemplateConfig>>

validateLabels()

Validate that labels exist on a GitHub repo. Compares the template labels against a list of known repo labels. Returns which labels exist and which are missing. Signature
(labels: string[], repoLabels: string[]) => TemplateResult<{ existing: string[]; missing: string[]; }>

getCurrentShell()

Detect the current shell. Signature
() => ShellType

getRcFilePath()

Get the RC file path for a shell. Signature
(shell?: ShellType | undefined) => string

detectAvailableShells()

Detect which shells are available on the system. Signature
() => ShellType[]

generateBashAliases()

Generate bash/zsh alias content. Signature
(cleoPath?: string | undefined) => string

generatePowershellAliases()

Generate PowerShell alias content. Signature
(cleoPath?: string | undefined) => string

hasAliasBlock()

Check if aliases are already injected in a file. Signature
(filePath: string) => boolean

getInstalledVersion()

Get the installed alias version from an RC file. Signature
(filePath: string) => string | null

injectAliases()

Inject aliases into a shell RC file. Signature
(filePath: string, shell?: ShellType, cleoPath?: string | undefined) => { action: "created" | "updated" | "added"; version: string; }

removeAliases()

Remove aliases from a shell RC file. Signature
(filePath: string) => boolean

checkAliasesStatus()

Get alias status for the current shell. Signature
(shell?: ShellType | undefined) => { shell: ShellType; rcFile: string; installed: boolean; version: string | null; needsUpdate: boolean; }

discoverReleaseTasks()

Discover task IDs for a release from completed tasks. Optionally filtered by date range or specific task IDs. Signature
(options?: { since?: string | undefined; until?: string | undefined; taskIds?: string[] | undefined; }, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<...>

groupTasksIntoSections()

Group tasks into changelog sections. Signature
(tasks: ChangelogTask[]) => ChangelogSection[]

generateChangelogMarkdown()

Generate changelog markdown for a version. Signature
(version: string, date: string, sections: ChangelogSection[]) => string

formatChangelogJson()

Format changelog data as JSON. Signature
(version: string, date: string, sections: ChangelogSection[]) => Record<string, unknown>

writeChangelogFile()

Write changelog content to a file. Signature
(filePath: string, content: string) => void

appendToChangelog()

Append a new release section to an existing CHANGELOG.md. Signature
(filePath: string, newContent: string) => void

generateChangelog()

Full changelog generation: discover tasks, group, generate, write. Signature
(version: string, options?: { since?: string | undefined; until?: string | undefined; taskIds?: string[] | undefined; outputPath?: string | undefined; append?: boolean | undefined; }, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<...>

parseCommandHeader()

Parse a ###CLEO header block from a script file. Signature
(scriptPath: string) => CommandMeta | null

scanAllCommands()

Scan a scripts directory and build a command registry. Returns a map of command name to metadata. Signature
(scriptsDir: string) => Map<string, CommandMeta>

validateHeader()

Validate a command header has required fields. Signature
(meta: CommandMeta) => { valid: boolean; errors: string[]; }

getCommandScriptMap()

Get command-to-script mapping. Signature
(scriptsDir: string) => Record<string, string>

getCommandsByCategory()

Group commands by category. Signature
(scriptsDir: string) => Record<string, CommandMeta[]>

getCommandsByRelevance()

Filter commands by relevance level. Signature
(scriptsDir: string, relevance: string) => CommandMeta[]

defaultFlags()

Default flag values. Signature
() => ParsedFlags

parseCommonFlags()

Parse common CLI flags from an argument array. Returns flags and remaining positional arguments. Signature
(args: string[]) => ParsedFlags

resolveFormat()

Resolve output format based on flags and TTY detection. Returns ‘json’ for non-TTY (piped), ‘human’ for TTY. Signature
(flagFormat: string) => "json" | "human"

isJsonOutput()

Check if output should be JSON. Signature
(flags: ParsedFlags) => boolean

getValidationKey()

Get the validation key for a target filename. Signature
(target: string) => string

extractMarkerVersion()

Extract the CLEO version from an injection marker string. Returns null if no version is present (current format). Returns the version string for legacy format. Signature
(markerLine: string) => string | null

checkManifestEntry()

Verify a manifest entry for a task has valid required fields. T4524 Signature
(entry: ManifestEntry | null) => ManifestIntegrity

checkReturnFormat()

Check if a response matches the expected return format. T4524 Signature
(response: string) => boolean

scoreSubagentCompliance()

Calculate comprehensive compliance score for a subagent. T4524 Signature
(taskId: string, agentId: string, manifestEntry: ManifestEntry | null, researchLinked: boolean, response: string) => ComplianceMetrics

calculateTokenEfficiency()

Calculate token efficiency metrics. T4524 Signature
(tokensUsed: number, maxTokens?: number, tasksCompleted?: number, inputTokens?: number, outputTokens?: number) => TokenEfficiency

calculateOrchestrationOverhead()

Calculate orchestration overhead metrics. T4524 Signature
(orchestratorTokens: number, totalSubagentTokens: number, numSubagents?: number) => OrchestrationOverhead

getScriptCommands()

Get command names from scripts directory. Returns sorted list of script basenames without .sh extension. T4527 Signature
(scriptsDir: string) => string[]

getIndexScripts()

Get script names from COMMANDS-INDEX.json. T4527 Signature
(indexPath: string) => string[]

getIndexCommands()

Get command names from COMMANDS-INDEX.json. T4527 Signature
(indexPath: string) => string[]

checkCommandsSync()

Check commands index vs scripts directory for sync. T4527 Signature
(scriptsDir: string, indexPath: string) => DriftIssue[]

checkWrapperSync()

Check wrapper template sync with COMMANDS-INDEX. T4527 Signature
(wrapperPath: string, indexPath: string) => DriftIssue[]

detectDrift()

Run full drift detection across scripts, index, wrapper, and README. T4527 Signature
(mode?: "full" | "quick", projectRoot?: string) => DriftReport

shouldRunDriftDetection()

Check if drift detection should run automatically based on config. T4527 Signature
(enabled?: boolean, autoCheck?: boolean, command?: string | undefined, criticalCommands?: string[]) => boolean

getCacheFilePath()

Get cache file path. T4525 Signature
(cleoHome?: string | undefined) => string

initCacheFile()

Initialize empty cache file. T4525 Signature
(cacheFile: string) => DoctorProjectCache

loadCache()

Load cache file or return null if missing/invalid. T4525 Signature
(cacheFile: string) => DoctorProjectCache | null

getFileHash()

Get file hash for cache invalidation. T4525 Signature
(filePath: string) => string

getCachedValidation()

Check if project validation is cached and valid. Returns the cache entry if valid, null if cache miss. T4525 Signature
(projectHash: string, projectPath: string, cacheFile?: string | undefined) => ProjectCacheEntry | null

cacheValidationResult()

Cache project validation results. T4525 Signature
(projectHash: string, projectPath: string, validationStatus: "warning" | "failed" | "passed", issues?: string[], schemaVersions?: SchemaVersions, cacheFile?: string | undefined) => void

clearProjectCache()

Clear cache for a specific project. T4525 Signature
(projectHash: string, cacheFile?: string | undefined) => void

clearEntireCache()

Clear entire cache. T4525 Signature
(cacheFile?: string | undefined) => void

isTempProject()

Check if a project path is a temporary/test directory. T4525 Signature
(path: string) => boolean

categorizeProjects()

Filter projects into categories: active, temp, orphaned. T4525 Signature
(projects: ProjectDetail[]) => CategorizedProjects

getProjectCategoryName()

Get human-readable project category name. T4525 Signature
(category: "active" | "orphaned" | "temp") => string

formatProjectHealthSummary()

Format project health summary for display. T4525 Signature
(summary: HealthSummary) => string

getProjectGuidance()

Get actionable guidance for project issues. T4525 Signature
(activeFailed: number, activeWarnings: number, tempCount: number, orphanedCount: number) => string[]

getUserJourneyStage()

Check user journey stage based on system state. T4525 Signature
(hasProjects: boolean, tempProjectCount: number, agentConfigsOk: boolean) => UserJourneyStage

getJourneyGuidance()

Get journey-specific guidance text. T4525 Signature
(stage: UserJourneyStage) => string[]

sanitizeFilePath()

Sanitize a file path for safe shell usage. Prevents command injection via malicious file names. T4523 Signature
(path: string) => string

validateTitle()

Validate a task title. Checks for emptiness, newlines, invisible characters, control chars, and length. T4523 Signature
(title: string) => ValidationResult

validateDescription()

T4523 Signature
(desc: string) => ValidationResult

validateNote()

T4523 Signature
(note: string) => ValidationResult

validateBlockedBy()

T4523 Signature
(reason: string) => ValidationResult

validateSessionNote()

T4523 Signature
(note: string) => ValidationResult

validateCancelReason()

Validate a cancellation reason. T4523 Signature
(reason: string) => ValidationResult

validateStatusTransition()

Validate that a status transition is allowed. T4523 Signature
(oldStatus: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived", newStatus: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived") => ValidationResult

isValidStatus()

Check if a status string is valid. T4523 Signature
(status: string) => status is "cancelled" | "pending" | "active" | "blocked" | "done" | "archived"

checkTimestampSanity()

Check timestamp format and sanity. T4523 Signature
(createdAt: string, completedAt?: string | undefined) => ValidationResult

isMetadataOnlyUpdate()

Check if an update contains only metadata fields (safe for done tasks). T4523 Signature
(fields: string[]) => boolean

normalizeLabels()

Deduplicate and normalize labels. T4523 Signature
(labels: string) => string

checkIdUniqueness()

Check ID uniqueness within and across files. T4523 Signature
(taskFile: TaskFile, archiveFile?: ArchiveFile | undefined) => ValidationResult

validateTask()

Validate a single task object. T4523 Signature
(task: Task) => ValidationResult

validateNoCircularDeps()

Check for circular dependencies using DFS. T4523 Signature
(tasks: Task[], taskId: string, newDeps: string[]) => ValidationResult

validateSingleActivePhase()

Validate only one phase is active. T4523 Signature
(taskFile: TaskFile) => ValidationResult

validateCurrentPhaseConsistency()

Validate currentPhase matches an active phase. T4523 Signature
(taskFile: TaskFile) => ValidationResult

validatePhaseTimestamps()

Validate phase timestamp ordering. T4523 Signature
(taskFile: TaskFile) => ValidationResult

validatePhaseStatusRequirements()

Validate phase status requirements (e.g., active phases must have startedAt). T4523 Signature
(taskFile: TaskFile) => ValidationResult

validateAll()

Run all validation checks on a TaskFile. T4523 Signature
(taskFile: TaskFile, archiveFile?: ArchiveFile | undefined) => ComprehensiveValidationResult

parseManifest()

Parse a MANIFEST.jsonl file into entries. Skips invalid JSON lines gracefully. T4524 Signature
(content: string) => ManifestDoc[]

findReviewDocs()

Find documents in review status. T4524 Signature
(entries: ManifestDoc[], filterId?: string | undefined) => ManifestDoc[]

extractTopics()

Extract markdown headings from file content. T4524 Signature
(content: string) => string[]

searchCanonicalCoverage()

Search for topic coverage in a docs directory. Returns count of matching files. T4524 Signature
(topic: string, docsFileContents: Map<string, string>) => { topic: string; matches: number; files: string[]; }

analyzeCoverage()

Analyze documentation coverage for review documents. T4524 Signature
(reviewDocs: ManifestDoc[], docsFileContents: Map<string, string>, filterId?: string | undefined) => GapReport

formatGapReport()

Format a gap report for human-readable display. T4524 Signature
(report: GapReport) => string

findManifestEntry()

Find a manifest entry for a task ID in a JSONL file. T4526 Signature
(taskId: string, manifestPath?: string | undefined) => Promise<ManifestEntry | null>

validateManifestEntry()

Run validation on a manifest entry for a specific task. T4526 Signature
(taskId: string, manifestEntry?: ManifestEntry | null | undefined, manifestPath?: string) => Promise<ManifestValidationResult>

logRealCompliance()

Log validation results to the compliance JSONL file. T4526 Signature
(taskId: string, validationResult: ManifestValidationResult, agentType?: string, compliancePath?: string) => Promise<void>

validateAndLog()

Find, validate, and log compliance for a task in one call. T4526 Signature
(taskId: string, manifestPath?: string, compliancePath?: string) => Promise<ManifestValidationResult>

checkOutputFileExists()

Check if expected output file exists. T4527 Signature
(taskId: string, expectedDir: string, pattern?: string | undefined) => boolean

checkDocumentationSections()

Check if file contains required documentation sections. T4527 Signature
(filePath: string, sections: string[]) => boolean

checkReturnMessageFormat()

Check if return message follows protocol format. Expected: ” . See MANIFEST.jsonl for .” T4527 Signature
(message: string, _protocolType?: string | undefined) => boolean

checkManifestFieldPresent()

Check if manifest entry has a required field (non-null, non-empty). T4527 Signature
(entry: Record<string, unknown>, fieldName: string) => boolean

checkManifestFieldType()

Check if manifest field has expected type. T4527 Signature
(entry: Record<string, unknown>, fieldName: string, expectedType: "string" | "number" | "boolean" | "object" | "array") => boolean

checkKeyFindingsCount()

Check if key_findings array has valid count (3-7). T4527 Signature
(entry: Record<string, unknown>) => boolean

checkStatusValid()

Check if status is valid enum value. T4527 Signature
(entry: Record<string, unknown>) => boolean

checkAgentType()

Check if agent_type matches expected value. T4527 Signature
(entry: Record<string, unknown>, expectedType: string) => boolean

checkLinkedTasksPresent()

Check if linked_tasks array contains required task IDs. T4527 Signature
(entry: Record<string, unknown>, requiredIds: string[]) => boolean

checkProvenanceTags()

Check if file contains provenance tag. T4527 Signature
(filePath: string, taskId?: string | undefined) => boolean

validateCommonManifestRequirements()

Validate common manifest requirements across all protocols. T4527 Signature
(entry: Record<string, unknown>, _protocolType?: string | undefined) => ProtocolValidationResult

isValidGateName()

T4526 Signature
(name: string) => name is "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented"

isValidAgentName()

T4526 Signature
(name: string) => name is "testing" | "planner" | "coder" | "qa" | "cleanup" | "security" | "docs"

getGateOrder()

T4526 Signature
() => ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]

getGateIndex()

T4526 Signature
(gateName: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented") => number

getDownstreamGates()

T4526 Signature
(fromGate: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented") => ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]

initVerification()

Initialize a new verification object with default values. T4526 Signature
() => Verification

computePassed()

Compute whether verification has passed based on required gates. T4526 Signature
(verification: Verification, requiredGates?: ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]) => boolean

setVerificationPassed()

Update the passed field on a verification object. T4526 Signature
(verification: Verification, passed: boolean) => Verification

updateGate()

Update a single gate value. T4526 Signature
(verification: Verification, gateName: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented", value: boolean | null, agent?: string | undefined) => Verification

resetDownstreamGates()

Reset all downstream gates to null after a gate failure. T4526 Signature
(verification: Verification, fromGate: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented") => Verification

incrementRound()

Increment the round counter. Returns null if max rounds exceeded. T4526 Signature
(verification: Verification, maxRounds?: number) => Verification | null

logFailure()

Log a failure to the failureLog array. T4526 Signature
(verification: Verification, gateName: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented", agent: string, reason: string) => Verification

checkAllGatesPassed()

Check if all required gates have passed. T4526 Signature
(verification: Verification, requiredGates?: ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]) => boolean

isVerificationComplete()

Check if verification is complete (passed = true). T4526 Signature
(verification: Verification | null) => boolean

getVerificationStatus()

Get verification status for display. T4526 Signature
(verification: Verification | null) => VerificationStatus

shouldRequireVerification()

Check if a task type should require verification. T4526 Signature
(taskType?: string, verificationEnabled?: boolean) => boolean

getMissingGates()

Get gate names that are not yet true. T4526 Signature
(verification: Verification, requiredGates?: ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]) => ("implemented" | ... 4 more ... | "documented")[]

getGateSummary()

Get gate summary for display. T4526 Signature
(verification: Verification) => { passed: boolean; round: number; gates: VerificationGates; lastAgent: string | null; lastUpdated: string; failureCount: number; }

checkCircularValidation()

Check for circular validation (self-approval prevention). Prevents: creator validating own work, validator re-testing, tester self-creating. T4526 Signature
(currentAgent: string, createdBy?: string | null | undefined, validatedBy?: string | null | undefined, testedBy?: string | null | undefined) => CircularValidationResult

allEpicChildrenVerified()

Check if all children of an epic have verification.passed = true. T4526 Signature
(epicId: string, tasks: TaskForVerification[]) => boolean

allSiblingsVerified()

Check if all siblings of a task are verified. T4526 Signature
(parentId: string, tasks: TaskForVerification[]) => boolean

getProjectInfo()

Read project-info.json and return a typed ProjectInfo. Falls back gracefully when projectId is missing (pre-T5333 installs) by returning an empty string, allowing callers to detect and handle. Signature
(cwd?: string | undefined) => Promise<ProjectInfo>
Throws
  • Error If .cleo/project-info.json does not exist or is invalid JSON.

getProjectInfoSync()

Synchronous variant for use in hot paths where async is not feasible. Returns null if the file is missing or unparseable. Signature
(cwd?: string | undefined) => ProjectInfo | null

ProtocolEnforcer

Main protocol enforcement class Signature
typeof ProtocolEnforcer
Methods

validateProtocol()

Validate protocol compliance for a manifest entry
(protocol: ProtocolType, manifestEntry: Record<string, unknown>, additionalData?: Record<string, unknown> | undefined) => Promise<ProtocolValidationResult>

validateRule()

Validate a single rule
(rule: ProtocolRule, manifestEntry: Record<string, unknown>, additionalData?: Record<string, unknown> | undefined) => Promise<ProtocolViolation | null>

checkLifecycleGate()

Check lifecycle gate prerequisites
(_taskId: string, targetStage: string, lifecycleManifest?: Record<string, unknown> | undefined) => Promise<{ passed: boolean; missingPrerequisites: string[]; message: string; }>

recordViolation()

Record a protocol violation
(protocol: ProtocolType, violations: ProtocolViolation[], score: number, taskId?: string | undefined) => void

getViolations()

Get recent violations
(limit?: number | undefined) => ViolationLogEntry[]

calculatePenalty()

Calculate penalty for violation severity
(severity: "error" | "warning") => number

enforceProtocol()

Middleware function for domain router Intercepts operations and validates protocol compliance before execution.
(request: ProtocolRequest, next: () => Promise<ProtocolResponse>) => Promise<ProtocolResponse>

requiresProtocolValidation()

Determine if operation requires protocol validation
(request: ProtocolRequest) => boolean

detectProtocol()

Detect protocol type from request/response
(request: ProtocolRequest, _response: ProtocolResponse) => ProtocolType | null

extractManifestEntry()

Extract manifest entry from response
(response: ProtocolResponse) => Record<string, unknown> | null

setStrictMode()

Set strict mode
(strict: boolean) => void

isStrictMode()

Get strict mode status
() => boolean

getHookCapableProviders(event)

Get all providers that support a specific hook event Signature
(event: HookEvent) => string[]
Parameters
NameTypeDescription
eventHookEventThe hook event to query
Returns — Array of provider IDs that support this event

getSharedHookEvents(providerIds)

Get hook events supported by all specified providers Signature
(providerIds?: string[] | undefined) => HookEvent[]
Parameters
NameTypeDescription
providerIds: string[] | undefinedOptional array of provider IDs (uses all active providers if omitted)
Returns — Array of hook events supported by all specified providers

validateChainShape()

Validate the topology/DAG of a chain shape. Checks: - All link source/target IDs reference existing stages - entryPoint references an existing stage - All exitPoints reference existing stages - No cycles (topological sort) - All stages are reachable from the entry point T5401 Signature
(shape: ChainShape) => string[]

validateGateSatisfiability()

Validate that all gates in a chain reference valid stages and gate names. Checks: - Every gate’s stageId references an existing stage - Every stage_complete check references an existing stage - Every verification_gate check references a valid GateName T5401 Signature
(chain: WarpChain) => string[]

validateChain()

Validate a complete WarpChain definition. Orchestrates shape validation and gate satisfiability checks, returning a unified ChainValidation result. T5401 Signature
(chain: WarpChain) => ChainValidation

addChain()

Store a validated WarpChain definition. Validates the chain before storing. Throws if validation fails. T5403 Signature
(chain: WarpChain, projectRoot: string) => Promise<void>

showChain()

Retrieve a WarpChain definition by ID. T5403 Signature
(id: string, projectRoot: string) => Promise<WarpChain | null>

listChains()

List all stored WarpChain definitions. T5403 Signature
(projectRoot: string) => Promise<WarpChain[]>

findChains()

Find WarpChain definitions by criteria. T5403 Signature
(criteria: ChainFindCriteria, projectRoot: string) => Promise<WarpChain[]>

createInstance()

Create a chain instance binding a chain to an epic. T5403 Signature
(params: { chainId: string; epicId: string; variables?: Record<string, unknown> | undefined; stageToTask?: Record<string, string> | undefined; }, projectRoot: string) => Promise<...>

showInstance()

Retrieve a chain instance by ID. T5403 Signature
(id: string, projectRoot: string) => Promise<WarpChainInstance | null>

listInstanceGateResults()

Read persisted gate results for a chain instance. Signature
(id: string, projectRoot: string) => Promise<GateResult[]>

advanceInstance()

Advance a chain instance to the next stage, recording gate results. T5403 Signature
(id: string, nextStage: string, gateResults: GateResult[], projectRoot: string) => Promise<WarpChainInstance>

validateResearchProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { strict?: boolean | undefined; hasCodeChanges?: boolean | undefined; }) => ProtocolValidationResult

validateConsensusProtocol()

T4499 Signature
(entry: ManifestEntryInput, votingMatrix?: VotingMatrix) => ProtocolValidationResult

validateSpecificationProtocol()

T4499 Signature
(entry: ManifestEntryInput, specContent?: string | undefined) => ProtocolValidationResult

validateDecompositionProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { siblingCount?: number | undefined; descriptionClarity?: boolean | undefined; maxSiblings?: number | undefined; maxDepth?: number | undefined; }) => ProtocolValidationResult

validateImplementationProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { hasTaskTags?: boolean | undefined; }) => ProtocolValidationResult

validateContributionProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { hasContributionTags?: boolean | undefined; }) => ProtocolValidationResult

validateReleaseProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { version?: string | undefined; hasChangelog?: boolean | undefined; }) => ProtocolValidationResult

validateArtifactPublishProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { artifactType?: string | undefined; buildPassed?: boolean | undefined; }) => ProtocolValidationResult

validateProvenanceProtocol()

T4499 Signature
(entry: ManifestEntryInput, options?: { hasAttestation?: boolean | undefined; hasSbom?: boolean | undefined; }) => ProtocolValidationResult

validateProtocol()

Validate a manifest entry against a specific protocol. Throws CleoError with appropriate exit code on strict failure. T4499 Signature
(protocol: "research" | "consensus" | "specification" | "decomposition" | "implementation" | "release" | "contribution" | "provenance" | "artifact-publish", entry: ManifestEntryInput, options?: Record<...>, strict?: boolean) => ProtocolValidationResult

buildDefaultChain()

Build the canonical 9-stage RCASD-IVTR+C WarpChain. - Each PIPELINE_STAGE becomes a WarpStage - Each prerequisite from STAGE_PREREQUISITES becomes an entry GateContract - Each verification gate from VERIFICATION_GATE_ORDER becomes an exit GateContract - All 8 links are linear (stage[i] - stage[i+1]) T5399 Signature
() => WarpChain

buildDefaultTessera()

Build the default RCASD Tessera template. Wraps buildDefaultChain() with template variables: - epicId (required, type ‘epicId’) - projectName (optional, type ‘string’, default ‘unnamed’) - skipResearch (optional, type ‘boolean’, default false) T5409 Signature
() => TesseraTemplate

instantiateTessera()

Instantiate a Tessera template into a concrete WarpChainInstance. Steps: 1. Validate all required variables are provided 2. Apply defaults for missing optional variables 3. Construct concrete WarpChain from template 4. Validate chain via validateChain() 5. Store via createInstance() from chain-store 6. Return instance T5409 Signature
(template: TesseraTemplate, input: TesseraInstantiationInput, projectRoot: string) => Promise<WarpChainInstance>

listTesseraTemplates()

List all registered Tessera templates. T5409 Signature
() => TesseraTemplate[]

showTessera()

Find a Tessera template by ID. T5409 Signature
(id: string) => TesseraTemplate | null

migrateClaudeMem(projectRoot, options)

Migrate observations from claude-mem’s SQLite database into CLEO brain.db. Reads from ~/.claude-mem/claude-mem.db (or a custom path) and inserts into: - brain_observations (all observations, prefixed CM-) - brain_decisions (decision-typed observations, prefixed CMD-) - brain_learnings (session summaries with learned field, prefixed CML-) Idempotent: skips rows whose ID already exists in brain.db. After all inserts, rebuilds FTS5 indexes. Signature
(projectRoot: string, options?: ClaudeMemMigrationOptions) => Promise<ClaudeMemMigrationResult>
Parameters
NameTypeDescription
projectRootstringThe CLEO project root (for brain.db resolution)
options: ClaudeMemMigrationOptionsMigration options

reasonWhy()

Build a causal trace for why a task is blocked. Walks upstream through depends fields, collecting unresolved blockers and their associated brain decisions. Leaf blockers (no further unresolved deps) are reported as root causes. Signature
(taskId: string, projectRoot: string, taskAccessor?: DataAccessor | undefined) => Promise<CausalTrace>

reasonSimilar(entryId, projectRoot, limit)

Find entries similar to a given brain.db entry. 1. Loads the source entry’s text from brain.db. 2. Calls searchSimilar() for vector-based similarity if embeddings exist. 3. Falls back to FTS5 keyword search if no embeddings are available. 4. Filters out the source entry itself. Signature
(entryId: string, projectRoot: string, limit?: number | undefined) => Promise<SimilarEntry[]>
Parameters
NameTypeDescription
entryIdstringID of the brain.db entry to find similar entries for
projectRootstringProject root directory
limit: number | undefinedMaximum results to return (default 10)
Returns — Array of similar entries ranked by distance/relevance

memoryShow()

memory.show - Look up a brain.db entry by ID Signature
(entryId: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryBrainStats()

memory.stats - Aggregate stats from brain.db across all tables Signature
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryDecisionFind()

memory.decision.find - Search decisions in brain.db Signature
(params: { query?: string | undefined; taskId?: string | undefined; limit?: number | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryDecisionStore()

memory.decision.store - Store a decision to brain.db Signature
(params: { decision: string; rationale: string; alternatives?: string[] | undefined; taskId?: string | undefined; sessionId?: string | undefined; }, projectRoot?: string | undefined) => Promise<...>

memoryFind()

memory.find - Token-efficient brain search Signature
(params: { query: string; limit?: number | undefined; tables?: string[] | undefined; dateStart?: string | undefined; dateEnd?: string | undefined; }, projectRoot?: string | undefined) => Promise<...>

memoryTimeline()

memory.timeline - Chronological context around anchor Signature
(params: { anchor: string; depthBefore?: number | undefined; depthAfter?: number | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryFetch()

memory.fetch - Batch fetch brain entries by IDs Signature
(params: { ids: string[]; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryObserve()

memory.observe - Save observation to brain Signature
(params: { text: string; title?: string | undefined; type?: string | undefined; project?: string | undefined; sourceSessionId?: string | undefined; sourceType?: string | undefined; }, projectRoot?: string | undefined) => Promise<...>

memoryPatternStore()

memory.pattern.store - Store a pattern to BRAIN memory Signature
(params: StorePatternParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryPatternFind()

memory.pattern.find - Search patterns in BRAIN memory Signature
(params: SearchPatternParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryPatternStats()

memory.pattern.stats - Get pattern memory statistics Signature
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryLearningStore()

memory.learning.store - Store a learning to BRAIN memory Signature
(params: StoreLearningParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryLearningFind()

memory.learning.find - Search learnings in BRAIN memory Signature
(params: SearchLearningParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryLearningStats()

memory.learning.stats - Get learning memory statistics Signature
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryContradictions()

memory.contradictions - Find contradictory entries in brain.db Signature
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memorySuperseded()

memory.superseded - Find superseded entries in brain.db Identifies entries that have been superseded by newer entries on the same topic. For brain.db, we group by: - Decisions: type + contextTaskId/contextEpicId - Patterns: type + context (first 100 chars for similarity) - Learnings: source + applicableTypes - Observations: type + project Signature
(params?: { type?: string | undefined; project?: string | undefined; } | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
memory.link - Link a brain entry to a task Signature
(params: { taskId: string; entryId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
memory.unlink - Remove a link between a brain entry and a task Signature
(params: { taskId: string; entryId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryGraphAdd()

memory.graph.add - Add a node or edge to the PageIndex graph Signature
(params: { nodeId?: string | undefined; nodeType?: string | undefined; label?: string | undefined; metadataJson?: string | undefined; fromId?: string | undefined; toId?: string | undefined; edgeType?: string | undefined; weight?: number | undefined; }, projectRoot?: string | undefined) => Promise<...>

memoryGraphShow()

memory.graph.show - Get a node and its edges from the PageIndex graph Signature
(params: { nodeId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryGraphNeighbors()

memory.graph.neighbors - Get neighbor nodes from the PageIndex graph Signature
(params: { nodeId: string; edgeType?: string | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryReasonWhy()

memory.reason.why - Causal trace through task dependency chains Signature
(params: { taskId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memoryReasonSimilar()

memory.reason.similar - Find semantically similar entries Signature
(params: { entryId: string; limit?: number | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

memorySearchHybrid()

memory.search.hybrid - Hybrid search across FTS5, vector, and graph Signature
(params: { query: string; ftsWeight?: number | undefined; vecWeight?: number | undefined; graphWeight?: number | undefined; limit?: number | undefined; }, projectRoot?: string | undefined) => Promise<...>

memoryGraphRemove()

memory.graph.remove - Remove a node or edge from the PageIndex graph Signature
(params: { nodeId?: string | undefined; fromId?: string | undefined; toId?: string | undefined; edgeType?: string | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestShow()

pipeline.manifest.show - Get manifest entry details by ID Signature
(researchId: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestList()

pipeline.manifest.list - List manifest entries with filters Signature
(params: PipelineManifestListParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestFind()

pipeline.manifest.find - Find manifest entries by text (LIKE search on content + type) Signature
(query: string, options?: { confidence?: number | undefined; limit?: number | undefined; } | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestPending()

pipeline.manifest.pending - Get pending manifest items Signature
(epicId?: string | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestStats()

pipeline.manifest.stats - Manifest statistics Signature
(epicId?: string | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestRead()

pipeline.manifest.read - Read manifest entries with optional filter Signature
(filter?: ResearchFilter | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestAppend()

pipeline.manifest.append - Append entry to pipeline_manifest table Signature
(entry: ExtendedManifestEntry, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestArchive()

pipeline.manifest.archive - Archive old manifest entries by date Signature
(beforeDate: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestCompact()

pipeline.manifest.compact - Dedup by contentHash (keep newest by createdAt) Signature
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestValidate()

pipeline.manifest.validate - Validate manifest entries for a task Signature
(taskId: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

pipelineManifestContradictions()

pipeline.manifest.contradictions - Find entries with overlapping topics but conflicting key_findings Signature
(projectRoot?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<EngineResult<{ contradictions: ContradictionDetail[]; }>>

pipelineManifestSuperseded()

pipeline.manifest.superseded - Identify entries replaced by newer work on same topic Signature
(projectRoot?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<EngineResult<{ superseded: SupersededDetail[]; }>>
pipeline.manifest.link - Link manifest entry to a task Signature
(taskId: string, researchId: string, notes?: string | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

readManifestEntries()

Read all manifest entries from the pipeline_manifest table. Replaces readManifestEntries() from pipeline-manifest-compat. Signature
(projectRoot?: string | undefined) => Promise<ExtendedManifestEntry[]>

filterEntries()

Filter manifest entries by criteria (alias for backward compatibility). Signature
(entries: ExtendedManifestEntry[], filter: ResearchFilter) => ExtendedManifestEntry[]

distillManifestEntry()

Distill a manifest entry to brain.db observation (Phase 3, pending). Signature
(_entryId: string, _projectRoot?: string | undefined) => Promise<EngineResult<unknown>>

migrateManifestJsonlToSqlite()

Migrate existing .cleo/MANIFEST.jsonl entries into the pipeline_manifest table. Skips entries that already exist (by id). Renames MANIFEST.jsonl to MANIFEST.jsonl.migrated when done. Signature
(projectRoot?: string | undefined) => Promise<{ migrated: number; skipped: number; }>
Returns — Count of migrated and skipped entries.

resolveProviderFromModelIndex()

Signature
(index: ModelsDevIndex, model?: string | undefined) => ModelProviderLookup

resolveProviderFromModelRegistry()

Signature
(model?: string | undefined) => Promise<ModelProviderLookup>

resetModelsDevCache()

Signature
() => void

measureTokenExchange()

Signature
(input: TokenExchangeInput) => Promise<TokenMeasurement>

recordTokenExchange()

Signature
(input: TokenExchangeInput) => Promise<{ sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; domain: string | null; ... 14 more ...; responseHash: string | null; }>

showTokenUsage()

Signature
(id: string, cwd?: string | undefined) => Promise<{ sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; domain: string | null; operation: string | null; ... 13 more ...; responseHash: string | null; } | null>

listTokenUsage()

Signature
(filters?: TokenUsageFilters, cwd?: string | undefined) => Promise<{ records: { sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; ... 15 more ...; responseHash: string | null; }[]; total: number; filtered: number; }>

summarizeTokenUsage()

Signature
(filters?: TokenUsageFilters, cwd?: string | undefined) => Promise<TokenUsageSummary>

deleteTokenUsage()

Signature
(id: string, cwd?: string | undefined) => Promise<{ deleted: boolean; id: string; }>

clearTokenUsage()

Signature
(filters?: TokenUsageFilters, cwd?: string | undefined) => Promise<{ deleted: number; }>

autoRecordDispatchTokenUsage()

Signature
(input: TokenExchangeInput) => Promise<void>

getLatestTokenRecord()

Signature
(cwd?: string | undefined) => Promise<{ sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; domain: string | null; operation: string | null; ... 13 more ...; responseHash: string | null; } | null>

getTokenUsageAggregateSql()

Signature
(cwd?: string | undefined) => Promise<{ provider: string; transport: string; totalTokens: number; count: number; }[]>

startParallelExecution()

Start parallel execution for a wave. Signature
(epicId: string, wave: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; wave: number; tasks: string[]; taskCount: number; startedAt: string; }>

endParallelExecution()

End parallel execution for a wave. Signature
(epicId: string, wave: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; wave: number; tasks: string[]; taskCount: number; startedAt: string | null; endedAt: string; durationMs: number; alreadyEnded?: boolean | undefined; }>

getParallelStatus()

Get current parallel execution state. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ParallelState>

listSkills()

List available skills. Signature
(_projectRoot: string) => { skills: SkillEntry[]; total: number; }

getSkillContent()

Read skill content for injection into agent context. Signature
(skillName: string, _projectRoot: string) => SkillContent

getUnblockOpportunities()

Analyze dependency graph for unblocking opportunities. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<UnblockResult>

validateSpawnReadiness()

Validate spawn readiness for a task. Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<SpawnValidationResult>

injectContext()

Read protocol injection content for a given protocol type. Core logic for session.context.inject. Signature
(protocolType: string, params?: { taskId?: string | undefined; variant?: string | undefined; } | undefined, projectRoot?: string | undefined) => ContextInjectionData

generateSessionId()

Generate a canonical session ID. Format: ses_YYYYMMDDHHmmss_6hex Example: ses_20260227171900_a1b2c3 Signature
() => string

isValidSessionId()

Check if a string is a valid session ID (any format). Signature
(id: string) => boolean

isCanonicalSessionId()

Check if a session ID uses the canonical format. Signature
(id: string) => boolean

extractSessionTimestamp()

Extract an approximate timestamp from any valid session ID format. Returns null if the ID format is not recognized. Signature
(id: string) => Date | null

createSession()

Create a new session. Signature
(session: Session, cwd?: string | undefined) => Promise<Session>

getSession()

Get a session by ID. Signature
(sessionId: string, cwd?: string | undefined) => Promise<Session | null>

updateSession()

Update a session. Signature
(sessionId: string, updates: Partial<Session>, cwd?: string | undefined) => Promise<Session | null>

listSessions()

List sessions with optional filters. Signature
(filters?: { active?: boolean | undefined; limit?: number | undefined; } | undefined, cwd?: string | undefined) => Promise<Session[]>

endSession()

End a session. Signature
(sessionId: string, note?: string | undefined, cwd?: string | undefined) => Promise<Session | null>

startTask()

Start working on a task within a session. Signature
(sessionId: string, taskId: string, cwd?: string | undefined) => Promise<void>

getCurrentTask()

Get current task for a session. Signature
(sessionId: string, cwd?: string | undefined) => Promise<{ taskId: string | null; since: string | null; }>

stopTask()

Stop working on the current task for a session. Signature
(sessionId: string, cwd?: string | undefined) => Promise<void>

workHistory()

Get work history for a session. Signature
(sessionId: string, limit?: number, cwd?: string | undefined) => Promise<{ taskId: string; setAt: string; clearedAt: string | null; }[]>

gcSessions()

Garbage collect old sessions (mark ended sessions as orphaned after threshold). Signature
(maxAgeDays?: number, cwd?: string | undefined) => Promise<number>

getActiveSession()

Get the currently active session (if any). Signature
(cwd?: string | undefined) => Promise<Session | null>

computeDependencyWaves()

Compute dependency waves for parallel execution. Tasks in the same wave can run in parallel; waves must be sequential. Signature
(tasks: Task[]) => DependencyWave[]

getNextTask()

Get the next task to work on (highest priority ready task). Signature
(tasks: Task[]) => Task | null

getCriticalPath()

Calculate the critical path (longest dependency chain). Returns task IDs along the critical path. Signature
(tasks: Task[]) => string[]

getTaskOrder()

Get task ordering by dependency + priority. Signature
(tasks: Task[]) => string[]

getParallelTasks()

Get parallelizable tasks (tasks with no unmet dependencies). Signature
(tasks: Task[]) => string[]

suggestRelated()

Suggest related tasks based on shared attributes. Signature
(taskId: string, opts: { threshold?: number | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

addRelation()

Add a relation between tasks. Signature
(from: string, to: string, type: string, reason: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

discoverRelated()

Discover related tasks using various methods. Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

listRelations()

List existing relations for a task. Signature
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

canCancel()

Check if a task can be cancelled. Signature
(task: Task) => { allowed: boolean; reason?: string | undefined; }

cancelTask()

Cancel a task in the tasks array (returns updated array). Does NOT handle children - use deletion-strategy for that. Signature
(taskId: string, tasks: Task[], reason?: string | undefined) => { tasks: Task[]; result: CancelResult; }

cancelMultiple()

Batch cancel multiple tasks. Signature
(taskIds: string[], tasks: Task[], reason?: string | undefined) => { tasks: Task[]; results: CancelResult[]; }

coreTaskNext()

Suggest next task to work on based on priority, phase, age, and deps. T4790 Signature
(projectRoot: string, params?: { count?: number | undefined; explain?: boolean | undefined; } | undefined) => Promise<{ suggestions: { id: string; title: string; priority: string; phase: string | null; score: number; reasons?: string[] | undefined; }[]; totalCandidates: number; }>

coreTaskBlockers()

Show blocked tasks and analyze blocking chains. T4790 Signature
(projectRoot: string, params?: { analyze?: boolean | undefined; limit?: number | undefined; } | undefined) => Promise<{ blockedTasks: { id: string; title: string; status: string; depends?: string[] | undefined; blockingChain: string[]; }[]; criticalBlockers: BottleneckTask[]; summary: string; total: number; limit: n...

coreTaskTree()

Build hierarchy tree. T4790 Signature
(projectRoot: string, taskId?: string | undefined) => Promise<{ tree: FlatTreeNode[]; totalNodes: number; }>

coreTaskDeps()

Show dependencies for a task. T4790 Signature
(projectRoot: string, taskId: string) => Promise<TaskDepsResult>

coreTaskRelates()

Show task relations. T4790 Signature
(projectRoot: string, taskId: string) => Promise<{ taskId: string; relations: { taskId: string; type: string; reason?: string | undefined; }[]; count: number; }>

coreTaskRelatesAdd()

Add a relation between two tasks. T4790 Signature
(projectRoot: string, taskId: string, relatedId: string, type: string, reason?: string | undefined) => Promise<{ from: string; to: string; type: string; reason?: string | undefined; added: boolean; }>

coreTaskAnalyze()

Analyze tasks for priority and leverage. T4790 Signature
(projectRoot: string, taskId?: string | undefined, params?: { tierLimit?: number | undefined; } | undefined) => Promise<TaskAnalysisResult & { tierLimit: number; }>

coreTaskRestore()

Restore a cancelled task back to pending. T4790 Signature
(projectRoot: string, taskId: string, params?: { cascade?: boolean | undefined; notes?: string | undefined; } | undefined) => Promise<{ task: string; restored: string[]; count: number; }>

coreTaskCancel()

Cancel a task (sets status to ‘cancelled’, a soft terminal state). Use restore to reverse. Use delete for permanent removal. T4529 Signature
(projectRoot: string, taskId: string, params?: { reason?: string | undefined; } | undefined) => Promise<{ task: string; cancelled: boolean; reason?: string | undefined; cancelledAt: string; }>

coreTaskUnarchive()

Move an archived task back to active tasks. T4790 Signature
(projectRoot: string, taskId: string, params?: { status?: string | undefined; preserveStatus?: boolean | undefined; } | undefined) => Promise<{ task: string; unarchived: boolean; title: string; status: string; }>

coreTaskReorder()

Change task position within its sibling group. T4790 Signature
(projectRoot: string, taskId: string, position: number) => Promise<{ task: string; reordered: boolean; newPosition: number; totalSiblings: number; }>

coreTaskReparent()

Move task under a different parent. T4790 Signature
(projectRoot: string, taskId: string, newParentId: string | null) => Promise<{ task: string; reparented: boolean; oldParent: string | null; newParent: string | null; newType?: string | undefined; }>

coreTaskPromote()

Promote a subtask to task or task to root. T4790 Signature
(projectRoot: string, taskId: string) => Promise<{ task: string; promoted: boolean; previousParent: string | null; typeChanged: boolean; }>

coreTaskReopen()

Reopen a completed task. T4790 Signature
(projectRoot: string, taskId: string, params?: { status?: string | undefined; reason?: string | undefined; } | undefined) => Promise<{ task: string; reopened: boolean; previousStatus: string; newStatus: string; }>

coreTaskComplexityEstimate()

Deterministic complexity scoring from task metadata. T4790 Signature
(projectRoot: string, params: { taskId: string; }) => Promise<{ size: "medium" | "small" | "large"; score: number; factors: ComplexityFactor[]; dependencyDepth: number; subtaskCount: number; fileCount: number; }>

coreTaskDepsOverview()

Overview of all dependencies across the project. T5157 Signature
(projectRoot: string) => Promise<{ totalTasks: number; tasksWithDeps: number; blockedTasks: (TaskRef & { unblockedBy: string[]; })[]; readyTasks: TaskRef[]; validation: { valid: boolean; errorCount: number; warningCount: number; }; }>

coreTaskDepsCycles()

Detect circular dependencies across the project. T5157 Signature
(projectRoot: string) => Promise<{ hasCycles: boolean; cycles: { path: string[]; tasks: Pick<TaskRef, "id" | "title">[]; }[]; }>

coreTaskDepends()

List dependencies for a task in a given direction. T4790 Signature
(projectRoot: string, taskId: string, direction?: "upstream" | "downstream" | "both", options?: { tree?: boolean | undefined; } | undefined) => Promise<{ taskId: string; direction: string; ... 6 more ...; upstreamTree?: FlatTreeNode[] | undefined; }>

coreTaskStats()

Compute task statistics. T4790 Signature
(projectRoot: string, epicId?: string | undefined) => Promise<{ total: number; pending: number; active: number; blocked: number; done: number; cancelled: number; byPriority: Record<string, number>; byType: Record<...>; }>

coreTaskExport()

Export tasks as JSON or CSV. T4790 Signature
(projectRoot: string, params?: { format?: "json" | "csv" | undefined; status?: string | undefined; parent?: string | undefined; } | undefined) => Promise<unknown>

coreTaskHistory()

Get task history from the log file. T4790 Signature
(projectRoot: string, taskId: string, limit?: number | undefined) => Promise<Record<string, unknown>[]>

coreTaskLint()

Lint tasks for common issues. T4790 Signature
(projectRoot: string, taskId?: string | undefined) => Promise<{ taskId: string; severity: "error" | "warning"; rule: string; message: string; }[]>

coreTaskBatchValidate()

Validate multiple tasks at once. T4790 Signature
(projectRoot: string, taskIds: string[], checkMode?: "full" | "quick") => Promise<{ results: Record<string, { severity: "error" | "warning"; rule: string; message: string; }[]>; summary: { ...; }; }>

coreTaskImport()

Import tasks from a JSON source string. T4790 Signature
(projectRoot: string, source: string, overwrite?: boolean | undefined) => Promise<{ imported: number; skipped: number; errors: string[]; remapTable?: Record<string, string> | undefined; }>

analyzeTaskPriority()

Analyze task priority with leverage scoring. Signature
(opts: { autoStart?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<AnalysisResult>

listLabels()

List all labels with task counts. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<LabelInfo[]>

showLabelTasks()

Show tasks with a specific label. Signature
(label: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

getLabelStats()

Get detailed label statistics. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>

createStoreProvider()

Create a store provider. Always creates SQLite provider (ADR-006). T4647 Signature
(_engine?: "sqlite" | undefined, cwd?: string | undefined) => Promise<StoreProvider>

getStore()

Get a StoreProvider instance for the given working directory. Convenience wrapper around createStoreProvider with auto-detection. T4645 T4638 Signature
(cwd?: string | undefined) => Promise<StoreProvider>

countJsonRecords()

Count records in JSON source files. Signature
(cleoDir: string) => { tasks: number; archived: number; sessions: number; }

migrateJsonToSqliteAtomic(cwd, tempDbPath, logger)

Migrate JSON data to SQLite with atomic rename pattern. Writes to a temporary database file first, then atomically renames. Signature
(cwd?: string | undefined, tempDbPath?: string | undefined, logger?: MigrationLogger | undefined) => Promise<MigrationResult>
Parameters
NameTypeDescription
cwd: string | undefinedOptional working directory
tempDbPath: string | undefinedOptional temporary database path for atomic migration
logger: MigrationLogger | undefinedOptional migration logger for audit trail (task T4727)
Returns — Migration result

migrateJsonToSqlite()

Signature
(cwd?: string | undefined, options?: MigrationOptions | undefined) => Promise<MigrationResult>

exportToJson()

Export SQLite data back to JSON format (for inspection or emergency recovery). Signature
(cwd?: string | undefined) => Promise<{ tasks: Task[]; archived: Task[]; sessions: Session[]; }>

repairMissingSizes()

Set size=‘medium’ on tasks that have no size value. Operates directly on the SQLite tasks table. Signature
(cwd: string | undefined, dryRun: boolean) => Promise<RepairAction>

repairMissingCompletedAt()

Set completedAt=now() on done/cancelled tasks that are missing a completedAt timestamp. Operates directly on the SQLite tasks table. Signature
(cwd: string | undefined, dryRun: boolean) => Promise<RepairAction>

runAllRepairs()

Run all repair functions. Returns all actions taken (or previewed in dry-run mode). Signature
(cwd: string | undefined, dryRun: boolean) => Promise<RepairAction[]>

runUpgrade(, , , )

Run a full upgrade pass on the project .cleo/ directory. Steps: 1. Pre-flight storage check (JSON → SQLite) 2. If migration needed and not dry-run, run auto-migration with backup 3. Schema version checks on JSON files 4. Structural repairs (checksums, missing fields) Signature
(options?: { dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; }) => Promise<UpgradeResult>
Parameters
NameTypeDescription
: \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \}options.dryRun Preview changes without applying
: \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \}options.includeGlobal Also check global ~/.cleo
: \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \}options.autoMigrate Auto-migrate storage if needed (default: true)
: \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \}options.cwd Project directory override

VerificationGate

Main Verification Gate class Orchestrates 4-layer validation and determines pass/fail status. Each layer must pass before proceeding to the next. Signature
typeof VerificationGate
Methods

verifyOperation()

Execute all 4 gate layers sequentially Stops at first failure unless in advisory mode.
(context: OperationContext) => Promise<VerificationResult>

runLayer()

Run a single validation layer with timing
(layer: GateLayer, validator: () => Promise<LayerResult>) => Promise<LayerResult>

buildSuccessResult()

Build success result when all gates pass
(layers: Record<GateLayer, LayerResult>) => VerificationResult

buildFailureResult()

Build failure result when a gate fails
(layers: Record<GateLayer, LayerResult>, blockedAt: GateLayer) => VerificationResult

determineSemanticExitCode()

Determine semantic layer exit code from violations
(violations: GateViolation[]) => ProtocolExitCode

determineReferentialExitCode()

Determine referential layer exit code from violations
(violations: GateViolation[]) => ProtocolExitCode

determineProtocolExitCode()

Determine protocol layer exit code from violations
(violations: GateViolation[]) => ProtocolExitCode

requiresValidation()

Check if an operation requires gate validation All mutate operations require validation. Query operations skip validation for performance.
(context: OperationContext) => boolean

getLayerName()

Get human-readable layer name
(layer: GateLayer) => string

createVerificationGate()

Factory function for creating verification gates Signature
(strictMode?: boolean) => VerificationGate

WorkflowGateTracker

WorkflowGateTracker Tracks the status of all 6 workflow verification gates for a task. Implements Section 7.4 failure cascade behavior: when a gate fails, all downstream gates reset to null. T3141 Signature
typeof WorkflowGateTracker
Methods

getGateStatus()

Get the status of a specific gate
(gateName: WorkflowGateName) => WorkflowGateStatus

getGateState()

Get the full state of a specific gate
(gateName: WorkflowGateName) => WorkflowGateState | undefined

getAllGates()

Get all gate states
() => WorkflowGateState[]

canAttempt()

Check if a gate can be attempted (all dependencies passed)
(gateName: WorkflowGateName) => boolean

passGate()

Mark a gate as passed.
(gateName: WorkflowGateName, agent?: string | undefined) => boolean

failGate()

Mark a gate as failed. Per Section 7.4: When a gate fails, all downstream gates reset to null.
(gateName: WorkflowGateName, reason?: string | undefined) => boolean

cascadeReset()

Reset a gate and all downstream gates to null.
(failedGateName: WorkflowGateName) => void

updateBlockedStatus()

Update blocked status for all gates based on current state.
() => void

allPassed()

Check if all gates have passed
() => boolean

getPendingGates()

Get all gates that are currently blocked or have null status
() => WorkflowGateState[]

getNextAttemptable()

Get the next gate that can be attempted
() => WorkflowGateName | null

getDownstreamGates()

Get downstream gates of a given gate (not including the gate itself)
(gateName: WorkflowGateName) => WorkflowGateName[]

toRecord()

Serialize gate states to a plain record
() => Record<string, WorkflowGateStatus>

fromRecord()

Restore gate states from a record
(record: Record<string, WorkflowGateStatus>) => void

isValidGate()

Check if a gate name is valid
(gateName: WorkflowGateName) => boolean

isValidWorkflowGateName()

Validate a workflow gate name string Signature
(name: string) => name is WorkflowGateName

getWorkflowGateDefinition()

Get the definition for a workflow gate Signature
(name: WorkflowGateName) => WorkflowGateDefinition | undefined

validateLayer1Schema()

Layer 1: Schema Validation Validates operation parameters against JSON Schema definitions. Checks required fields, data types, and format constraints. Signature
(context: OperationContext) => Promise<LayerResult>

validateLayer2Semantic()

Layer 2: Semantic Validation Validates business rules and logical constraints. Signature
(context: OperationContext) => Promise<LayerResult>

validateLayer3Referential()

Layer 3: Referential Validation Validates cross-entity references and relationships. Signature
(context: OperationContext) => Promise<LayerResult>

validateLayer4Protocol()

Layer 4: Protocol Validation Validates RCASD-IVTR+C lifecycle compliance and protocol requirements. Signature
(context: OperationContext, _enforcer: ProtocolEnforcer) => Promise<LayerResult>

isFieldRequired()

Helper to check if a field is required for an operation Signature
(domain: string, operation: string, field: string) => boolean

validateWorkflowGateName()

Validate a workflow gate name T3141 Signature
(name: string) => boolean

validateWorkflowGateStatus()

Validate a workflow gate status value per Section 7.3 T3141 Signature
(status: unknown) => status is "failed" | "blocked" | "passed" | null

validateWorkflowGateUpdate()

Validate a gate update operation. T3141 Signature
(gateName: string, status: string, agent?: string | undefined, tracker?: WorkflowGateTracker | undefined) => GateViolation[]

buildMcpInputSchema()

Build a JSON Schema input_schema object from an OperationDef. Algorithm: 1. Iterate def.params 2. Skip params where mcp.hidden === true 3. Map ParamType → JSON Schema type 4. Collect names where required === true into required[] 5. Return type: ‘object’, properties, required Signature
(def: OperationDef) => JSONSchemaObject

buildCommanderArgs()

Split OperationDef.params into positional arguments and option flags, suitable for Commander.js registration. - cli.positional === true → goes into positionals[] - everything else with a cli key → goes into options[] - Params with no cli key → MCP-only; excluded from both arrays Signature
(def: OperationDef) => CommanderArgSplit

buildCommanderOptionString()

Build the Commander option string for a single non-positional ParamDef. Examples: name:‘taskId’, type:‘string’, cli: → ‘—taskId ’ name:‘status’, type:‘string’, cli:short:’-s’, flag:‘status’ → ‘-s, —status ’ name:‘dryRun’, type:‘boolean’, cli:flag:‘dry-run’ → ‘—dry-run’ name:‘limit’, type:‘number’, cli: → ‘—limit ’ Signature
(param: ParamDef) => string

camelToKebab()

Convert a camelCase string to kebab-case. e.g. ‘includeArchive’ → ‘include-archive’ Signature
(s: string) => string

validateRequiredParamsDef()

Validates that all required parameters are present in the request. Returns an array of missing parameter names. Replaces the old requiredParams: string[] check in registry.ts. Signature
(def: OperationDef, params?: Record<string, unknown> | undefined) => string[]

validateConsensusTask()

Validate consensus protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; votingMatrixFile?: string | undefined; }) => Promise<ValidationResult>

checkConsensusManifest()

Validate consensus protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; votingMatrixFile?: string | undefined; }) => Promise<ValidationResult>

validateContributionTask()

Validate contribution protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

checkContributionManifest()

Validate contribution protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

validateDecompositionTask()

Validate decomposition protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; epicId?: string | undefined; }) => Promise<ValidationResult>

checkDecompositionManifest()

Validate decomposition protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; epicId?: string | undefined; }) => Promise<ValidationResult>

validateImplementationTask()

Validate implementation protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

checkImplementationManifest()

Validate implementation protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

validateSpecificationTask()

Validate specification protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; specFile?: string | undefined; }) => Promise<ValidationResult>

checkSpecificationManifest()

Validate specification protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; specFile?: string | undefined; }) => Promise<ValidationResult>

validateSchema(schemaType, data)

Validate data against a CLEO schema Signature
(schemaType: "config", data: unknown) => ValidationResult
Parameters
NameTypeDescription
schemaType"config"Which schema to validate against
dataunknownThe data to validate
Returns — Validation result with errors if invalid

validateTask(task)

Validate a single task object against the drizzle-zod insert schema. Uses drizzle-derived Zod schemas as the single source of truth for field-level constraints (pattern, length, enum). Signature
(task: unknown) => ValidationResult
Parameters
NameTypeDescription
taskunknownTask object to validate
Returns — Validation result

clearSchemaCache()

Clear the schema cache (useful for testing) Signature
() => void

validateTitleDescription()

Validate that title and description are both present and different. This is a critical anti-hallucination check. Signature
(title?: string | undefined, description?: string | undefined) => RuleViolation[]

validateTimestamps()

Validate that timestamps are not in the future Signature
(task: TaskLike) => RuleViolation[]

validateIdUniqueness()

Validate ID uniqueness across all tasks (todo + archive) Signature
(taskId: string, existingIds: Set<string>) => RuleViolation[]

validateNoDuplicateDescription()

Validate no duplicate task descriptions Signature
(description: string, existingDescriptions: string[], _excludeTaskId?: string | undefined) => RuleViolation[]

validateHierarchy()

Validate hierarchy constraints. Accepts optional limits to override defaults (from config). Signature
(parentId: string | null | undefined, tasks: { id: string; parentId?: string | null | undefined; type?: string | undefined; }[], _taskType?: string | undefined, limits?: { maxDepth?: number | undefined; maxSiblings?: number | undefined; } | undefined) => RuleViolation[]

validateStatusTransition()

Validate status transition Signature
(currentStatus: string, newStatus: string) => RuleViolation[]

validateNewTask()

Run all validation rules on a task being created Signature
(task: TaskLike, existingIds: Set<string>, existingDescriptions: string[], existingTasks: { id: string; parentId?: string | null | undefined; type?: string | undefined; }[], limits?: { ...; } | undefined) => RuleViolation[]

hasErrors()

Check if violations contain any errors (not just warnings) Signature
(violations: RuleViolation[]) => boolean

coreValidateReport()

Run comprehensive validation report on tasks database — checks business rules, dependencies, checksums, data integrity, and schema compliance. T4795 Signature
(projectRoot: string) => Promise<ValidateReportResult>

coreValidateAndFix()

Run validation report, then apply data repairs for fixable issues. Calls runAllRepairs() from src/core/repair.ts (same repairs used by upgrade). T4795 Signature
(projectRoot: string, dryRun?: boolean) => Promise<ValidateAndFixResult>

coreValidateSchema()

Validate data against a schema type. For SQLite-backed types (todo, archive, sessions, log), queries rows directly from SQLite and validates with drizzle-zod schemas. For config type, uses AJV against the JSON schema file. If raw data is provided, validates directly with AJV (backward compat). T4786 Signature
(type: string, data: unknown, projectRoot: string) => Promise<{ type: string; valid: boolean; errors: unknown[]; errorCount: number; }>

coreValidateTask()

Validate a single task against anti-hallucination rules. T4786 Signature
(taskId: string, projectRoot: string) => Promise<{ taskId: string; valid: boolean; violations: RuleViolation[]; errorCount: number; warningCount: number; }>

coreValidateProtocol()

Check basic protocol compliance for a task. T4786 Signature
(taskId: string, protocolType: string | undefined, projectRoot: string) => Promise<{ taskId: string; protocolType: string; compliant: boolean; violations: { code: string; message: string; severity: string; }[]; }>

coreValidateManifest()

Validate manifest JSONL entries for required fields. T4786 Signature
(projectRoot: string) => { valid: boolean; totalEntries: number; validEntries: number; invalidEntries: number; errors: { line: number; entryId: string; errors: string[]; }[]; message?: string | undefined; }

coreValidateOutput()

Validate an output file for required sections. T4786 Signature
(filePath: string, taskId: string | undefined, projectRoot: string) => { filePath: string; valid: boolean; issues: { code: string; message: string; severity: string; }[]; fileSize: number; lineCount: number; }

coreComplianceSummary()

Get aggregated compliance metrics. T4786 Signature
(projectRoot: string) => { total: number; pass: number; fail: number; partial: number; passRate: number; byProtocol: Record<string, { pass: number; fail: number; partial: number; }>; }

coreComplianceViolations()

List compliance violations. T4786 Signature
(limit: number | undefined, projectRoot: string) => { violations: { timestamp: string; taskId: string; protocol: string; result: string; violations?: { code: string; message: string; severity: "error" | "warning"; }[] | undefined; }[]; total: number; }

coreComplianceRecord()

Record a compliance check result to COMPLIANCE.jsonl. T4786 Signature
(taskId: string, result: string, protocol: string | undefined, violations: { code: string; message: string; severity: "error" | "warning"; }[] | undefined, projectRoot: string) => { ...; }

coreTestStatus()

Check test suite availability. T4786 Signature
(projectRoot: string) => { batsTests: { available: boolean; directory: string | null; }; mcpTests: { available: boolean; directory: string | null; }; message: string; }

coreCoherenceCheck()

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

coreTestRun()

Execute test suite via subprocess. T4786 Signature
(params: { scope?: string | undefined; pattern?: string | undefined; parallel?: boolean | undefined; } | undefined, projectRoot: string) => { ran: boolean; runner?: string | undefined; ... 5 more ...; message?: string | undefined; }

coreBatchValidate()

Batch validate all tasks against schema and rules. T4786 Signature
(projectRoot: string) => Promise<{ totalTasks: number; validTasks: number; invalidTasks: number; totalErrors: number; totalWarnings: number; results: { taskId: string; valid: boolean; errorCount: number; warningCount: number; violations: RuleViolation[]; }[]; }>

coreTestCoverage()

Get test coverage metrics. T4786 Signature
(projectRoot: string) => { [key: string]: unknown; available: boolean; message?: string | undefined; }

buildBrainState()

Build brain state for agent bootstrapping. Signature
(projectRoot: string, opts?: { speed?: "full" | "fast" | "complete" | undefined; } | undefined, accessor?: DataAccessor | undefined) => Promise<BrainState>

getCriticalPath()

Find the critical path (longest dependency chain) in the task graph. Signature
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CriticalPathResult>

resolveSkillPathsForProvider(providerId, scope, projectRoot)

Get effective skill paths for a provider considering precedence Signature
(providerId: string, scope: "global" | "project", projectRoot?: string | undefined) => Promise<ResolvedSkillPath[]>
Parameters
NameTypeDescription
providerIdstringThe ID of the provider
scope"global" | "project"The scope (‘global’ or ‘project’)
projectRoot: string | undefinedOptional project root path for project-scoped resolution
Returns — Array of resolved skill paths with precedence information Throws
  • Error if provider not found

getProvidersWithPrecedence(precedence)

Get all providers that use a specific precedence mode Signature
(precedence: SkillsPrecedence) => string[]
Parameters
NameTypeDescription
precedenceSkillsPrecedenceThe precedence mode to filter by
Returns — Array of provider IDs using the specified precedence

getSkillsMapWithPrecedence()

Build complete skills map with precedence information Signature
() => { providerId: string; toolName: string; precedence: SkillsPrecedence; paths: { global: string | null; project: string | null; }; }[]
Returns — Array of provider skill configurations with precedence data

determineInstallationTargets(context)

Determine target installation paths for a skill Signature
(context: SkillInstallationContext) => Promise<{ providerId: string; path: string; }[]>
Parameters
NameTypeDescription
contextSkillInstallationContextThe installation context including target providers and project root
Returns — Array of installation targets with provider ID and path

supportsAgentsPath(providerId)

Check if provider supports agents path Signature
(providerId: string) => Promise<boolean>
Parameters
NameTypeDescription
providerIdstringThe ID of the provider to check
Returns — True if provider has agents path configuration

coreTaskPlan()

Build composite planning view. T4914 Signature
(projectRoot: string) => Promise<PlanResult>

buildIndex(cwd)

Scan .cleo/rcasd/ and legacy .cleo/rcsd/ directories and build the RCASD index. Reads all _manifest.json files and any spec/report markdown files to produce a complete index. Signature
(cwd?: string | undefined) => RcasdIndex
Parameters
NameTypeDescription
cwd: string | undefinedWorking directory
Returns — Populated RcasdIndex T4801

writeIndex(index, cwd)

Write RCASD-INDEX.json to disk. Signature
(index: RcasdIndex, cwd?: string | undefined) => void
Parameters
NameTypeDescription
indexRcasdIndexThe index to write
cwd: string | undefinedWorking directory T4801

readIndex(cwd)

Read RCASD-INDEX.json from disk. Signature
(cwd?: string | undefined) => RcasdIndex | null
Parameters
NameTypeDescription
cwd: string | undefinedWorking directory
Returns — The index or null if not found T4801

rebuildIndex(cwd)

Rebuild and write the index from current disk state. Signature
(cwd?: string | undefined) => RcasdIndex
Parameters
NameTypeDescription
cwd: string | undefinedWorking directory
Returns — The rebuilt index T4801

getTaskAnchor(taskId, cwd)

Get task anchor by task ID. Signature
(taskId: string, cwd?: string | undefined) => TaskAnchor | null
Parameters
NameTypeDescription
taskIdstringThe task ID to look up
cwd: string | undefinedWorking directory
Returns — TaskAnchor or null T4801

findByStage(stage, cwd)

Find tasks by pipeline stage. Signature
(stage: string, cwd?: string | undefined) => [string, TaskAnchor][]
Parameters
NameTypeDescription
stagestringThe pipeline stage to filter by
cwd: string | undefinedWorking directory
Returns — Array of [taskId, anchor] pairs T4801

findByStatus(status, cwd)

Find tasks by status. Signature
(status: "completed" | "failed" | "active" | "archived" | "paused", cwd?: string | undefined) => [string, TaskAnchor][]
Parameters
NameTypeDescription
status"completed" | "failed" | "active" | "archived" | "paused"The status to filter by
cwd: string | undefinedWorking directory
Returns — Array of [taskId, anchor] pairs T4801

getIndexTotals(cwd)

Get index summary statistics. Signature
(cwd?: string | undefined) => IndexTotals | null
Parameters
NameTypeDescription
cwd: string | undefinedWorking directory
Returns — Index totals or null T4801

generateCodebaseMapSummary()

Signature
(result: CodebaseMapResult) => string

sequenceChains()

Sequence two chains: connect A’s exit points to B’s entry point. B’s stage IDs are prefixed with “b” to avoid collision with A. The result is validated and throws if invalid. T5406 Signature
(a: WarpChain, b: WarpChain) => WarpChain

parallelChains()

Compose chains in parallel with a common fork entry and join stage. Creates a fork entry stage that links to each chain’s entry, and all chain exits link to the provided joinStage. Each chain’s IDs are prefixed with “pindex” to avoid collisions. T5406 Signature
(chains: WarpChain[], joinStage: WarpStage) => WarpChain

resolveEpicFromContent()

Extract an epic/task ID from file content by searching for: 1. @task T#### or @epic T#### annotations (highest priority) 2. JSON "task", "epicId", or "taskId" fields 3. First T#### at a word boundary (fallback) Signature
(content: string) => string | null

resolveEpicFromFilename()

Extract an epic ID from a filename pattern like T####-* or T####_*. Signature
(filename: string) => string | null

normalizeDirectoryNames()

Rename suffixed epic directories (e.g. T4881_install-channelsT4881). Signature
(options?: ConsolidateOptions) => MoveRecord[]

migrateConsensusFiles()

Migrate .cleo/consensus/ files to appropriate epic’s consensus/ subdirectory. - T4869-checkpoint-consensus.json → rcasd/T4869/consensus/ - Agent finding files and CONSENSUS-REPORT.md → resolve epic from content - phase1-best-practices-evidence.md → resolve epic from content → research/ Signature
(options?: ConsolidateOptions) => MoveRecord[]

migrateContributionFiles()

Migrate .cleo/contributions/ files to appropriate epic’s contributions/ subdirectory. Files follow the pattern T####-session-*.json with epicId in content. Signature
(options?: ConsolidateOptions) => MoveRecord[]

migrateLooseFiles()

Migrate loose T####_*.md files from .cleo/rcasd/ root into rcasd/\{epicId\}/research/ subdirectories. Signature
(options?: ConsolidateOptions) => MoveRecord[]

consolidateRcasd(, )

Consolidate all provenance files into the unified .cleo/rcasd/\{epicId\}/ structure with stage subdirectories. Performs migrations in order: 1. Rename suffixed directories (T4881_install-channels → T4881) 2. Move consensus files to appropriate epic’s consensus/ subdirectory 3. Move contribution files to appropriate epic’s contributions/ subdirectory 4. Move loose research files to appropriate epic’s research/ subdirectory Signature
(options?: ConsolidateOptions) => MigrationResult
Parameters
NameTypeDescription
: ConsolidateOptionsoptions.dryRun - If true, log planned moves without executing them
: ConsolidateOptionsoptions.cwd - Optional working directory override

initializePipeline(taskId, options)

Initialize a new pipeline for a task. Creates a new pipeline record in the database with all 9 stages initialized to ‘not_started’ status. The pipeline starts at the research stage by default. Signature
(taskId: string, options?: InitializePipelineOptions) => Promise<Pipeline>
Parameters
NameTypeDescription
taskIdstringThe task ID (e.g., ‘T4800’)
options: InitializePipelineOptionsOptional configuration
Returns — Promise resolving to the created Pipeline Throws
  • CleoError If pipeline already exists or database operation fails
Example
const pipeline = await initializePipeline('T4800', {
  startStage: 'research',
  assignedAgent: 'agent-001'
});
console.log(`Pipeline initialized: ${pipeline.id}`);

getPipeline(taskId)

Retrieve a pipeline by task ID. Returns the complete pipeline state including current stage and status. Returns null if no pipeline exists for the given task ID. Signature
(taskId: string) => Promise<Pipeline | null>
Parameters
NameTypeDescription
taskIdstringThe task ID (e.g., ‘T4800’)
Returns — Promise resolving to Pipeline or null Throws
  • CleoError If database query fails
Example
const pipeline = await getPipeline('T4800');
if (pipeline) {
  console.log(`Current stage: ${pipeline.currentStage}`);
}

advanceStage(taskId, options)

Advance a pipeline to the next stage. Performs atomic stage transition with prerequisite checking and audit logging. Validates the transition is allowed, updates stage statuses, and records the transition in the audit trail. Signature
(taskId: string, options: AdvanceStageOptions) => Promise<void>
Parameters
NameTypeDescription
taskIdstringThe task ID
optionsAdvanceStageOptionsAdvance options including target stage and reason
Returns — Promise resolving when transition is complete Throws
  • CleoError If transition is invalid or prerequisites not met
Example
await advanceStage('T4800', {
  toStage: 'consensus',
  reason: 'Research completed, moving to consensus',
  initiatedBy: 'agent-001'
});

getCurrentStage(taskId)

Get the current stage of a pipeline. Convenience method to quickly check which stage a task is currently in. Signature
(taskId: string) => Promise<"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release">
Parameters
NameTypeDescription
taskIdstringThe task ID
Returns — Promise resolving to the current Stage Throws
  • CleoError If database query fails
Example
const currentStage = await getCurrentStage('T4800');
if (currentStage === 'validation') {
  console.log('Task is in verification');
}

listPipelines(options)

List pipelines with optional filtering. Signature
(options?: PipelineQueryOptions) => Promise<Pipeline[]>
Parameters
NameTypeDescription
options: PipelineQueryOptionsQuery options for filtering and pagination
Returns — Promise resolving to array of Pipelines Throws
  • CleoError If database query fails
Example
const activePipelines = await listPipelines({
  status: 'active',
  limit: 10
});

completePipeline(taskId, _reason)

Complete a pipeline (mark all stages done). Marks the pipeline as completed and sets the completion timestamp. Only valid when the pipeline is in the ‘release’ stage. Signature
(taskId: string, _reason?: string | undefined) => Promise<void>
Parameters
NameTypeDescription
taskIdstringThe task ID
_reason: string | undefinedOptional completion reason (unused, for API compatibility)
Returns — Promise resolving when complete T4800 T4912 - Implemented SQLite wiring Throws
  • CleoError If pipeline not found or not in releasable state

cancelPipeline(taskId, reason)

Cancel a pipeline before completion. Marks the pipeline as cancelled (user-initiated). Once cancelled, the pipeline cannot be resumed (a new one must be created). Use this for deliberate user decisions to abandon a pipeline. System-forced terminations should use the ‘aborted’ status directly. Signature
(taskId: string, reason: string) => Promise<void>
Parameters
NameTypeDescription
taskIdstringThe task ID
reasonstringReason for cancellation
Returns — Promise resolving when cancelled T4800 T4912 - Implemented SQLite wiring Throws
  • CleoError If pipeline not found or already completed

pipelineExists(taskId)

Check if a pipeline exists for a task. Signature
(taskId: string) => Promise<boolean>
Parameters
NameTypeDescription
taskIdstringThe task ID
Returns — Promise resolving to boolean T4800 T4912 - Implemented SQLite wiring

getPipelineStatistics()

Get pipeline statistics. Returns aggregate counts of pipelines by status and stage. Signature
() => Promise<{ total: number; byStatus: Record<"completed" | "failed" | "cancelled" | "active" | "blocked" | "aborted", number>; byStage: Partial<Record<"research" | "consensus" | "architecture_decision" | ... 5 more ... | "release", number>>; }>
Returns — Promise resolving to statistics object T4800 T4912 - Implemented SQLite wiring Throws
  • CleoError If database query fails

getPipelineStages(taskId)

Get all stages for a pipeline. Signature
(taskId: string) => Promise<PipelineStageRecord[]>
Parameters
NameTypeDescription
taskIdstringThe task ID
Returns — Promise resolving to array of stage records T4912

findResumablePipelines(options, cwd)

Query active pipelines that can be resumed. Searches the lifecycle_pipelines table for pipelines with status ‘active’ and joins with lifecycle_stages to determine current stage status. Also joins with tasks table to get task metadata. Signature
(options?: FindResumableOptions, cwd?: string | undefined) => Promise<ResumablePipeline[]>
Parameters
NameTypeDescription
options: FindResumableOptionsQuery options for filtering
cwd: string | undefinedWorking directory for database
Returns — Promise resolving to array of resumable pipelines Example
// Find all active pipelines
const resumable = await findResumablePipelines();

// Find specific tasks
const specific = await findResumablePipelines({
  taskIds: ['T4805', 'T4806']
});

// Include blocked pipelines
const withBlocked = await findResumablePipelines({
  includeBlocked: true
});

loadPipelineContext(taskId, cwd)

Load complete pipeline context for session resume. Uses SQL JOINs to efficiently load all related data: - Pipeline and current stage - All stages with their status - Gate results for current stage - Evidence linked to current stage - Recent transitions - Task details Signature
(taskId: string, cwd?: string | undefined) => Promise<PipelineContext>
Parameters
NameTypeDescription
taskIdstringThe task ID to load context for
cwd: string | undefinedWorking directory for database
Returns — Promise resolving to pipeline context Example
const context = await loadPipelineContext('T4805');
console.log(`Current stage: ${context.currentStage}`);
console.log(`Stage status: ${context.stages.find(s => s.stage === context.currentStage)?.status}`);

resumeStage(taskId, targetStage, options, cwd)

Resume a specific stage in a pipeline. Updates the stage status from ‘blocked’ or ‘not_started’ to ‘in_progress’, records the transition, and returns the resume result. Signature
(taskId: string, targetStage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", options?: { ...; }, cwd?: string | undefined) => Promise<...>
Parameters
NameTypeDescription
taskIdstringThe task ID
targetStage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to resume
options: \{ ...; \}Resume options
cwd: string | undefinedWorking directory for database
Returns — Promise resolving to resume result Example
const result = await resumeStage('T4805', 'implement');
if (result.success) {
  console.log(`Resumed ${result.taskId} at ${result.stage}`);
}

autoResume(cwd)

Auto-detect where to resume across all active pipelines. Finds the best candidate for resuming work based on: 1. Active stages (currently in progress) 2. Blocked stages (can be unblocked) 3. Failed stages (can be retried) 4. Priority ordering Signature
(cwd?: string | undefined) => Promise<AutoResumeResult>
Parameters
NameTypeDescription
cwd: string | undefinedWorking directory for database
Returns — Promise resolving to auto-resume result Example
const result = await autoResume();
if (result.canResume) {
  console.log(`Recommended: Resume ${result.taskId} at ${result.stage}`);
} else if (result.options && result.options.length > 0) {
  console.log('Multiple options available:', result.options);
}

checkSessionResume(options, cwd)

Check for resumable work on session start. Integrates with session initialization to check for active pipelines and present resumable work to the user. Can auto-resume if there’s a clear single candidate. Signature
(options?: SessionResumeCheckOptions, cwd?: string | undefined) => Promise<SessionResumeCheckResult>
Parameters
NameTypeDescription
options: SessionResumeCheckOptionsResume check options
cwd: string | undefinedWorking directory for database
Returns — Promise resolving to resume check result Example
// On session start
const resumeCheck = await checkSessionResume({ autoResume: true });
if (resumeCheck.didResume) {
  console.log(`Auto-resumed ${resumeCheck.resumedTaskId}`);
} else if (resumeCheck.requiresUserChoice) {
  console.log('Multiple options:', resumeCheck.options);
}

formatResumeSummary(pipelines)

Get resume summary for display to user. Formats resumable pipelines into a human-readable summary. Signature
(pipelines: ResumablePipeline[]) => string
Parameters
NameTypeDescription
pipelinesResumablePipeline[]Resumable pipelines
Returns — Formatted summary string T4805

handleCompletedStage(context)

Handle completed stage edge case. If the current stage is completed, suggests advancing to next stage. Signature
(context: PipelineContext) => { action: "review" | "advance" | "stay"; message: string; nextStage?: "research" | "consensus" | "architecture_decision" | "specification" | ... 5 more ... | undefined; }
Parameters
NameTypeDescription
contextPipelineContextPipeline context
Returns — Recommendation for handling completed stage T4805

handleBlockedStage(context)

Handle blocked stage edge case. Provides information about why a stage is blocked and potential resolutions. Signature
(context: PipelineContext) => { isBlocked: boolean; blockReason?: string | undefined; blockedSince?: Date | undefined; resolutions: string[]; canUnblock: boolean; }
Parameters
NameTypeDescription
contextPipelineContextPipeline context
Returns — Block analysis and resolution hints T4805

checkBlockedStageDetails(taskId, cwd)

Handle blocked stage edge case - async version with database lookup. Signature
(taskId: string, cwd?: string | undefined) => Promise<{ isBlocked: boolean; blockReason?: string | undefined; blockedSince?: Date | undefined; resolutions: string[]; canUnblock: boolean; prerequisites?: { ...; }[] | undefined; }>
Parameters
NameTypeDescription
taskIdstringTask ID to check
cwd: string | undefinedWorking directory
Returns — Block analysis with prerequisite details T4805

checkPrerequisites(targetStage, currentStages)

Check if prerequisites are met for a stage. Validates that all prerequisite stages are in an acceptable state (completed or skipped) for the target stage to proceed. Signature
(targetStage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", currentStages: Record<"research" | ... 7 more ... | "release", StageState>) => Promise<...>
Parameters
NameTypeDescription
targetStage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to check prerequisites for
currentStagesRecord<"research" | ... 7 more ... | "release"Current state of all stages
Returns — Promise resolving to PrereqCheck result Throws
  • CleoError If validation fails
Example
const check = await checkPrerequisites('implement', {
  research: { status: 'completed' },
  spec: { status: 'completed' },
  decompose: { status: 'completed' },
  // ... other stages
});
if (check.met) {
  console.log('Ready to implement');
}

validateTransition(transition, context)

Validate a stage transition. Comprehensive validation that checks both transition rules and prerequisites. This is the core state machine validation logic. Signature
(transition: StateTransition, context: StateMachineContext) => Promise<TransitionValidation>
Parameters
NameTypeDescription
transitionStateTransitionThe transition to validate
contextStateMachineContextCurrent state machine context
Returns — Promise resolving to TransitionValidation Throws
  • CleoError If validation fails unexpectedly
Example
const validation = await validateTransition(
  { from: 'spec', to: 'implement', initiatedBy: 'agent-001' },
  pipelineContext
);
if (!validation.valid) {
  console.log(validation.errors);
}

executeTransition(transition, context)

Execute a state transition. Applies the transition to the state machine context, updating stage statuses and returning the new state. This function does NOT persist to database - that is handled by the pipeline module. Signature
(transition: StateTransition, context: StateMachineContext) => Promise<StateTransitionResult>
Parameters
NameTypeDescription
transitionStateTransitionThe transition to execute
contextStateMachineContextCurrent state machine context
Returns — Promise resolving to StateTransitionResult Throws
  • CleoError If transition is invalid
Example
const result = await executeTransition(
  { from: 'spec', to: 'implement', initiatedBy: 'agent-001' },
  pipelineContext
);
if (result.success) {
  console.log(`Transitioned to ${result.newState.stage}`);
}

setStageStatus(stage, status, context)

Set the status of a stage. Updates stage status with validation of allowed state transitions. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", status: "completed" | ... 4 more ... | "skipped", context: StateMachineContext) => StageState
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to update
status"completed" | ... 4 more ... | "skipped"The new status
contextStateMachineContextCurrent state machine context
Returns — Updated StageState T4800 Throws
  • CleoError If status transition is invalid

getStageStatus(stage, context)

Get the status of a stage. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", context: StateMachineContext) => "completed" | ... 4 more ... | "skipped"
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to check
contextStateMachineContextCurrent state machine context
Returns — The stage status T4800

isValidStatusTransition(from, to)

Check if a status transition is valid. State transitions: not_started → in_progress, skipped in_progress → completed, blocked, failed blocked → in_progress failed → in_progress (retry) completed → (no transition - use force to override) skipped → (no transition) Signature
(from: "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped", to: "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped") => { ...; }
Parameters
NameTypeDescription
from"completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped"Current status
to"completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped"Target status
Returns — Object with valid flag and reason T4800

createInitialContext(pipelineId, assignedAgent)

Create initial state machine context for a pipeline. Signature
(pipelineId: string, assignedAgent?: string | undefined) => StateMachineContext
Parameters
NameTypeDescription
pipelineIdstringThe pipeline/task ID
assignedAgent: string | undefinedOptional agent to assign
Returns — Initial StateMachineContext T4800

getValidNextStages(context, includeForce)

Get stages that can be transitioned to from the current stage. Signature
(context: StateMachineContext, includeForce?: boolean) => ("research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release")[]
Parameters
NameTypeDescription
contextStateMachineContextCurrent state machine context
includeForce: booleanWhether to include transitions that require force
Returns — Array of valid next stages T4800

getCurrentStageState(context)

Get the current stage state. Signature
(context: StateMachineContext) => StageState
Parameters
NameTypeDescription
contextStateMachineContextState machine context
Returns — Current StageState T4800

isTerminalState(context)

Check if the pipeline is in a terminal state. Signature
(context: StateMachineContext) => boolean
Parameters
NameTypeDescription
contextStateMachineContextState machine context
Returns — True if in release stage and completed T4800

isBlocked(context)

Check if the pipeline is blocked. Signature
(context: StateMachineContext) => boolean
Parameters
NameTypeDescription
contextStateMachineContextState machine context
Returns — True if current stage is blocked T4800

validateTransitions(transitions, context)

Validate multiple transitions. Signature
(transitions: StateTransition[], context: StateMachineContext) => Promise<TransitionValidation[]>
Parameters
NameTypeDescription
transitionsStateTransition[]Array of transitions to validate
contextStateMachineContextState machine context
Returns — Array of validation results T4800

canSkipStage(stage)

Check if a stage can be skipped. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => boolean
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to check
Returns — True if stage is skippable T4800

skipStage(stage, reason, context)

Skip a stage with validation. Signature
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", _reason: string, context: StateMachineContext) => StageState
Parameters
NameTypeDescription
stage"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"The stage to skip
reasonReason for skipping
contextStateMachineContextState machine context
Returns — Updated StageState T4800 Throws
  • CleoError If stage cannot be skipped

getContextStatusFromPercentage()

Determine status from percentage. Signature
(percentage: number) => ContextStatus

processContextInput()

Process context window input and write state file. Returns the status line string for display. Tries adapter-based context monitoring first; falls back to local implementation. Signature
(input: ContextWindowInput, cwd?: string | undefined) => Promise<string>

isHITLEnabled()

Check if HITL warnings are enabled. Signature
(cwd?: string | undefined) => boolean

generateHITLWarnings()

Generate HITL warnings based on lock state. Signature
(cwd?: string | undefined) => HITLWarningsResult

getHighestLevel()

Get highest warning level from warnings. Signature
(warnings: HITLWarning[]) => HITLLevel

getConcurrencyJson()

Get concurrency data for analyze JSON output. Signature
(cwd?: string | undefined) => Record<string, unknown>

getEnforcementMode()

Get the current enforcement mode. Signature
(cwd?: string | undefined) => EnforcementMode

isSessionEnforcementEnabled()

Check if session enforcement is enabled. Signature
(cwd?: string | undefined) => boolean

getActiveSessionInfo()

Get active session info. Returns null if no active session. Signature
(cwd?: string | undefined) => Promise<ActiveSessionInfo | null>

requireActiveSession()

Require an active session for write operations. In strict mode, throws if no session is active. In warn mode, returns a warning but allows the operation. In none mode, always allows. Signature
(operation: string, cwd?: string | undefined) => Promise<EnforcementResult>

validateTaskInScope()

Validate that a task is within the current session’s scope. Only enforced when a session is active. Signature
(taskId: string, taskEpicId?: string | undefined, cwd?: string | undefined) => Promise<{ inScope: boolean; warning?: string | undefined; }>

checkStatuslineIntegration()

Check if statusline integration is configured. Returns the current integration status. Signature
() => StatuslineStatus

getStatuslineConfig()

Get the statusline setup command for Claude Code settings. Signature
() => Record<string, unknown>

getSetupInstructions()

Get human-readable setup instructions. Signature
() => string

getPreferredChannel(domain, operation)

Look up the preferred channel for a given domain + operation. Signature
(domain: string, operation: string) => "cli" | "mcp" | "either"
Parameters
NameTypeDescription
domainstringDomain name
operationstringOperation name
Returns — Preferred channel (‘mcp’, ‘cli’, or ‘either’ as fallback)

getRoutingForDomain(domain)

Get routing entries for a specific domain. Signature
(domain: string) => RoutingEntry[]
Parameters
NameTypeDescription
domainstringDomain name
Returns — All routing entries for the domain

getOperationsByChannel(channel)

Get all operations that prefer a specific channel. Signature
(channel: "cli" | "mcp" | "either") => RoutingEntry[]
Parameters
NameTypeDescription
channel"cli" | "mcp" | "either"Channel preference to filter by
Returns — Matching routing entries

generateMemoryProtocol(context)

Generate dynamic memory protocol instructions based on provider capabilities. Signature
(context: ProviderContext) => string
Parameters
NameTypeDescription
contextProviderContextProvider capability context
Returns — Markdown content for memory protocol guidance

generateRoutingGuide(context)

Generate a dynamic routing guide based on operation preferences. Signature
(context: ProviderContext) => string
Parameters
NameTypeDescription
contextProviderContextProvider capability context
Returns — Markdown content showing preferred channels per operation

generateDynamicSkillContent(context)

Generate complete dynamic skill content for the current provider. Signature
(context: ProviderContext) => string
Parameters
NameTypeDescription
contextProviderContextProvider capability context
Returns — Complete dynamic skill markdown content

TaskCache

In-memory cache for task indices with checksum-based staleness detection. Signature
typeof TaskCache
Methods

computeChecksum()

Compute a checksum from task data for staleness detection.
(tasks: Task[]) => string

init()

Initialize or rebuild cache from tasks. Returns true if cache was rebuilt, false if already valid.
(tasks: Task[]) => boolean

buildLabelIndex()

(tasks: Task[]) => void

buildPhaseIndex()

(tasks: Task[]) => void

buildHierarchyIndex()

(tasks: Task[]) => void

getTasksByLabel()

Get task IDs by label.
(label: string) => string[]

getTasksByPhase()

Get task IDs by phase.
(phase: string) => string[]

getAllLabels()

Get all labels.
() => string[]

getAllPhases()

Get all phases.
() => string[]

getLabelCount()

Get label count for a specific label.
(label: string) => number

getParent()

Get parent ID for a task.
(taskId: string) => string | null

getChildren()

Get children IDs for a task.
(taskId: string) => string[]

getDepth()

Get depth for a task.
(taskId: string) => number

getChildCount()

Get child count.
(taskId: string) => number

getRootTasks()

Get root tasks (no parent).
() => string[]

getLeafTasks()

Get leaf tasks (no children).
() => string[]

invalidate()

Force invalidation and rebuild.
() => void

getStats()

Get cache statistics.
() => { initialized: boolean; labelCount: number; phaseCount: number; taskCount: number; maxDepth: number; }

extractPackageMeta()

Extract package metadata from an export file. T4552 Signature
(sourceFilePath: string) => Promise<ImportPackageMeta>

logImportStart()

Log import operation start with package metadata. T4552 Signature
(sourceFilePath: string, sessionId?: string | undefined, cwd?: string | undefined) => Promise<void>

logImportSuccess()

Log import operation completion with full metadata. T4552 Signature
(sourceFilePath: string, tasksImported: string[], idRemap: Record<string, string>, conflicts?: { type: string; resolution: string; }[] | undefined, options?: ImportOptions | undefined, sessionId?: string | undefined, cwd?: string | undefined) => Promise<...>

logImportError()

Log import operation error with diagnostic details. T4552 Signature
(sourceFilePath: string, errorMessage: string, errorCode: string | number, stage?: "validation" | "unknown" | "parsing" | "remapping" | "writing", sessionId?: string | undefined, cwd?: string | undefined) => Promise<...>

logImportConflict()

Log import conflict detection and resolution. T4552 Signature
(conflictType: ImportConflictType, taskId: string, conflictDetails: Record<string, unknown>, resolution: ImportConflictResolution, sessionId?: string | undefined, cwd?: string | undefined) => Promise<...>

topologicalSortTasks()

Topological sort for task import order using Kahn’s algorithm. Ensures tasks are imported in dependency order: - Parents before children (parentId references) - Dependencies before dependents (depends[] references) - Only counts edges to tasks within the set (external deps ignored) T4552 Signature
(tasks: SortableTask[]) => string[]

detectCycles()

Detect cycles in task dependency graph. Returns true if no cycles, false if cycles detected. T4552 Signature
(tasks: SortableTask[]) => boolean

findActivePipelinesWithStagesAndTasks(taskIds, cwd)

Find active pipelines joined with their stages and tasks. Optionally filters by specific task IDs. Signature
(taskIds?: string[] | undefined, cwd?: string | undefined) => Promise<PipelineStageTaskRow[]>
Parameters
NameTypeDescription
taskIds: string[] | undefinedOptional list of task IDs to filter by
cwd: string | undefinedWorking directory for database
Returns — Rows with pipeline, stage, and task data

findPipelineWithCurrentStageAndTask(taskId, cwd)

Find a pipeline with its current stage and task by taskId. Matches stages where stageName equals the pipeline’s currentStageId. Signature
(taskId: string, cwd?: string | undefined) => Promise<PipelineStageTaskRow[]>
Parameters
NameTypeDescription
taskIdstringTask ID to look up
cwd: string | undefinedWorking directory for database
Returns — Matching rows (typically 0 or 1)

findPipelineWithStage(taskId, stageName, cwd)

Find a pipeline and a specific stage by taskId and stageName. Signature
(taskId: string, stageName: string, cwd?: string | undefined) => Promise<PipelineStageRow[]>
Parameters
NameTypeDescription
taskIdstringTask ID
stageNamestringStage name to match
cwd: string | undefinedWorking directory for database
Returns — Matching rows (typically 0 or 1)

updatePipelineCurrentStage(pipelineId, currentStageId, cwd)

Update pipeline’s currentStageId. Signature
(pipelineId: string, currentStageId: string, cwd?: string | undefined) => Promise<void>
Parameters
NameTypeDescription
pipelineIdstringPipeline ID to update
currentStageIdstringNew current stage identifier
cwd: string | undefinedWorking directory for database

getStagesByPipelineId(pipelineId, cwd)

Get all stages for a pipeline, ordered by sequence. Signature
(pipelineId: string, cwd?: string | undefined) => Promise<{ id: string; status: "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped"; notesJson: string | null; ... 15 more ...; provenanceChainJson: string | null; }[]>
Parameters
NameTypeDescription
pipelineIdstringPipeline ID
cwd: string | undefinedWorking directory for database
Returns — All stage rows for the pipeline

activateStage(stageId, startedAt, cwd)

Update a stage’s status to ‘in_progress’ and clear block fields. Signature
(stageId: string, startedAt: string, cwd?: string | undefined) => Promise<void>
Parameters
NameTypeDescription
stageIdstringStage ID to update
startedAtstringISO timestamp for when the stage started
cwd: string | undefinedWorking directory for database

findPipelineWithCurrentStage(taskId, cwd)

Find pipeline with current stage (no task join) by taskId. Used by checkBlockedStageDetails. Signature
(taskId: string, cwd?: string | undefined) => Promise<PipelineStageRow[]>
Parameters
NameTypeDescription
taskIdstringTask ID
cwd: string | undefinedWorking directory for database
Returns — Matching rows

getGateResultsByStageId(stageId, cwd)

Get gate results for a stage, ordered by checkedAt descending. Signature
(stageId: string, cwd?: string | undefined) => Promise<{ id: string; reason: string | null; stageId: string; gateName: string; result: "warn" | "pass" | "fail"; checkedAt: string; checkedBy: string; details: string | null; }[]>
Parameters
NameTypeDescription
stageIdstringStage ID
cwd: string | undefinedWorking directory for database
Returns — Gate result rows

getGateResultsByStageIdUnordered(stageId, cwd)

Get gate results for a stage without ordering (for simple checks). Signature
(stageId: string, cwd?: string | undefined) => Promise<{ id: string; reason: string | null; stageId: string; gateName: string; result: "warn" | "pass" | "fail"; checkedAt: string; checkedBy: string; details: string | null; }[]>
Parameters
NameTypeDescription
stageIdstringStage ID
cwd: string | undefinedWorking directory for database
Returns — Gate result rows

getEvidenceByStageId(stageId, cwd)

Get evidence for a stage, ordered by recordedAt descending. Signature
(stageId: string, cwd?: string | undefined) => Promise<{ id: string; description: string | null; type: "file" | "url" | "manifest"; stageId: string; uri: string; recordedAt: string; recordedBy: string | null; }[]>
Parameters
NameTypeDescription
stageIdstringStage ID
cwd: string | undefinedWorking directory for database
Returns — Evidence rows

getRecentTransitions(pipelineId, limit, cwd)

Get recent transitions for a pipeline, ordered by createdAt descending. Signature
(pipelineId: string, limit?: number, cwd?: string | undefined) => Promise<{ id: string; createdAt: string; pipelineId: string; fromStageId: string; toStageId: string; transitionType: "automatic" | "manual" | "forced"; transitionedBy: string | null; }[]>
Parameters
NameTypeDescription
pipelineIdstringPipeline ID
limit: numberMax rows to return (default: 10)
cwd: string | undefinedWorking directory for database
Returns — Transition rows

insertTransition(transition, cwd)

Insert a new transition record. Signature
(transition: { id: string; pipelineId: string; fromStageId: string; toStageId: string; createdAt?: string | undefined; transitionType?: "automatic" | "manual" | "forced" | undefined; transitionedBy?: string | ... 1 more ... | undefined; }, cwd?: string | undefined) => Promise<...>
Parameters
NameTypeDescription
transition\{ id: string; pipelineId: string; fromStageId: string; toStageId: string; createdAt?: string | undefined; transitionType?: "automatic" | "manual" | "forced" | undefined; transitionedBy?: string | ... 1 more ... | undefined; \}Transition data to insert
cwd: string | undefinedWorking directory for database

checkAtomicity()

Check task atomicity using 6-point heuristic test. Default threshold: 4 (passing requires = 4/6 criteria met). Signature
(task: Task, threshold?: number) => AtomicityResult

extractTaskRefs()

Extract task IDs from text content. Scans for patterns like T1234, T001, T42 (T followed by 3+ digits). Signature
(text: string, excludeId?: string | undefined) => string[]

createRelatesEntries()

Create relates entries from extracted task IDs. Signature
(refs: string[], relType?: RelatesType, reason?: string | undefined) => RelatesEntry[]

mergeRelatesArrays()

Merge new relates entries with existing ones. Existing entries take precedence (dedup by taskId). Signature
(existing: RelatesEntry[], newEntries: RelatesEntry[]) => RelatesEntry[]

validateRelatesRefs()

Validate that referenced task IDs exist. Returns array of invalid (non-existent) task IDs. Signature
(relates: RelatesEntry[], validTaskIds: string[]) => string[]

extractAndCreateRelates()

Convenience: extract task refs from text and create relates entries. Signature
(text: string, excludeId?: string | undefined, relType?: RelatesType, reason?: string | undefined) => RelatesEntry[]

calculateAffectedTasks()

Calculate which tasks would be affected by a delete operation. Signature
(taskId: string, strategy: string, tasks: Task[]) => AffectedTasks

calculateImpact()

Calculate impact of deletion. Signature
(affected: AffectedTasks, tasks: Task[]) => DeleteImpact

generateWarnings()

Generate warnings based on impact analysis. Signature
(affected: AffectedTasks, impact: DeleteImpact, strategy: string) => DeleteWarning[]

previewDelete()

Main preview function - coordinates all preview calculations. Signature
(taskId: string, tasks: Task[], options?: { strategy?: string | undefined; reason?: string | undefined; } | undefined) => DeletePreview

isValidStrategy()

Validate a strategy name. Signature
(strategy: string) => strategy is ChildStrategy

handleChildren()

Handle children using the specified strategy. Returns the modified tasks array and the strategy result. Signature
(taskId: string, strategy: ChildStrategy, tasks: Task[], options?: { force?: boolean | undefined; cascadeThreshold?: number | undefined; allowCascade?: boolean | undefined; } | undefined) => { ...; }

GraphCache

Graph cache for expensive dependency calculations. Automatically invalidates when tasks change. Signature
typeof GraphCache
Methods

computeChecksum()

Compute a simple checksum from task data to detect changes.
(tasks: Task[]) => string

isValid()

Check if cache is still valid for given tasks.
(tasks: Task[]) => boolean

isExpired()

Check if a cache entry has expired.
<T>(entry: CacheEntry<T>) => boolean

invalidate()

Invalidate all caches.
() => void

ensureFresh()

Ensure cache is fresh for the given task set.
(tasks: Task[]) => void

getDescendants()

Get descendants of a task (cached).
(taskId: string, tasks: Task[]) => string[]

getChildren()

Get children of a task (cached).
(taskId: string, tasks: Task[]) => string[]

getDependents()

Get dependents of a task (cached).
(taskId: string, tasks: Task[]) => string[]

getWaves()

Get dependency waves (cached).
(tasks: Task[]) => DependencyWave[]

getStats()

Get cache statistics.
() => { descendantsSize: number; childrenSize: number; dependentsSize: number; hasWaves: boolean; }

discoverByLabels()

Discover related tasks by shared labels. Signature
(taskId: string, tasks: Task[]) => DiscoveryMatch[]

discoverByDescription()

Discover related tasks by description similarity (keyword-based Jaccard). Signature
(taskId: string, tasks: Task[]) => DiscoveryMatch[]

discoverByFiles()

Discover related tasks by shared files. Signature
(taskId: string, tasks: Task[]) => DiscoveryMatch[]

discoverByHierarchy()

Discover related tasks by hierarchical proximity (siblings and cousins). Signature
(taskId: string, tasks: Task[], options?: { siblingBoost?: number | undefined; cousinBoost?: number | undefined; } | undefined) => DiscoveryMatch[]

discoverRelatedTasks()

Discover related tasks using all methods combined. Signature
(taskId: string, tasks: Task[], method?: DiscoveryMethod) => DiscoveryMatch[]

suggestRelates()

Suggest relates entries filtered by threshold. Signature
(taskId: string, tasks: Task[], threshold?: number) => DiscoveryMatch[]

getCurrentPhase()

Get the current active phase from project metadata. Signature
(project: ProjectMeta) => Phase | null

getTasksByPhase()

Get tasks belonging to a specific phase. Signature
(phaseName: string, tasks: Task[]) => Task[]

calculatePhaseProgress()

Calculate progress for a phase. Signature
(phaseName: string, tasks: Task[]) => PhaseProgress

getAllPhaseProgress()

Get progress for all phases. Signature
(phases: Record<string, Phase>, tasks: Task[]) => PhaseProgress[]

validatePhaseTransition()

Signature
(fromPhase: string | null, toPhase: string, phases: Record<string, Phase>) => PhaseTransitionValidation

createPhaseTransition()

Create a phase transition record. Signature
(phase: string, transitionType: "completed" | "started" | "rollback", taskCount: number, fromPhase?: string | null | undefined, reason?: string | undefined) => PhaseTransition

applyPhaseTransition()

Apply a phase transition to project metadata. Returns updated project data. Signature
(project: ProjectMeta, toPhase: string, transitionType: "completed" | "started" | "rollback", taskCount: number, reason?: string | undefined) => ProjectMeta

getNextPhase()

Get the next phase in order. Signature
(currentPhaseName: string | null, phases: Record<string, Phase>) => string | null

allPhasesComplete()

Check if all phases are complete. Signature
(phases: Record<string, Phase>) => boolean

reparentTask(data, opts)

Reparent a task within a TaskFile. Mutates the task in-place within data.tasks. Updates parentId, type, and updatedAt on the target task, and lastUpdated on the TaskFile. Signature
(data: TaskFile, opts: ReparentOptions) => Promise<ReparentResult>
Parameters
NameTypeDescription
dataTaskFileThe loaded TaskFile (mutated in place)
optsReparentOptionsReparent options (taskId, newParentId)
Returns — Result with old/new parent and new type

getSizeWeight()

Get weight for a task size. Signature
(size: TaskSize | null | undefined) => number

getPriorityWeight()

Get weight for a task priority. Signature
(priority: TaskPriority) => number

calculateTaskScore()

Calculate a composite score for task ordering. Higher score = should be worked on first. Signature
(task: Task) => number

sortByWeight()

Sort tasks by weighted score (highest first). Signature
(tasks: Task[]) => Task[]

calculateTotalEffort()

Calculate total weighted effort for a set of tasks. Signature
(tasks: Task[]) => number

calculateWeightedProgress()

Calculate completion percentage by weight. Signature
(tasks: Task[]) => number

calculateRemainingEffort()

Estimate remaining effort (weighted sum of non-complete tasks). Signature
(tasks: Task[]) => number

getLastActivity()

Get the most recent activity timestamp for a task. Signature
(task: Task) => string

classifyStaleness()

Classify staleness level for a task. Signature
(task: Task, thresholds?: StalenessThresholds) => StalenessLevel

getStalenessInfo()

Get staleness info for a single task. Signature
(task: Task, thresholds?: StalenessThresholds | undefined) => StalenessInfo

findStaleTasks()

Find all stale tasks (stale, critical, or abandoned). Signature
(tasks: Task[], thresholds?: StalenessThresholds | undefined) => StalenessInfo[]

getStalenessSummary()

Signature
(tasks: Task[], thresholds?: StalenessThresholds | undefined) => StalenessSummary

validateReleaseTask()

Validate release protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

checkReleaseManifest()

Validate release protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

validateResearchTask()

Validate research protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

checkResearchManifest()

Validate research protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

validateTestingTask()

Validate testing protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

checkTestingManifest()

Validate testing protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

validateValidationTask()

Validate verification/validation protocol for a task. Signature
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>

checkValidationManifest()

Validate validation protocol from manifest file. Signature
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>