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

getLogDir()

Get the current log directory path. Useful for read APIs that need to scan log files. Signature

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

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

getSystemInfo()

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

_resetPlatformPathsCache()

Invalidate the path and system info caches. Use in tests after mutating CLEO_HOME env var. Signature

isProjectInitialized()

Check if a CLEO project is initialized at the given root. Checks for tasks.db. Signature

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

getCleoTemplatesDir()

Get the global CLEO templates directory. Signature

getCleoSchemasDir()

Get the global CLEO schemas directory. Signature

getCleoDocsDir()

Get the global CLEO docs directory. Signature

getCleoDir()

Get the project CLEO data directory (relative). Respects CLEO_DIR env var, defaults to “.cleo”. Signature

getCleoDirAbsolute()

Get the absolute path to the project CLEO directory. Signature

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

resolveProjectPath()

Resolve a project-relative path to an absolute path. Signature

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

getConfigPath()

Get the path to the project’s config.json file. Signature

getSessionsPath()

Get the path to the project’s sessions.json file. Signature

getArchivePath()

Get the path to the project’s archive file. Signature

getLogPath()

Get the path to the project’s log file. Canonical structured runtime log path (pino). T4644 Signature

getBackupDir()

Get the backup directory for operational backups. Signature

getGlobalConfigPath()

Get the global config file path. Signature

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

getAgentOutputsAbsolute()

Get the absolute path to the agent outputs directory. T4700 Signature

getManifestPath()

Get the absolute path to the MANIFEST.jsonl file. Checks config.agentOutputs.manifestFile for custom filename, defaults to ‘MANIFEST.jsonl’. T4700 Signature

getManifestArchivePath()

Get the absolute path to the MANIFEST.archive.jsonl file. T4700 Signature

isAbsolutePath()

Check if a path is absolute (POSIX or Windows). Signature

getCleoLogDir()

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

getCleoCacheDir()

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

getCleoTempDir()

Get the OS temp directory for CLEO ephemeral files. Signature

getCleoConfigDir()

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

getAgentsHome()

Get the global agents hub directory. Respects AGENTS_HOME env var, defaults to ~/.agents. Signature

getClaudeAgentsDir()

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

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

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

listSqliteBackups()

List existing SQLite backup snapshots, newest first. Signature

getBrainDbPath()

Get the path to the brain.db SQLite database file. Signature

resolveBrainMigrationsFolder()

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

isBrainVecLoaded()

Check whether the sqlite-vec extension is loaded for the current brain.db. Signature

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

closeBrainDb()

Close the brain.db database connection and release resources. Signature

resetBrainDbState()

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

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

getNexusDbPath()

Get the path to the nexus.db SQLite database file. nexus.db lives in the global ~/.cleo/ directory. Signature

resolveNexusMigrationsFolder()

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

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

closeNexusDb()

Close the nexus.db database connection and release resources. Signature

resetNexusDbState()

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

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

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

getDbPath()

Get the path to the SQLite database file. Signature

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

resolveMigrationsFolder()

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

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

closeDb()

Close the database connection and release resources. Signature

resetDbState()

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

getSchemaVersion()

Get the schema version from the database. Signature

dbExists()

Check if the database file exists. Signature

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

getNativeTasksDb()

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

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

safeParseJson()

Parse a JSON string, returning undefined on null/undefined input or parse error. Signature

safeParseJsonArray()

Parse a JSON string expected to contain an array. Returns undefined for null/undefined input, empty arrays, or parse errors. Signature

rowToTask()

Convert a database TaskRow to a domain Task object. Signature

taskToRow()

Convert a domain Task to a database row for insert/upsert. Signature

archivedTaskToRow()

Convert a domain Task to a row suitable for archived tasks. Signature

rowToSession()

Convert a SessionRow to a domain Session. Signature

getErrorDefinition()

Look up an error definition by exit code. Signature

getErrorDefinitionByLafsCode()

Look up an error definition by LAFS string code. Signature

getAllErrorDefinitions()

Get all error definitions as an array. Signature

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
Methods

toLAFSError()

Produce a LAFS-conformant error object. T4655

toProblemDetails()

Produce an RFC 9457 Problem Details object. T5240

toJSON()

Structured JSON representation for LAFS output (backward compatible).

getHttpStatus()

Derive HTTP status from exit code range. Used as fallback when catalog lookup misses.

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

upsertSession()

Upsert a single session row into the sessions table. Signature

updateDependencies()

Update dependencies for a task: delete existing, then re-insert. Optionally filters by a set of valid IDs. Signature

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

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

loadRelationsForTasks()

Batch-load relations for a list of tasks and apply them in-place. Mirrors loadDependenciesForTasks pattern for task_relations table (T5168). Signature

setMetaValue()

Write a JSON blob to the schema_meta table by key. Signature

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
Parameters

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

safeReadFile()

Read a file and return its contents. Returns null if the file does not exist. Signature

atomicWriteJson()

Write JSON data atomically with consistent formatting. Signature

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
Parameters Returns — Result with paths and success status

restoreDatabaseFromBackup(dbPath, backupPath)

Restore database from backup after failed migration. Signature
Parameters Returns — true if restore succeeded

cleanupMigrationArtifacts(backupPath)

Clean up migration artifacts after successful migration. Signature
Parameters Returns — true if cleanup succeeded

validateSqliteDatabase(dbPath)

Validate SQLite database integrity by attempting to open it. Signature
Parameters 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

listBackups()

List existing backups for a file, sorted by number (newest first). Signature

restoreFromBackup()

Restore a file from its most recent backup. Returns the path of the backup that was restored. Signature

acquireLock()

Acquire an exclusive lock on a file. Returns a release function that must be called when done. Signature

isLocked()

Check if a file is currently locked. Signature

withLock()

Execute a function while holding an exclusive lock on a file. The lock is automatically released when the function completes (or throws). Signature

isProviderHookEvent()

Type guard for CAAMP/provider-discoverable hook events. Signature

isInternalHookEvent()

Type guard for CLEO-local coordination hook events. Signature

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

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.

isEnabled()

Check if a specific event is currently enabled. Both the global enabled flag and the per-event flag must be true.

setConfig()

Update the hook system configuration. Merges the provided config with the existing config.

getConfig()

Get the current hook configuration.

listHandlers()

List all registered handlers for a specific event. Returns handlers in priority order (highest first).

readJson()

Read and parse a JSON file. Returns null if the file does not exist. Signature

readJsonRequired()

Read a JSON file, throwing if it doesn’t exist. Signature

computeChecksum()

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

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

appendJsonl()

Append a line to a JSONL file atomically. Used for manifest entries and audit logs. Signature

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

makeCleoGitEnv()

Build environment variables that point git at the isolated .cleo/.git repo. T4872 Signature

cleoGitCommand()

Run a git command against the isolated .cleo/.git repo, suppressing errors. T4872 Signature

isCleoGitInitialized()

Check whether the isolated .cleo/.git repo has been initialized. T4872 Signature

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

loadCheckpointConfig()

Load checkpoint configuration from config.json. T4552 Signature

shouldCheckpoint()

Check whether a checkpoint should be performed. Evaluates: enabled, .cleo/.git initialized, debounce elapsed, files changed. T4552 T4872 Signature

gitCheckpoint()

Stage .cleo/ state files and commit to the isolated .cleo/.git repo. Never fatal - all git errors are suppressed. T4552 T4872 Signature

gitCheckpointStatus()

Show checkpoint configuration and status. T4552 T4872 Signature

gitCheckpointDryRun()

Show what files would be committed (dry-run). T4552 T4872 Signature

DataSafetyError

Safety violation error Signature

getSafetyStats()

Get current safety statistics Signature

resetSafetyStats()

Reset safety statistics (for testing) Signature

safeSaveSessions()

Safe wrapper for DataAccessor.saveSessions() Signature

safeSaveArchive()

Safe wrapper for DataAccessor.saveArchive() Signature

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

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

runDataIntegrityCheck()

Run comprehensive data integrity check. Validates all data files and sequence consistency. Signature

forceSafetyCheckpoint()

Force immediate checkpoint. Use before destructive operations. Signature

disableSafety()

Disable all safety for current process. DANGEROUS - only use for recovery operations. Signature

enableSafety()

Re-enable safety after being disabled. Signature

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
Methods

logVerbose()

Log safety operation if verbose mode is enabled.

getSafetyOptions()

Get safety options for data-safety-central operations.

loadArchive()

loadSessions()

saveSessions()

saveArchive()

appendLog()

upsertSingleTask()

archiveSingleTask()

removeSingleTask()

loadSingleTask()

addRelation()

getMetaValue()

setMetaValue()

getSchemaVersion()

queryTasks()

countTasks()

getChildren()

countChildren()

countActiveChildren()

getAncestorChain()

getSubtree()

getDependents()

getDependencyChain()

taskExists()

loadTasks()

updateTaskFields()

getNextPosition()

shiftPositions()

transaction()

getActiveSession()

upsertSingleSession()

removeSingleSession()

close()

wrapWithSafety(accessor, cwd)

Wrap a DataAccessor with safety. This is the internal factory helper that wraps any accessor with the SafetyDataAccessor wrapper. Signature
Parameters Returns — SafetyDataAccessor wrapping the input

isSafetyEnabled()

Check if safety is currently enabled. Signature
Returns — true if safety checks are active

getSafetyStatus()

Get safety status information. Signature
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

getAccessor()

Convenience: get a DataAccessor with auto-detected engine. Signature

showSequence()

Show current sequence state. Signature

checkSequence()

Check sequence integrity. Signature

repairSequence()

Repair sequence if behind. Signature

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

SafetyError

Safety violation error. Signature

checkTaskExists()

Check if a task ID already exists (collision detection). Signature
Throws
  • SafetyError if task exists and strict mode is enabled

verifyTaskWrite()

Verify a task was actually written to the database. Signature
Throws
  • SafetyError if verification fails

validateAndRepairSequence()

Validate and repair sequence if necessary. Signature
Returns — true if sequence was valid or successfully repaired

triggerCheckpoint()

Trigger auto-checkpoint after successful write. Signature

safeCreateTask()

Safely create a task with all safety mechanisms. Wraps the actual createTask operation. Signature

safeUpdateTask()

Safely update a task with all safety mechanisms. Signature

safeDeleteTask()

Safely delete a task with all safety mechanisms. Signature

verifySessionWrite()

Verify session write. Signature

safeCreateSession()

Safely create a session with all safety mechanisms. Signature

forceCheckpointBeforeOperation()

Force a checkpoint before destructive operations. Use this before migrations, bulk updates, etc. Signature

runDataIntegrityCheck()

Run comprehensive data integrity check. Reports all issues found. Signature

getTask()

Get a task by ID, including its dependencies. Signature

updateTask()

Update an existing task. Signature

deleteTask()

Delete a task by ID. Signature

listTasks()

List tasks with optional filters. Signature

findTasks()

Find tasks by fuzzy text search. Signature

archiveTask()

Archive a task (sets status to ‘archived’ with metadata). Signature

addDependency()

Add a dependency between tasks. Signature

removeDependency()

Remove a dependency. Signature

addRelation()

Add a relation between tasks. Signature

getRelations()

Get relations for a task. Signature

getBlockerChain()

Get the dependency chain (blockers) for a task using recursive CTE. Signature

getChildren()

Get children of a task (hierarchy). Signature

getSubtree()

Build a tree from a root task using recursive CTE. Signature

countByStatus()

Count tasks by status. Signature

countTasks()

Get total task count (excluding archived). Signature

createTask()

Create a task with full safety protections. Includes: collision detection, write verification, sequence validation, auto-checkpoint. Signature

updateTaskSafe()

Update a task with full safety protections. Includes: write verification, auto-checkpoint. Signature

deleteTaskSafe()

Delete a task with full safety protections. Includes: delete verification, auto-checkpoint. Signature

showTask()

Get a task by ID with enriched details. Checks active tasks first, then archive if not found. T4460 Signature

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

paginate()

Apply pagination to an array of items and return the sliced result with page metadata. T4668 T4663 Signature

toCompact()

Convert a full Task to compact representation. Signature

listTasks()

List tasks with optional filtering and pagination. T4460 Signature

fuzzyScore()

Calculate fuzzy match score between query and text. Higher score = better match. 0 = no match. T4460 Signature

findTasks()

Search tasks by fuzzy matching, ID prefix, or exact title. Returns minimal fields only (context-efficient). T4460 Signature

extractAdrId()

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

parseFrontmatter()

Parse bold-key frontmatter pattern: Key: value Signature

extractTitle()

Extract H1 title from markdown Signature

parseAdrFile()

Parse a single ADR markdown file into an AdrRecord Signature

linkPipelineAdr(projectRoot, taskId)

Link ADRs to a pipeline task when the architecture_decision stage completes. Signature
Parameters

syncAdrsToDb()

Sync all ADR markdown files into the architecture_decisions table AND regenerate MANIFEST.jsonl in one pass. Signature

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

Record an evidence artifact linked to a lifecycle stage. Writes to the SQLite lifecycle_evidence table. Signature
Parameters Returns — The created evidence record

getEvidence(epicId, stage, cwd)

Query evidence records for an epic, optionally filtered by stage. Signature
Parameters 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
Parameters Returns — The created evidence record

getEvidenceSummary(epicId, cwd)

Aggregate evidence counts per stage for an epic. Signature
Parameters Returns — Array of per-stage summaries with type breakdowns

normalizeEpicId(dirName)

Strip suffixes from epic directory names. E.g. T4881_install-channels - T4881 Signature
Parameters Returns — The normalized T#### epic ID

getRcasdBaseDir(cwd)

Get the absolute path to the .cleo/rcasd/ base directory. Signature
Parameters 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
Parameters 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
Parameters 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
Parameters Returns — Absolute path to the stage subdirectory

ensureStagePath(epicId, stage, cwd)

Get the stage subdirectory path, creating it if it does not exist. Signature
Parameters 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
Parameters 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
Parameters 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
Parameters Returns — Array of file info with extracted epic ID

listEpicDirs(cwd)

List all epic directories across rcasd/ and rcsd/. Signature
Parameters 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
Parameters Returns — Parsed frontmatter, body, and raw YAML block

serializeFrontmatter(metadata)

Convert a FrontmatterMetadata object to a YAML frontmatter string. Output format: Signature
Parameters 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
Parameters 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
Parameters 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
Parameters Returns — Array of files with matching related links

getStageOrder(stage)

Get the order/index of a stage (1-based). Signature
Parameters Returns — The stage order (1-9) T4800

isStageBefore(stageA, stageB)

Check if stage A comes before stage B in the pipeline. Signature
Parameters Returns — True if stageA comes before stageB T4800

isStageAfter(stageA, stageB)

Check if stage A comes after stage B in the pipeline. Signature
Parameters Returns — True if stageA comes after stageB T4800

getNextStage(stage)

Get the next stage in the pipeline. Signature
Parameters Returns — The next stage, or null if at the end T4800

getPreviousStage(stage)

Get the previous stage in the pipeline. Signature
Parameters Returns — The previous stage, or null if at the start T4800

getStagesBetween(from, to)

Get all stages between two stages (inclusive). Signature
Parameters Returns — Array of stages between from and to T4800

getPrerequisites(stage)

Get prerequisites for a stage. Signature
Parameters Returns — Array of prerequisite stages T4800

isPrerequisite(potentialPrereq, stage)

Check if one stage is a prerequisite of another. Signature
Parameters Returns — True if potentialPrereq is required before stage T4800

getDependents(stage)

Get all stages that depend on a given stage. Signature
Parameters Returns — Array of stages that require this stage T4800

isValidStage(stage)

Check if a stage name is valid. Signature
Parameters Returns — True if valid stage name T4800

validateStage(stage)

Validate a stage name and throw if invalid. Signature
Parameters Returns — The validated Stage T4800 Throws
  • Error If stage is invalid

isValidStageStatus(status)

Check if a stage status is valid. Signature
Parameters Returns — True if valid status T4800

getStagesByCategory(category)

Get stages by category. Signature
Parameters Returns — Array of stages in that category T4800

getSkippableStages()

Get skippable stages. Signature
Returns — Array of stages that can be skipped T4800

checkTransition(from, to, force)

Check if a transition is allowed. Signature
Parameters Returns — Object with allowed flag and reason T4800

ensureStageArtifact()

Ensure stage artifact exists and frontmatter/backlinks are up to date. Signature

getLifecycleState()

Get the current lifecycle state for an epic. T4467 Signature

startStage()

Start a lifecycle stage. T4467 Signature

completeStage()

Complete a lifecycle stage. T4467 Signature

skipStage()

Skip a lifecycle stage. T4467 Signature

checkGate()

Check lifecycle gate before starting a stage. T4467 Signature

getLifecycleStatus()

Get lifecycle status for an epic from SQLite. Returns stage progress, current/next stage, and blockers. T4801 - SQLite-native implementation Signature

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

getLifecycleGates()

Get all gate statuses for an epic. T4785 Signature

getStagePrerequisites()

Get prerequisites for a target stage. Pure data function, no I/O. T4785 Signature

checkStagePrerequisites()

Check if a stage’s prerequisites are met for an epic. T4785 Signature

recordStageProgress()

Record a stage status transition (progress/record). SQLite-native implementation - T4801 T4785 T4801 Signature

skipStageWithReason()

Skip a stage with a reason (engine-compatible). T4785 Signature

resetStage()

Reset a stage to pending (emergency). T4785 Signature

passGate()

Mark a gate as passed. SQLite-native implementation - T4801 T4785 T4801 Signature

failGate()

Mark a gate as failed. SQLite-native implementation - T4801 T4785 T4801 Signature

listEpicsWithLifecycle()

List all epic IDs that have lifecycle data. T4785 Signature

getCurrentSessionId()

Get the current session ID. Signature

getContextStatePath()

Get context state file path for a session. Signature

readContextState()

Read context state for a session. Returns null if stale or missing. Signature

getThresholdLevel()

Determine the threshold level for a given percentage. Signature

shouldAlert()

Determine if we should alert based on threshold crossing. Returns the alert level if a new threshold was crossed, null otherwise. Signature

getRecommendedAction()

Get recommended action for an alert level. Signature

checkContextAlert()

Main function to check and determine if an alert should fire. Non-blocking - always returns a result. Signature

pushWarning()

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

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

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

formatOutput()

Format any result (success or error) as LAFS JSON. Signature

getRegistryEntry()

Look up a registry entry by CLEO exit code. T4671 T4663 Signature

getRegistryEntryByLafsCode()

Look up a registry entry by LAFS string code. T4671 T4663 Signature

getCleoErrorRegistry()

Get the full CLEO error registry for conformance testing. T4671 T4663 Signature

isCleoRegisteredCode()

Check if a LAFS code is registered in the CLEO error registry. T4671 T4663 Signature

createTestDb()

Create a temporary directory with an initialized tasks.db. Usage: Signature

makeTaskFile()

Build a TaskFile structure from a list of task partials. Useful for seeding test data via accessor.upsertSingleTask(). Signature

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

getChildren()

Get direct children of a task. Signature

getChildIds()

Get direct child IDs. Signature

getDescendants()

Get all descendants of a task (recursive). Signature

getDescendantIds()

Get all descendant IDs (flat list). Signature

getParentChain()

Get the parent chain (ancestors) from a task up to the root. Returns ordered from immediate parent to root. Signature

getParentChainIds()

Get the parent chain as IDs. Signature

getDepth()

Calculate depth of a task in the hierarchy (0-based). Root tasks have depth 0, their children depth 1, etc. Signature

getRootAncestor()

Get the root ancestor of a task. Signature

isAncestorOf()

Check if a task is an ancestor of another. Signature

isDescendantOf()

Check if a task is a descendant of another. Signature

getSiblings()

Get sibling tasks (same parent). Signature

validateHierarchy()

Signature

wouldCreateCircle()

Detect circular reference if parentId were set. Signature

buildTree()

Signature

flattenTree()

Flatten a tree back to a list (depth-first). Signature

resolveHierarchyPolicy()

Resolve a full HierarchyPolicy from config, starting with a profile preset and overriding with any explicitly set config.hierarchy fields. Signature

assertParentExists()

Assert that a parent task exists in the task list. Returns an error result if not found, null if OK. Signature

assertNoCycle()

Assert that re-parenting would not create a cycle. Returns an error result if a cycle is detected, null if OK. Signature

countActiveChildren()

Count active (non-done, non-cancelled, non-archived) children of a parent. Signature

validateHierarchyPlacement()

Validate whether a new task can be placed under the given parent according to the resolved hierarchy policy. Signature

loadConfig()

Load and merge configuration from all sources. Priority: defaults global config project config environment vars Signature

getConfigValue()

Get a single config value with source tracking. Returns the value and which source it came from. Signature

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

getRawConfig()

Get the full raw project config (no cascade). Returns null if no config file exists. T4789 Signature

parseConfigValue()

Parse a string value into its appropriate JS type. Handles booleans, null, integers, floats, and JSON. T4789 Signature

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

validateTitle()

Validate a task title. T4460 Signature

validateStatus()

Validate task status. T4460 Signature

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

validatePriority()

Validate task priority. T4460 T4572 Signature

validateTaskType()

Validate task type. T4460 Signature

validateSize()

Validate task size. T4460 Signature

validateLabels()

Validate label format. T4460 Signature

validatePhaseFormat()

Validate phase slug format. T4460 Signature

validateDepends()

Validate dependency IDs exist. T4460 Signature

validateParent()

Validate parent hierarchy constraints. T4460 Signature

getTaskDepth()

Get the depth of a task in the hierarchy. T4460 Signature

inferTaskType()

Infer task type from parent context. T4460 Signature

getNextPosition()

Get the next position for a task within a parent scope. T4460 Signature

logOperation()

Log an operation to the audit log. T4460 Signature

findRecentDuplicate()

Check for recent duplicate task. T4460 Signature

addTask()

Add a new task to the todo file. T4460 Signature

listPhases()

List all phases with status summaries. T4464 Signature

showPhase()

Show the current phase details. T4464 Signature

setPhase()

Set the current project phase. T4464 Signature

startPhase()

Start a phase (pending - active). T4464 Signature

completePhase()

Complete a phase (active - completed). T4464 Signature

advancePhase()

Advance to the next phase. T4464 Signature

renamePhase()

Rename a phase and update all task references. T4464 Signature

deletePhase()

Delete a phase with optional task reassignment. T4464 Signature

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
Parameters

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

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

validateAgainstSchema()

Validate data against a JSON Schema object. Throws CleoError on validation failure. Signature

validateAgainstSchemaFile()

Load a JSON Schema file and validate data against it. Signature

checkSchema()

Check if data is valid against a schema without throwing. Returns an array of error messages (empty if valid). Signature

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
Parameters 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
Parameters 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
Parameters Returns — Summary of installed, updated, and total schemas

checkGlobalSchemas()

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

checkSchemaStaleness()

Compare global schema versions against bundled package versions. Signature
Returns — Report of stale, current, and missing schemas

listInstalledSchemas()

List all schemas installed in ~/.cleo/schemas/. Signature
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
Parameters 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

checkSchemaIntegrity(cwd)

Check integrity of all active JSON files in a CLEO project. Signature
Parameters

detectProjectType()

Detect project type from directory contents. Returns a schema-compliant ProjectContext object. Signature

BrainDataAccessor

Signature
Methods

addDecision()

getDecision()

findDecisions()

updateDecision()

addPattern()

getPattern()

findPatterns()

updatePattern()

addLearning()

getLearning()

findLearnings()

updateLearning()

addObservation()

getObservation()

findObservations()

updateObservation()

getLinksForMemory()

getLinksForTask()

addStickyNote()

getStickyNote()

findStickyNotes()

updateStickyNote()

deleteStickyNote()

addPageNode()

getPageNode()

findPageNodes()

removePageNode()

addPageEdge()

getPageEdges()

getNeighbors()

removePageEdge()

getBrainAccessor()

Factory: get a BrainDataAccessor backed by the brain.db singleton. Signature

setEmbeddingProvider()

Register an embedding provider for the brain system. Validates that the provider’s dimensions match the vec0 table. Signature
Throws
  • Error if provider dimensions do not match EMBEDDING_DIMENSIONS

getEmbeddingProvider()

Get the currently registered embedding provider, or null. Signature

clearEmbeddingProvider()

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

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

isEmbeddingAvailable()

Check whether embedding is currently available. Signature

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

rebuildFts5Index()

Rebuild FTS5 indexes from the content tables. Useful after bulk inserts that bypass triggers. T5130 Signature

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

resetFts5Cache()

Reset the cached FTS5 availability flag. Used in tests to force re-detection. Signature

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

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

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

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

fileExists()

Check if a file exists and is readable. Signature

stripCLEOBlocks()

Strip legacy !— CLEO:START —…!— CLEO:END — blocks from a file. Called before CAAMP injection to prevent competing blocks. Signature

removeCleoFromRootGitignore()

Remove .cleo/ or .cleo entries from the project root .gitignore. Signature

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

getGitignoreContent()

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

getCleoVersion()

Read CLEO version from package.json. Signature

createDefaultConfig()

Signature

ensureCleoStructure()

Create .cleo/ directory and all required subdirectories. Idempotent: skips directories that already exist. Signature

ensureGitignore()

Create or repair .cleo/.gitignore from template. Idempotent: skips if file already exists with correct content. Signature

ensureConfig()

Create default config.json if missing. Idempotent: skips if file already exists. Signature

ensureProjectInfo()

Create or refresh project-info.json. Idempotent: skips if file already exists (unless force). Signature

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

ensureProjectContext()

Detect and write project-context.json. Idempotent: skips if file exists and is less than staleDays old (default: 30). Signature

ensureCleoGitRepo()

Initialize isolated .cleo/.git checkpoint repository. Idempotent: skips if .cleo/.git already exists. Signature

ensureSqliteDb()

Create SQLite database if missing. Idempotent: skips if tasks.db already exists. Signature

checkCleoStructure()

Verify all required .cleo/ subdirectories exist. Signature

checkGitignore()

Verify .cleo/.gitignore exists and matches template. Signature

checkConfig()

Verify config.json exists and is valid JSON. Signature

checkProjectInfo()

Verify project-info.json exists with required fields. Signature

checkProjectContext()

Verify project-context.json exists and is not stale (default: 30 days). Signature

checkCleoGitRepo()

Verify .cleo/.git checkpoint repository exists. Signature

checkSqliteDb()

Verify .cleo/tasks.db exists and is non-empty. Signature

ensureBrainDb()

Create brain.db if missing. Idempotent: skips if brain.db already exists. Signature

checkBrainDb()

Verify .cleo/brain.db exists and is non-empty. Signature

checkMemoryBridge()

Verify .cleo/memory-bridge.md exists. Warning level if missing (not failure) — it is auto-generated. Signature

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

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

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

checkGlobalHome()

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

checkGlobalTemplates()

Check that the global injection template is present and current. Read-only: no side effects. Signature

checkLogDir()

Check that the project log directory exists. Read-only: no side effects. Signature

getMcpServerName()

Resolve MCP server name by channel. Signature

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

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

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

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

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

recordDecision()

Record a decision to the audit trail. Appends a JSON line to .cleo/audit/decisions.jsonl. Throws if required params are missing. Signature

getDecisionLog()

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

computeHandoff()

Compute handoff data for a session. Gathers all session statistics and auto-computes structured state. Signature

persistHandoff()

Persist handoff data to a session. Signature

getHandoff()

Get handoff data for a session. Signature

getLastHandoff()

Get handoff data for the most recent ended session. Filters by scope if provided. Signature

computeDebrief()

Compute rich debrief data for a session. Builds on computeHandoff() and adds decisions, git state, chain position. T4959 Signature

generateMemoryBridgeContent()

Generate memory bridge content from brain.db. Returns the markdown string (does not write to disk). Signature

writeMemoryBridge()

Write memory bridge content to .cleo/memory-bridge.md. Signature

refreshMemoryBridge()

Best-effort refresh: call from session.end, tasks.complete, or memory.observe. Never throws. Signature

detectLegacyAgentOutputs(projectRoot, cleoDir)

Detect legacy agent-output directories in a project. Read-only check — never modifies the filesystem. Signature
Parameters

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
Parameters

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
Returns — Number of projects migrated.

getNexusHome()

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

getNexusCacheDir()

Get path to the NEXUS cache directory. Signature

getRegistryPath()

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

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

readRegistryRequired()

Read the global registry, throwing if not initialized. Signature

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

nexusRegister()

Register a project in the global registry (nexus.db). Signature
Returns — The project hash.

nexusUnregister()

Unregister a project from the global registry. Signature

nexusList()

List all registered projects. Signature

nexusGetProject()

Get a project by name or hash. Returns null if not found. Signature

nexusProjectExists()

Check if a project exists in the registry. Signature

nexusSync()

Sync project metadata (task count, labels) for a registered project. Signature

nexusSyncAll()

Sync all registered projects. Signature
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

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

analyzeStack()

Signature

analyzeArchitecture()

Signature

analyzeStructure()

Signature

analyzeConventions()

Signature

analyzeTesting()

Signature

analyzeIntegrations()

Signature

analyzeConcerns()

Signature

storePattern()

Store a new pattern. If a similar pattern already exists (same type + matching text), increments frequency. T4768, T5241 Signature

searchPatterns()

Search patterns by criteria. T4768, T5241 Signature

patternStats()

Get pattern statistics. T4768, T5241 Signature

storeLearning()

Store a new learning. T4769, T5241 Signature

searchLearnings()

Search learnings by criteria. Results sorted by confidence (highest first). T4769, T5241 Signature

learningStats()

Get learning statistics. T4769, T5241 Signature

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
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
Parameters 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
Parameters 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
Parameters 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
Parameters Returns — Count of processed and skipped observations

storeMapToBrain()

Signature

mapCodebase()

Signature

isValidAdapter()

Validate that a loaded module export implements the CLEOProviderAdapter interface. Checks for required methods and properties without relying on instanceof. Signature

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

detectProvider()

Detect whether a provider is active in the current environment by checking its detection patterns. Signature

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
Methods

getInstance()

resetInstance()

Reset singleton (for testing).

discover()

Discover adapter manifests from packages/adapters/. Returns manifests found (does not load adapter code yet).

detectActive()

Auto-detect which adapters match the current environment and return their manifest IDs.

activate()

Load and initialize an adapter by manifest ID. Dynamically imports from the manifest’s packagePath — no hardcoded adapters.

getActive()

Get the currently active adapter, or null if none.

getActiveId()

Get the active adapter’s ID, or null.

get()

Get a specific adapter by ID.

getManifest()

Get the manifest for a specific adapter.

listAdapters()

List all known adapters with summary info.

healthCheckAll()

Run health check on all initialized adapters.

healthCheck()

Health check a single adapter.

dispose()

Dispose all initialized adapters.

disposeAdapter()

Dispose a single adapter.

wireAdapterHooks()

Wire an adapter’s hook event map into CLEO’s HookRegistry. Creates bridging handlers at priority 50 for each mapped event.

cleanupAdapterHooks()

Clean up hook registrations for an adapter.

initAgentDefinition()

Install cleo-subagent agent definition to ~/.agents/agents/. T4685 Signature

initMcpServer()

Install MCP server config to all detected providers via CAAMP. T4706 Signature

initCoreSkills()

Install CLEO core skills to the canonical skills directory via CAAMP. T4707 T4689 Signature

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

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
Parameters

updateDocs()

Run update-docs only: refresh all injections without reinitializing. Re-injects CLEO-INJECTION.md into all detected agent instruction files. T4686 Signature

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

isAutoInitEnabled()

Check if auto-init is enabled via environment variable. T4789 Signature

ensureInitialized()

Check if a project is initialized and auto-init if configured. Returns initialized: true if ready, throws otherwise. T4789 Signature

getVersion()

Get the current CLEO/project version. Checks VERSION file, then package.json. T4789 Signature

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

installMcpToProviders()

Install the CLEO MCP server config to all detected providers. Signature

installSkillsGlobally()

Install CLEO core skills globally via CAAMP. Signature

bootstrapCaamp()

Signature

exportTasks()

Export tasks to a portable format. Returns the formatted content and metadata. Signature

importTasks()

Import tasks from an export file. Signature

validateSyntax()

Validate a query string matches expected syntax. Signature

parseQuery()

Parse a query string into its components. Signature
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

resolveProjectPath()

Resolve a project name to its filesystem path. Handles special cases: ”.” (current), ”*” (wildcard marker). Signature

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

getProjectFromQuery()

Extract the project name from a query without full resolution. Useful for permission checks before task lookup. Signature

extractKeywords()

Extract meaningful keywords from text (filters stop words and short tokens). Signature

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

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

permissionLevel()

Convert a permission string to its numeric level. Returns 0 for invalid/unknown permissions. Signature

getPermission()

Get the permission level for a registered project. Returns ‘read’ as default if the project has no explicit permission. Signature

checkPermission()

Check if a project has sufficient permissions (non-throwing). Uses hierarchical comparison: execute = write = read. Signature
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

checkPermissionDetail()

Full permission check returning a structured result. Signature

setPermission()

Set the permission level for a project. Validates the permission value and updates the registry. T4574 Signature

canRead()

Convenience: check read access. Signature

canWrite()

Convenience: check write access. Signature

canExecute()

Convenience: check execute access. Signature

matchesPattern()

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

getSharingStatus()

Get the sharing status: which .cleo/ files are tracked vs ignored. T4883 Signature

syncGitignore()

Sync the project .gitignore to match the sharing config. Adds/updates a managed section between CLEO markers. T4883 Signature

invalidateDepsCache()

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

buildGraph()

Build an adjacency graph from task dependencies. T4464 Signature

getDepsOverview()

Get dependency overview for all tasks. T4464 Signature

getTaskDeps()

Get dependencies for a specific task. T4464 Signature

topologicalSort()

Topological sort of tasks respecting dependencies. Returns tasks in execution order. Throws on cycles. T4464 Signature

getExecutionWaves()

Group tasks into parallelizable execution waves. T4464 Signature

getCriticalPath()

Find the critical path (longest dependency chain) from a task. T4464 Signature

getImpact()

Find all tasks affected by changes to a given task. T4464 Signature

detectCycles()

Detect circular dependencies in the task graph. T4464 Signature

getTaskTree()

Build task hierarchy tree. T4464 Signature

addRelation()

Manage task relationships (relates/blocks). T4464 Signature

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

detectCircularDependencies(tasks, graph)

Detect circular dependencies using DFS traversal. Signature
Parameters 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
Parameters 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
Parameters Returns — Complete dependency analysis

countManifestEntries(projectRoot)

Count manifest entries from MANIFEST.jsonl. Signature
Parameters Returns — Number of manifest entries

estimateContext(taskCount, projectRoot, epicId)

Estimate context usage for orchestration. Signature
Parameters Returns — Context estimation with recommendations

computeWaves()

Compute execution waves using topological sort. Signature

getEnrichedWaves()

Get enriched wave data for an epic. Signature

countByStatus()

Count tasks by status. Signature

computeEpicStatus(epicId, epicTitle, children)

Compute epic-specific status. Signature
Parameters Returns — Epic status with wave information

computeOverallStatus(tasks)

Compute overall orchestration status across all tasks. Signature
Parameters Returns — Overall status with epic count

computeProgress(tasks)

Compute progress metrics for all tasks. Signature
Parameters Returns — Progress metrics with completion percentage

computeStartupSummary(epicId, epicTitle, children, readyCount)

Compute startup summary for an epic. Signature
Parameters Returns — Startup summary with wave information

startOrchestration()

Start an orchestrator session for an epic. T4466 Signature

analyzeEpic()

Analyze an epic’s dependency structure. T4466 Signature

getReadyTasks()

Get parallel-safe ready tasks for an epic. T4466 Signature

getNextTask()

Get the next task to work on for an epic. T4466 Signature

prepareSpawn()

Prepare a spawn context for a subagent. T4466 Signature

validateSpawnOutput()

Validate a subagent’s output. T4466 Signature

getOrchestratorContext()

Get orchestrator context summary. T4466 Signature

autoDispatch()

Auto-dispatch: determine the protocol for a task based on metadata. T4466 Signature

resolveTokens()

Resolve tokens in a prompt string. T4466 Signature

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
Parameters

storeDecision()

Store a new decision or update an existing one if a duplicate is found. Duplicate detection: same decision text (case-insensitive). T5155 Signature

recallDecision()

Recall a specific decision by ID. T5155 Signature

searchDecisions()

Search decisions by type, confidence, outcome, and/or free-text query. Query searches across decision + rationale fields using LIKE. T5155 Signature

listDecisions()

List decisions with pagination. T5155 Signature

updateDecisionOutcome()

Update the outcome of a decision after learning from results. T5155 Signature

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

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

resolveTaskDetails()

Resolve an array of task IDs to their full Task objects. Tasks that cannot be found are silently excluded. Signature

completeTask()

Complete a task by ID. Handles dependency checking and optional auto-completion of epics. T4461 Signature

updateTask()

Update a task’s fields. T4461 Signature

getLinksByProvider()

Find all links for a given provider. Signature

getLinkByExternalId()

Find a link by provider + external ID. Signature

getLinksByTaskId()

Find all links for a given CLEO task. Signature
Create a new external task link. Signature
Update the lastSyncAt and optionally the title/metadata for an existing link. Signature

removeLinksByProvider()

Remove all links for a provider (used during provider deregistration). Signature

reconcile(externalTasks, options, accessor)

Reconcile external task state with CLEO’s authoritative task store. Signature
Parameters Returns — Reconciliation result with actions taken.

getArtifactHandler()

Get handler for an artifact type. T4552 Signature

hasArtifactHandler()

Check if a handler is registered for an artifact type. T4552 Signature

buildArtifact()

Build an artifact using the appropriate handler. T4552 Signature

validateArtifact()

Validate an artifact using the appropriate handler. T4552 Signature

publishArtifact()

Publish an artifact using the appropriate handler. T4552 Signature

getSupportedArtifactTypes()

Get all supported artifact types. T4552 Signature

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

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

loadReleaseConfig()

Load release configuration with defaults. Signature

validateReleaseConfig()

Validate release configuration. Signature

getArtifactType()

Get artifact type from config. Signature

getReleaseGates()

Get release gates from config. Signature

getChangelogConfig()

Get changelog configuration. Signature

getDefaultGitFlowConfig()

Return the default GitFlow branch configuration. Signature

getGitFlowConfig()

Merge caller-supplied GitFlow config with defaults. Signature

getDefaultChannelConfig()

Return the default channel configuration. Signature

getChannelConfig()

Merge caller-supplied channel config with defaults. Signature

getPushMode()

Return the configured push mode, defaulting to ‘auto’. Signature

getDefaultChannelConfig()

Return the default branch-to-channel mapping. Signature

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

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

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

describeChannel()

Return a human-readable description of the given release channel. Signature

getPlatformPath()

Get the output path for a CI platform. Signature

detectCIPlatform()

Detect the CI platform from the project. Signature

generateCIConfig()

Generate CI config for a platform. Signature

writeCIConfig()

Write CI config to the appropriate path. Signature

validateCIConfig()

Validate an existing CI config. Signature

isGhCliAvailable()

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

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

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

buildPRBody()

Build the markdown body for a GitHub pull request. Signature

formatManualPRInstructions()

Format human-readable instructions for creating a PR manually. Signature

createPullRequest()

Create a GitHub pull request using the gh CLI, or return manual instructions if the CLI is unavailable or the operation fails. Signature

checkEpicCompleteness()

Check epic completeness for a set of release task IDs. Verifies all children of each referenced epic are included. Signature

checkDoubleListing()

Check if any tasks are listed in multiple releases. Signature

validateVersionFormat()

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

isCalVer()

Check if a version string is CalVer format. Signature

calculateNewVersion()

Calculate new version from current + bump type. Signature

getVersionBumpConfig()

Get version bump configuration, mapping config field names to VersionBumpTarget. Signature

isVersionBumpConfigured()

Check if version bump is configured. Signature

bumpVersionFromConfig()

Bump version in all configured files. Signature

prepareRelease()

Prepare a release (create a release manifest entry). T4788 Signature

generateReleaseChangelog()

Generate changelog for a release. T4788 Signature

listManifestReleases()

List all releases. T4788 Signature

showManifestRelease()

Show release details. T4788 Signature

commitRelease()

Mark release as committed (metadata only). T4788 Signature

tagRelease()

Mark release as tagged (metadata only). T4788 Signature

runReleaseGates()

Run release validation gates. T4788 T5586 Signature

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

rollbackRelease()

Rollback a release. T4788 Signature

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

markReleasePushed()

Update release status after push, with optional provenance fields. T4788 T5580 Signature

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

gradeSession()

Grade a session by sessionId using the 5-dimension behavioral rubric. Signature

readGrades()

Read past grade results from .cleo/metrics/GRADES.jsonl Signature

handleSessionStart()

Handle onSessionStart - capture initial session context Signature

handleSessionEnd()

Handle onSessionEnd - capture session summary Signature

handleToolStart()

Handle onToolStart (maps to task.start in CLEO) Signature

handleToolComplete()

Handle onToolComplete (maps to task.complete in CLEO) Signature

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

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

handlePromptSubmit()

Handle onPromptSubmit - optionally capture prompt events to BRAIN No-op by default. Set CLEO_BRAIN_CAPTURE_MCP=true to enable. Signature

handleResponseComplete()

Handle onResponseComplete - optionally capture response events to BRAIN No-op by default. Set CLEO_BRAIN_CAPTURE_MCP=true to enable. Signature

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

linkMemoryToTask()

Link a memory entry to a task. T5156 Signature

unlinkMemoryFromTask()

Remove a link between a memory entry and a task. T5156 Signature
Get all memory entries linked to a specific task. T5156 Signature
Get all tasks linked to a specific memory entry. T5156 Signature
Batch create multiple links at once. T5156 Signature

getLinkedDecisions()

Get all decisions linked to a task. Convenience method that fetches full decision rows. T5156 Signature

getLinkedPatterns()

Get all patterns linked to a task. Convenience method that fetches full pattern rows. T5156 Signature

getLinkedLearnings()

Get all learnings linked to a task. Convenience method that fetches full learning rows. T5156 Signature

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

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
Parameters 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
Parameters Returns — Relevant brain memory entries

depsReady(depends, taskLookup)

Check if all dependencies of a task are satisfied. Signature
Parameters 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

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

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

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

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

showSession()

Show a specific session. Looks in active sessions first, then session history. Throws CleoError if not found. Signature

getSessionStats()

Compute session statistics, optionally for a specific session. Throws CleoError if a specific session is requested but not found. Signature

suspendSession()

Suspend an active session. Sets status to ‘suspended’ and records the reason. Throws if session not found or not active. Signature

switchSession()

Switch to a different session. Suspends the current active session and activates the target. Throws if session not found or archived. Signature

SessionView

Signature
Methods

from()

Create a SessionView from a Session array.

findActive()

Find the currently active session (if any).

findById()

Find a session by ID.

filterByStatus()

Filter sessions by one or more statuses.

findByScope()

Find sessions matching a scope type and optional rootTaskId.

sortByDate()

Sort sessions by a date field. Returns a new array (does not mutate).

mostRecent()

Get the most recently started session.

toArray()

Convert back to a plain Session array (shallow copy).

Symbol.iterator

Support for-of iteration.

selectRuntimeProviderContext()

Signature

detectRuntimeProviderContext()

Signature

resetRuntimeProviderContextCache()

Signature

parseScope()

Parse a scope string into a SessionScope. T4463 Signature

readSessions()

Read sessions from accessor or JSON file. T4463 Signature

saveSessions()

Save sessions via accessor or JSON file. T4463 Signature

startSession()

Start a new session. T4463 Signature

endSession()

End a session. T4463 Signature

sessionStatus()

Get current session status. T4463 Signature

resumeSession()

Resume an existing session. T4463 Signature

listSessions()

List sessions with optional filtering. T4463 Signature

gcSessions()

Garbage collect old sessions. Marks orphaned sessions that have been active too long. T4463 Signature

archiveSticky(id, projectRoot)

Archive a sticky note. Signature
Parameters Returns — The archived sticky note or null if not found

convertStickyToTask(stickyId, taskTitle, projectRoot)

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

convertStickyToMemory(stickyId, memoryType, projectRoot)

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

convertStickyToTaskNote(stickyId, taskId, projectRoot)

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

convertStickyToSessionNote(stickyId, sessionId, projectRoot)

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

generateStickyId(projectRoot)

Generate the next sticky note ID. Finds the highest existing SN-XXX ID and increments. Signature
Parameters Returns — Next sticky note ID (e.g., “SN-042”)

addSticky(params, projectRoot)

Create a new sticky note. Signature
Parameters Returns — The created sticky note

listStickies(params, projectRoot)

List sticky notes with optional filters. Signature
Parameters Returns — Array of sticky notes

purgeSticky(id, projectRoot)

Purge (permanently delete) a sticky note. Signature
Parameters Returns — The deleted sticky note or null if not found

getSticky(id, projectRoot)

Get a sticky note by ID. Signature
Parameters 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

deleteTask()

Delete a task (soft delete - moves to archive). T4461 Signature

Cleo

Signature
Methods

init()

forProject()

calculateExportChecksum()

Calculate SHA-256 checksum for export integrity (truncated to 16 hex chars). Signature

verifyExportChecksum()

Verify export package checksum. Signature

buildIdMap()

Build ID map from tasks. Signature

buildRelationshipGraph()

Build relationship graph from tasks. Signature

buildExportPackage()

Build a complete export package. Signature

exportSingle()

Export a single task. Signature

exportSubtree()

Export a subtree (task + all descendants). Signature

exportTasksPackage()

Export tasks to a portable cross-project package. Signature

getCostHint()

Determine cost hint for an operation based on domain and operation name. Signature

groupOperationsByDomain(ops)

Group operations by domain into a compact format. Signature
Parameters Returns — Domain-grouped operations with query and mutate arrays

buildVerboseOperations(ops)

Build verbose operation entries with cost hints. Signature
Parameters 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
Parameters Returns — The computed help result

getNextAvailableId()

Get the next available task ID number from existing tasks. Signature

generateRemapTable()

Generate a remap table for importing tasks. Maps source task IDs to new sequential IDs starting from nextAvailable. Signature

validateRemapTable()

Validate that a remap table is complete and consistent. Signature

remapTaskId()

Remap a single task ID, returning original if not in table. Signature

remapTaskReferences()

Remap all ID references in a task. Signature

detectDuplicateTitles()

Detect duplicate titles between import and target. Signature

resolveDuplicateTitle()

Resolve duplicate title by appending suffix. Signature

importTasksPackage()

Import tasks from a cross-project export package with ID remapping. Signature

findAdrs()

Signature

listAdrs()

List ADRs from .cleo/adrs/ directory with optional status filter Signature

showAdr()

Retrieve a single ADR by ID (e.g., ‘ADR-007’) Signature

validateAllAdrs()

Validate all ADRs in .cleo/adrs/ against the schema Signature

providerList()

List all registered providers. T4332 Signature

providerGet()

Get a single provider by ID or alias. T4332 Signature

providerDetect()

Detect all providers installed on the system. T4332 Signature

providerInstalled()

Get providers that are installed on the system. T4332 Signature

providerCount()

Get count of registered providers. T4332 Signature

registryVersion()

Get CAAMP registry version. T4332 Signature

mcpList()

List MCP servers for a specific provider. T4332 Signature

mcpListAll()

List MCP servers across all installed providers. T4332 Signature

mcpInstall()

Install an MCP server to a provider’s config. T4332 Signature

mcpRemove()

Remove an MCP server from a provider’s config. T4332 Signature

mcpConfigPath()

Resolve the config file path for a provider. T4332 Signature

injectionCheck()

Check injection status for a single file. T4332 Signature

injectionCheckAll()

Check injection status across all providers. T4332 Signature

injectionUpdate()

Inject or update content in a single file. T4332 Signature

injectionUpdateAll()

Inject content to all providers’ instruction files. T4332 Signature

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

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

checkProviderCapability(provider, capabilityPath)

Check if provider supports a specific capability Signature
Parameters 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

getComplianceJsonlPath()

Resolve COMPLIANCE.jsonl path for a project root. Signature

readComplianceJsonl()

Read COMPLIANCE.jsonl entries. Invalid JSON lines are skipped to preserve append-only log resilience. Signature

appendComplianceJsonl()

Append one entry to COMPLIANCE.jsonl, creating directories as needed. Signature

getComplianceSummary()

Get compliance summary. Signature

listComplianceViolations()

List compliance violations. Signature

getComplianceTrend()

Get compliance trend. Signature

auditEpicCompliance()

Audit epic compliance. Signature

syncComplianceMetrics()

Sync compliance metrics to a summary file. Signature

getSkillReliability()

Get skill reliability stats. Signature

getValueMetrics()

Get value metrics (T2833). Signature

getContextStatus()

Get context status. Signature

checkContextThreshold()

Check context threshold (returns exit code info). Signature

listContextSessions()

List all context state files. Signature

injectTasks()

Inject tasks for external consumption. Signature

collectDiagnostics()

Collect system diagnostics for bug reports. Signature

formatDiagnosticsTable()

Format diagnostics as markdown table. Signature

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

getTemplateConfig()

Get template configuration - tries live parse, cache, then fallback. Signature

getTemplateForSubcommand()

Get the template for a specific subcommand (bug, feature, etc.). Signature

cacheTemplates()

Cache parsed templates to .cleo/issue-templates.json. Signature

validateLabelsExist()

Validate that required labels exist (informational). Signature

buildIssueBody()

Build structured issue body with template sections. Signature

checkGhCli()

Check that gh CLI is installed and authenticated. Signature

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

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

addResearch()

Add a research entry. T4465 Signature

showResearch()

Show a specific research entry. T4465 Signature

listResearch()

List research entries with optional filtering. T4465 Signature

pendingResearch()

List pending research entries. T4465 Signature

linkResearch()

Link a research entry to a task. T4465 Signature

updateResearch()

Update research findings. T4465 Signature

statsResearch()

Get research statistics. T4474 Signature

linksResearch()

Get research entries linked to a specific task. T4474 Signature

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

readManifest()

Read manifest entries from MANIFEST.jsonl. T4465 Signature

appendManifest()

Append a manifest entry. T4465 Signature

queryManifest()

Query manifest entries. T4465 Signature

readExtendedManifest()

Read all manifest entries as extended entries. T4787 Signature

filterManifestEntries()

Filter manifest entries by criteria. T4787 Signature

showManifestEntry()

Show a manifest entry by ID with optional file content. T4787 Signature

searchManifest()

Search manifest entries by text with relevance scoring. T4787 Signature

pendingManifestEntries()

Get pending manifest entries (partial, blocked, or needing followup). T4787 Signature

manifestStats()

Get manifest-based research statistics. T4787 Signature

linkManifestEntry()

Link a manifest entry to a task (adds taskId to linked_tasks array). T4787 Signature

appendExtendedManifest()

Append an extended manifest entry. Validates required fields before appending. T4787 Signature

archiveManifestEntries()

Archive manifest entries older than a date. T4787 Signature

findContradictions()

Find manifest entries with overlapping topics but conflicting key_findings. T4787 Signature

findSuperseded()

Identify research entries replaced by newer work on same topic. T4787 Signature

readProtocolInjection()

Read protocol injection content for a given protocol type. T4787 Signature

compactManifest()

Compact MANIFEST.jsonl by removing duplicate/stale entries. T4787 Signature

validateManifestEntries()

Validate research entries for a task. T4787 Signature

ensureMetricsDir()

Ensure metrics directory exists, returning its path. Signature

getCompliancePath()

Get compliance log path. Signature

getViolationsPath()

Get violations log path. Signature

getSessionsMetricsPath()

Get sessions metrics log path. Signature

isoTimestamp()

Generate ISO 8601 UTC timestamp. Signature

isoDate()

Generate ISO 8601 date only. Signature

readJsonlFile()

Read a JSONL file into an array of parsed objects. Signature

getComplianceSummaryBase()

Get compliance summary from log file. Signature

isOtelEnabled()

Check if OTel telemetry is enabled. Signature

getOtelSetupCommands()

Get environment variable commands for OTel capture setup. Signature

parseTokenMetrics()

Parse OTel token metrics from collected data. Signature

getSessionTokens()

Get aggregated token counts from OTel data. Signature

recordSessionStart()

Record token counts at session start. Signature

recordSessionEnd()

Record token counts at session end. Signature

compareSessions()

Compare token usage between two sessions. Signature

getTokenStats()

Get statistics about token usage across sessions. Signature

logABEvent()

Log an A/B test event. Signature

startABTest()

Start an A/B test session. Signature

endABTest()

End an A/B test session with summary. Signature

getABTestResults()

Get results for a specific test variant. Signature

listABTests()

List all A/B tests. Signature

compareABTest()

Compare two variants of the same test. Signature

getABTestStats()

Get aggregate statistics of all A/B tests. Signature

syncMetricsToGlobal()

Sync project metrics to global aggregation file. Signature

getProjectComplianceSummary()

Get compliance summary for the current project. Signature

getGlobalComplianceSummary()

Get compliance summary across all projects. Signature

getComplianceTrend()

Get compliance trend over time. Signature

getSkillReliability()

Get reliability stats per skill/agent. Signature

logSessionMetrics()

Log session metrics to SESSIONS.jsonl. Signature

getSessionMetricsSummary()

Get summary of session metrics. Signature

isValidEnumValue()

Validate that a value is a member of a given enum. Signature

estimateTokens()

Estimate token count from text. ~4 characters per token. Signature

estimateTokensFromFile()

Estimate token count from a file. Signature

logTokenEvent()

Log a token usage event to the JSONL file. Signature

trackFileRead()

Track a file read with token estimate. Signature

trackManifestQuery()

Track a manifest query (partial read). Signature

trackSkillInjection()

Track skill injection with tokens. Signature

trackPromptBuild()

Track final prompt size. Signature

trackSpawnOutput()

Track subagent output tokens. Signature

trackSpawnComplete()

Track complete spawn cycle (prompt + output). Signature

startTokenSession()

Start tracking tokens for a session. Signature

endTokenSession()

End token tracking session with summary. Signature

getTokenSummary()

Get token usage summary for a time period. Signature

compareManifestVsFull()

Compare manifest vs full file token usage strategies. Signature

getTrackingStatus()

Get tracking status. Signature

computeChecksum(filePath)

Compute SHA-256 checksum of a file. Signature
Parameters 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
Parameters 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
Parameters Returns — true if checksums match, false otherwise T4728

MigrationLogger

Structured logger for migration operations Signature
Methods

getLevelPriority()

Get numeric priority for log level comparison.

shouldLog()

Check if a log level should be recorded.

log()

Write a log entry.

info()

Log an info-level message.

warn()

Log a warning-level message.

error()

Log an error-level message.

debug()

Log a debug-level message.

logFileOperation()

Log file operation with size information.

logValidation()

Log validation result.

logImportProgress()

Log import progress.

phaseStart()

Log phase start.

phaseComplete()

Log phase completion.

phaseFailed()

Log phase failure.

cleanupOldLogs()

Clean up old log files, keeping only the most recent ones.

getLogPath()

Get the absolute path to the log file.

getRelativeLogPath()

Get the path to the log file relative to cleoDir.

getEntries()

Get all logged entries.

getEntriesByLevel()

Get entries filtered by level.

getEntriesByPhase()

Get entries for a specific phase.

getDurationMs()

Get the total duration of the migration so far.

getSummary()

Get summary statistics for the migration.

createMigrationLogger()

Create a migration logger for the given cleo directory. Convenience function for functional programming style. Signature

readMigrationLog()

Read and parse a migration log file. Signature

logFileExists()

Check if a log file exists and is readable. Signature

getLatestMigrationLog()

Get the most recent migration log file for a cleo directory. Signature

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

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
Parameters 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
Parameters Returns — The updated migration state T4726

updateMigrationPhase(cleoDir, phase)

Update just the migration phase. Convenience wrapper for common phase transition. Signature
Parameters Returns — The updated migration state T4726

updateMigrationProgress(cleoDir, progress)

Update progress counters during import. Signature
Parameters Returns — The updated migration state T4726

addMigrationError(cleoDir, error)

Add an error to the migration state. Signature
Parameters Returns — The updated migration state T4726

addMigrationWarning(cleoDir, warning)

Add a warning to the migration state. Signature
Parameters Returns — The updated migration state T4726

loadMigrationState(cleoDir)

Load existing migration state. Signature
Parameters Returns — Migration state, or null if no state file exists T4726

isMigrationInProgress(cleoDir)

Check if a migration is in progress. Signature
Parameters Returns — true if migration state exists and is not complete/failed T4726

canResumeMigration(cleoDir)

Check if migration can be resumed. Signature
Parameters Returns — Object with resume info, or null if cannot resume T4726

completeMigration(cleoDir)

Mark migration as complete. Signature
Parameters Returns — The completed migration state T4726

failMigration(cleoDir, error)

Mark migration as failed with error details. Signature
Parameters Returns — The failed migration state T4726

clearMigrationState(cleoDir)

Clear migration state file. Safe to call even if state doesn’t exist. Signature
Parameters

getMigrationSummary(cleoDir)

Get a summary of migration state for display. Signature
Parameters 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
Parameters 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
Parameters Returns — Validation result with details for each file T4725

formatValidationResult(result)

Format validation result for human-readable output. Signature
Parameters 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
Parameters Returns — Warning message if mismatch detected, null otherwise

detectVersion()

Detect schema version from a data file. T4468 Signature

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

getMigrationStatus()

Get migration status for all data files. T4468 Signature

runMigration()

Run migrations on a data file. T4468 Signature

runAllMigrations()

Run all pending migrations. T4468 Signature

invalidateGraphCache()

Invalidate the in-memory graph cache. Signature

buildGlobalGraph()

Build the global dependency graph from all registered projects. Uses checksum-based caching to avoid unnecessary rebuilds. Signature

nexusDeps()

Show dependencies for a task across projects. Supports forward (what this depends on) and reverse (what depends on this) lookups. Signature

resolveCrossDeps()

Resolve an array of dependencies (local or cross-project). Signature

criticalPath()

Calculate the critical path across project boundaries. Returns the longest dependency chain in the global graph. Signature

blockingAnalysis()

Analyze the blocking impact of a task across all projects. Uses BFS to find all direct and transitive dependents. Signature

orphanDetection()

Detect orphaned cross-project dependencies. Finds tasks with dependency references to projects or tasks that don’t exist. Signature

compareLevels()

Compare two pino levels numerically. Returns negative if a b, 0 if equal, positive if a b. Signature

matchesFilter()

Check if a single entry matches the filter criteria. All specified fields must match (AND logic). Signature

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

paginate()

Apply pagination (limit/offset) to a result set. Signature

isValidLevel()

Validate that a string is a valid PinoLevel. Signature

parseLogLine()

Parse a single JSONL line into a PinoLogEntry. Returns null for empty lines, non-JSON, or lines missing required fields. Signature

parseLogLines()

Parse multiple JSONL lines into PinoLogEntry array. Skips malformed lines. Signature

getProjectLogDir()

Get the project log directory path. Uses getLogDir() from logger if available, falls back to config-based resolution. Signature

getGlobalLogDir()

Get the global log directory path (~/.cleo/logs/). Signature

discoverLogFiles()

Discover all log files in the specified scope. Returns file info sorted by date (newest first). Signature

readLogFileLines()

Read all lines from a log file synchronously. Returns raw JSON strings (one per line). Suitable for small-to-medium files. Signature

streamLogFileLines()

Create an async iterable over lines of a log file. Suitable for large files — does not load entire file into memory. Signature

queryLogs()

High-level query: discover files, parse, filter, paginate. Convenience wrapper combining all three layers. Signature

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

getLogSummary()

Get a summary of log activity (counts by level, date range, subsystems). Reads all discovered files but does not return individual entries. Signature

getOtelStatus()

Get token tracking status. Signature

getOtelSummary()

Get combined token usage summary. Signature

getOtelSessions()

Get session-level token data. Signature

getOtelSpawns()

Get spawn-level token data. Signature

getRealTokenUsage()

Get real token usage from Claude Code API. Signature

clearOtelData()

Clear token tracking data with backup. Signature

listPhases()

List all phases with status summaries. T5326 Signature

showPhase()

Show phase details by slug or current phase. T5326 Signature

getCurrentBranch()

Get the current branch name in .cleo/.git. T4884 Signature

addRemote()

Add a git remote to .cleo/.git. T4884 Signature

removeRemote()

Remove a git remote from .cleo/.git. T4884 Signature

listRemotes()

List configured remotes in .cleo/.git. T4884 Signature

push()

Push .cleo/.git to a remote. T4884 Signature

pull()

Pull from a remote into .cleo/.git. Uses rebase strategy to maintain clean history. T4884 Signature

getSyncStatus()

Get the sync status between local .cleo/.git and remote. T4884 Signature

getRoadmap()

Get roadmap from pending epics and CHANGELOG history. Signature

getOperationMode()

Lookup the execution mode for a specific operation Signature

canRunNatively()

Check if an operation can run natively (without CLI) Signature

requiresCLI()

Check if an operation requires CLI Signature

getNativeOperations()

Get all native-capable operations for a domain Signature

generateCapabilityReport()

Generate a capability report for system.doctor Signature

getCapabilityMatrix()

Get the full capability matrix (for testing/introspection) Signature

findHighestId()

Find the highest existing task ID number Signature

generateNextIdFromSet()

Generate the next ID given an explicit set of existing IDs. Useful when caller has already loaded task data. Signature

isValidTaskId()

Validate that a task ID matches the expected format Signature

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

SecurityError

Security validation error thrown when input fails sanitization Signature

sanitizeTaskId()

Sanitize and validate a task ID Signature

sanitizePath()

Sanitize and validate a file path Signature

sanitizeContent()

Sanitize content string Signature

validateEnum()

Validate that a value is in an allowed enum set Signature

RateLimiter

In-memory sliding window rate limiter Signature
Methods

check()

record()

consume()

reset()

getConfig()

setConfig()

ensureArray()

Normalize a value to an array of strings. Handles MCP clients sending comma-separated strings where arrays are expected. Signature

sanitizeParams()

Sanitize all params in a request before routing Signature

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
Methods

register()

deregister()

send()

poll()

heartbeat()

createConversation()

getAgent()

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
Methods

register()

deregister()

send()

poll()

heartbeat()

createConversation()

getAgent()

request()

Make an HTTP request to the SignalDock API.

createTransport()

Create an AgentTransport instance based on configuration. Returns SignalDockTransport if signaldock is enabled, otherwise returns ClaudeCodeTransport as the default. Signature

getSkillSearchPaths()

Build the CAAMP skill search paths in priority order. Uses CAAMP’s canonical path functions for standard locations. T4516 Signature

getSkillsDir()

Get the primary skills directory (app-embedded). T4516 Signature

getSharedDir()

Get the shared skills resources directory. T4516 Signature

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

listCanonicalSkillNames()

List all known canonical skill names (unique values from the map). T4516 Signature

parseFrontmatter()

Parse YAML-like frontmatter from a SKILL.md file. Handles the --- delimited header with key: value pairs. T4516 Signature

discoverSkill()

Discover a single skill from a directory. Tries CAAMP’s parseSkillFile first, falls back to local parsing. T4516 Signature

discoverSkillsInDir()

Discover all skills in a single directory. Scans for subdirectories containing SKILL.md. T4516 Signature

discoverAllSkills()

Discover all skills across CAAMP search paths. Returns skills in priority order (earlier paths take precedence). T4516 Signature

findSkill()

Find a specific skill by name across all search paths. T4516 Signature

toSkillSummary()

Convert a Skill to a lightweight SkillSummary. T4516 Signature

generateManifest()

Generate a skill manifest from discovered skills. T4516 Signature

resolveTemplatePath()

Resolve a skill template path (SKILL.md) by name. T4516 Signature

getAgentsDir()

Get the agents directory path. T4518 Signature

parseAgentConfig()

Parse an AGENT.md file into an AgentConfig. AGENT.md uses the same YAML frontmatter format as SKILL.md. T4518 Signature

loadAgentConfig()

Load agent configuration by name. Searches in the agents/ directory. T4518 Signature

getSubagentConfig()

Get the cleo-subagent configuration (universal executor). T4518 Signature

agentExists()

Check if an agent definition exists. T4518 Signature

installAgent()

Install a single agent via symlink. T4518 Signature

installAllAgents()

Install all agents from the project agents/ directory. T4518 Signature

uninstallAgent()

Uninstall a single agent by removing its symlink. T4518 Signature

getRegistryPath()

Get the agent registry file path. T4518 Signature

readRegistry()

Read the agent registry, creating if needed. T4518 Signature

saveRegistry()

Save the agent registry. T4518 Signature

registerAgent()

Register an agent in the registry. T4518 Signature

unregisterAgent()

Unregister an agent from the registry. T4518 Signature

getAgent()

Get an agent from the registry by name. T4518 Signature

listAgents()

List all registered agents. T4518 Signature

syncRegistry()

Scan the agents/ directory and register all found agents. T4518 Signature

loadPlaceholders()

Load token definitions from placeholders.json. T4521 Signature

buildDefaults()

Build the full default values map (merging placeholders.json with hardcoded defaults). T4521 Signature

validateTokenValue()

Validate a single token value against its pattern. T4521 Signature

validateRequired()

Validate all required tokens are present and valid. T4521 Signature

validateAllTokens()

Validate all tokens in a values map (required + optional). T4521 Signature

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

hasUnresolvedTokens()

Check if a template has unresolved tokens after injection. T4521 Signature

loadAndInject()

Load a skill template and inject tokens. T4521 Signature

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

autoDispatch()

Auto-dispatch a task to the most appropriate skill. Tries strategies in priority order: label - catalog - type - keyword - fallback. T4517 Signature

dispatchExplicit()

Dispatch with explicit skill override. Verifies the skill exists before returning. T4517 Signature

getProtocolForDispatch()

Get the protocol type for a dispatch result. T4517 Signature

prepareSpawnContext()

Prepare spawn context for a dispatched skill. Returns the skill name and protocol needed for token injection. T4517 Signature

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

loadProtocolBase()

Load the subagent protocol base content. T4521 Signature

buildTaskContext()

Build task context block for injection into a subagent prompt. T4521 Signature

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

injectProtocol()

Inject the subagent protocol into skill content. Composes: skill content + protocol base + task context. T4521 Signature

orchestratorSpawnSkill()

Full orchestrator spawn workflow (skill-based). High-level function that loads the skill, injects protocol, and returns the prompt. T4521 Signature

prepareTokenValues()

Prepare standard token values for a task spawn. T4521 Signature

installSkill()

Install a single skill via CAAMP. Signature

generateContributionId()

Generate a unique contribution ID. T4520 Signature

validateContributionTask()

Validate that a task is suitable for contribution protocol. T4520 Signature

getContributionInjection()

Generate the contribution injection block for a subagent prompt. T4520 Signature

detectConflicts()

Detect conflicts between two sets of decisions. T4520 Signature

computeConsensus()

Compute weighted consensus from multiple agent decisions. T4520 Signature

createContributionManifestEntry()

Create a manifest entry for a contribution. T4520 Signature

ensureOutputs()

Ensure agent outputs directory and manifest file exist. T4520 Signature

readManifest()

Read all manifest entries. T4520 Signature

appendManifest()

Append a manifest entry (atomic JSONL append). T4520 Signature

findEntry()

Find a manifest entry by ID. T4520 Signature

filterEntries()

Filter manifest entries by criteria. T4520 Signature

getPendingFollowup()

Get entries with pending follow-ups. T4520 Signature

getFollowupTaskIds()

Get unique follow-up task IDs from all manifest entries. T4520 Signature

taskHasResearch()

Check if a task has linked research. T4520 Signature

archiveEntry()

Archive a manifest entry (move to archive status). T4520 Signature

rotateManifest()

Rotate manifest by archiving old entries. T4520 Signature

isCacheFresh()

Check if the cached manifest is fresh (within TTL). T4520 Signature

invalidateCache()

Invalidate the cache (delete the cached manifest). T4520 Signature

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

regenerateCache()

Force regenerate the cache. T4520 Signature

loadConfig()

Load SkillsMP configuration from skillsmp.json. T4521 Signature

searchSkills()

Search the skills marketplace. Delegates to CAAMP’s searchSkills for the actual API call. T4521 Signature

getSkill()

Get a specific skill from the marketplace. Uses CAAMP’s MarketplaceClient for retrieval. T4521 Signature

isEnabled()

Check if the marketplace is enabled and reachable. T4521 Signature

buildPrompt()

Build a fully-resolved prompt for spawning a subagent. T4519 Signature

spawn()

Generate full spawn command with metadata. T4519 Signature

canParallelize()

Check if tasks can be spawned in parallel (no inter-dependencies). T4519 Signature

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

getThresholds()

Get orchestrator context thresholds from config or defaults. T4519 Signature

getContextState()

Read the current context state from session-aware files. T4519 Signature

sessionInit()

Initialize orchestrator session state. Determines the recommended action based on current state. T4519 Signature

shouldPause()

Check if orchestrator should pause based on context usage. T4519 Signature

analyzeDependencies()

Analyze dependency graph and compute execution waves. T4519 Signature

getNextTask()

Get the next task ready to spawn for an epic. T4519 Signature

getReadyTasks()

Get all tasks ready to spawn in parallel (no inter-dependencies). T4519 Signature

generateHitlSummary()

Generate a Human-in-the-Loop summary for session handoff. T4519 Signature

validateSubagentOutput()

Validate a subagent’s manifest entry for protocol compliance. T4519 Signature

validateManifestIntegrity()

Validate the entire manifest file integrity. T4519 Signature

verifyCompliance()

Verify previous agent completed protocol compliance before spawning next. T4519 Signature

validateOrchestratorCompliance()

Validate orchestrator compliance (post-hoc behavioral checks). T4519 Signature

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

resolveSkillPath()

Resolve a skill directory containing SKILL.md. Searches all paths from getSkillSearchPaths() in priority order. First match wins. T4552 Signature

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

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

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

formatIsoDate(inputDate)

Format a date string in ISO 8601 format. Converts a YYYY-MM-DD date string to a full ISO 8601 timestamp. Signature
Parameters 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
Returns — Current timestamp (e.g., “2026-02-16T14:30:00Z”) T4552

isValidIsoDate()

Validate that a string is a valid ISO 8601 date. T4552 Signature

formatDateYMD()

Format a Date object to a YYYY-MM-DD string. T4552 Signature

validateSkill()

Validate a skill directory structure and content. T4517 Signature

validateSkills()

Validate multiple skills at once. T4517 Signature

validateReturnMessage()

Validate a return message against protocol-compliant patterns. T4517 Signature

getInstalledVersionAsync()

Get the installed version of a skill from CAAMP lock state. Signature

checkSkillUpdateAsync()

Check if a specific skill needs an update via CAAMP. Signature

checkAllSkillUpdatesAsync()

Check all installed skills for available updates via CAAMP. Signature

exportSnapshot()

Export current task state to a snapshot. T4882 Signature

writeSnapshot()

Write a snapshot to a file. T4882 Signature

readSnapshot()

Read a snapshot from a file. T4882 Signature

getDefaultSnapshotPath()

Generate a default snapshot file path. T4882 Signature

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

SpawnAdapterRegistry

Registry to manage spawn adapters. Maintains mappings between adapter IDs, provider IDs, and adapter instances. Supports registration, lookup, and capability-based filtering. Signature
Methods

register()

Register an adapter with the registry.

get()

Get an adapter by its unique ID.

getForProvider()

Get the adapter registered for a specific provider.

hasAdapterForProvider()

Check if an adapter is registered for a given provider.

list()

List all registered adapters.

listSpawnCapable()

List adapters for providers that have spawn capability. Queries CAAMP for spawn-capable providers and returns the corresponding registered adapters.

canProviderSpawn()

Check if a provider can spawn subagents. Uses providerSupportsById to check if the provider supports the spawn.supportsSubagents capability.

clear()

Clear all adapter registrations. Removes all adapters and provider mappings from the registry.

getProvidersWithSpawnCapability(capability)

Get providers by specific spawn capability Queries CAAMP for providers that support a specific spawn capability. Signature
Parameters Returns — Array of providers with the specified capability

hasParallelSpawnProvider()

Check if any provider supports parallel spawn Signature
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
Parameters 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
Returns — Promise that resolves when initialization is complete

getProjectStats()

Get project statistics. Signature

rankBlockedTask()

Compute a ranking score for a blocked task. Higher score = more urgent = sort first. Signature

getDashboard()

Get project dashboard data. Signature

getCompletionHistory()

Get completion history data. Signature

filterByDate()

Filter tasks by date range on archivedAt. Signature

summaryReport()

Generate summary statistics. Signature

byPhaseReport()

Group tasks by phase with cycle time averages. Signature

byLabelReport()

Group tasks by label frequency. Signature

byPriorityReport()

Group tasks by priority with cycle time averages. Signature

cycleTimesReport()

Compute cycle time statistics with distribution buckets. Signature

trendsReport()

Compute archive trends by day and month. Signature

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

getArchiveStats()

Get archive statistics. Signature

auditData()

Audit data integrity. Signature

createBackup()

Create a backup of CLEO data files. Signature

restoreBackup()

Restore from a backup. Signature

cleanupSystem()

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

writeJsonFileAtomic(filePath, data, indent)

Write a JSON file atomically with backup rotation. Pattern: write temp - backup original - rename temp to target Signature
Parameters

readJsonFile(filePath)

Read a JSON file, returning parsed content or null if not found. Signature
Parameters

getDataPath(projectRoot, filename)

Get the path to a CLEO data file within a project root. Signature
Parameters

resolveProjectRoot()

Resolve the project root directory. Checks CLEO_ROOT env, then falls back to cwd. Signature

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

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
Parameters

isProjectInitialized()

Check if a CLEO project directory exists at the given path Signature

listBackups()

List backup files for a given data file Signature

detectPlatform()

Detect the current platform. Signature

commandExists()

Check if a command exists on PATH. Signature

requireTool()

Require a tool to be available, returning an error message if missing. Signature

checkRequiredTools()

Check all required tools. Signature

getIsoTimestamp()

Get ISO 8601 UTC timestamp. Signature

isoToEpoch()

Convert ISO timestamp to epoch seconds. Signature

dateDaysAgo()

Get ISO date for N days ago. Signature

getFileSize()

Get file size in bytes. Signature

getFileMtime()

Get file modification time as ISO string. Signature

generateRandomHex()

Generate N random hex characters. Signature

sha256()

Compute SHA-256 checksum of a string. Signature

createTempFilePath()

Create a temporary file path. Signature

getNodeVersionInfo()

Get Node.js version info. Signature

getNodeUpgradeInstructions()

Get platform-specific Node.js upgrade instructions. Returns actionable install/upgrade guidance based on OS and available tools. Signature

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

checkCliInstallation()

T4525 Signature

checkCliVersion()

T4525 Signature

checkDocsAccessibility()

T4525 Signature

checkAtReferenceResolution()

T4525 Signature

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

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

checkCleoGitignore()

Check if .cleo/.gitignore exists and matches the template. T4700 Signature

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

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

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

checkLegacyAgentOutputs()

Check if any legacy output directories still exist. Delegates detection to the migration/agent-outputs utility. T4700 Signature

checkCaampMarkerIntegrity()

Verify balanced CAAMP:START/END markers in CLAUDE.md and AGENTS.md. T5153 Signature

checkAtReferenceTargetExists()

Parse references from AGENTS.md CAAMP block and verify each target file exists. T5153 Signature

checkTemplateFreshness()

Compare templates/CLEO-INJECTION.md vs ~/.cleo/templates/CLEO-INJECTION.md. T5153 Signature

checkTierMarkersPresent()

Verify all 3 tier markers exist with matching close tags in deployed template. T5153 Signature

checkNodeVersion()

Check that Node.js meets the minimum required version. Provides OS-specific upgrade instructions when below minimum. Signature

checkGlobalSchemaHealth()

Check that global schemas at ~/.cleo/schemas/ are installed and not stale. Delegates to checkGlobalSchemas() from schema-management.ts. Signature

checkNoLocalSchemas()

Warn if deprecated .cleo/schemas/ directory still exists in the project. Schemas should live in ~/.cleo/schemas/ (global), not in project directories. Signature

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

runAllGlobalChecks()

Run all global health checks and return results array. T4525 Signature

calculateHealthStatus()

Calculate overall status from check results. Returns: 0=passed, 50=warning, 52=critical. T4525 Signature

getSystemHealth()

Run system health checks (SQLite-first per ADR-006). Signature

getSystemDiagnostics()

Run extended diagnostics with fix suggestions. Signature

coreDoctorReport()

Run comprehensive doctor diagnostics combining dependency checks, directory checks, data file checks, gitignore checks, and environment info. T4795 Signature

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

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
Parameters

generateInjection()

Generate Minimum Viable Injection (MVI) markdown. Signature

getLabels()

Get all labels with counts and task IDs per label. Signature

getSystemMetrics()

Get system metrics: token usage, compliance summary, session counts. Signature

getMigrationStatus()

Check/report schema migration status. Signature

getRuntimeDiagnostics()

Signature

safestop()

Safe stop: signal clean shutdown for agents. Signature

uncancelTask()

Uncancel a cancelled task (restore to pending). Signature

detectCircularDeps()

Detect circular dependencies using DFS. Returns the cycle path if found, empty array otherwise. Signature

wouldCreateCycle()

Check if adding a dependency would create a cycle. Signature

getBlockedTasks()

Get tasks that are blocked (have unmet dependencies). Signature

getReadyTasks()

Get tasks that are ready (all dependencies met). Signature

getDependents()

Get tasks that depend on a given task. Signature

getDependentIds()

Get dependent IDs. Signature

getUnresolvedDeps()

Get unresolved dependencies for a task (deps that are not done/cancelled). Signature

validateDependencyRefs()

Validate dependencies for missing references. Signature

validateDependencies()

Full dependency graph validation. Signature

topologicalSort()

Topological sort of tasks by dependencies. Returns sorted task IDs or null if cycle detected. Signature

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

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

currentTask()

Show current task work state. T4462 T4750 Signature

startTask()

Start working on a specific task. T4462 T4750 Signature

stopTask()

Stop working on the current task. T4462 T4750 Signature

getWorkHistory()

Get task work history from session notes. T4462 T4750 Signature

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

getTemplateForSubcommand()

Get template config for a specific subcommand (bug/feature/help). Performs a live parse and filters to the matching template. Signature

generateTemplateConfig()

Generate and cache the config as .cleo/issue-templates.json. Performs a live parse, then writes the result using writeJsonFileAtomic. Signature

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

getCurrentShell()

Detect the current shell. Signature

getRcFilePath()

Get the RC file path for a shell. Signature

detectAvailableShells()

Detect which shells are available on the system. Signature

generateBashAliases()

Generate bash/zsh alias content. Signature

generatePowershellAliases()

Generate PowerShell alias content. Signature

hasAliasBlock()

Check if aliases are already injected in a file. Signature

getInstalledVersion()

Get the installed alias version from an RC file. Signature

injectAliases()

Inject aliases into a shell RC file. Signature

removeAliases()

Remove aliases from a shell RC file. Signature

checkAliasesStatus()

Get alias status for the current shell. Signature

discoverReleaseTasks()

Discover task IDs for a release from completed tasks. Optionally filtered by date range or specific task IDs. Signature

groupTasksIntoSections()

Group tasks into changelog sections. Signature

generateChangelogMarkdown()

Generate changelog markdown for a version. Signature

formatChangelogJson()

Format changelog data as JSON. Signature

writeChangelogFile()

Write changelog content to a file. Signature

appendToChangelog()

Append a new release section to an existing CHANGELOG.md. Signature

generateChangelog()

Full changelog generation: discover tasks, group, generate, write. Signature

parseCommandHeader()

Parse a ###CLEO header block from a script file. Signature

scanAllCommands()

Scan a scripts directory and build a command registry. Returns a map of command name to metadata. Signature

validateHeader()

Validate a command header has required fields. Signature

getCommandScriptMap()

Get command-to-script mapping. Signature

getCommandsByCategory()

Group commands by category. Signature

getCommandsByRelevance()

Filter commands by relevance level. Signature

defaultFlags()

Default flag values. Signature

parseCommonFlags()

Parse common CLI flags from an argument array. Returns flags and remaining positional arguments. Signature

resolveFormat()

Resolve output format based on flags and TTY detection. Returns ‘json’ for non-TTY (piped), ‘human’ for TTY. Signature

isJsonOutput()

Check if output should be JSON. Signature

getValidationKey()

Get the validation key for a target filename. Signature

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

checkManifestEntry()

Verify a manifest entry for a task has valid required fields. T4524 Signature

checkReturnFormat()

Check if a response matches the expected return format. T4524 Signature

scoreSubagentCompliance()

Calculate comprehensive compliance score for a subagent. T4524 Signature

calculateTokenEfficiency()

Calculate token efficiency metrics. T4524 Signature

calculateOrchestrationOverhead()

Calculate orchestration overhead metrics. T4524 Signature

getScriptCommands()

Get command names from scripts directory. Returns sorted list of script basenames without .sh extension. T4527 Signature

getIndexScripts()

Get script names from COMMANDS-INDEX.json. T4527 Signature

getIndexCommands()

Get command names from COMMANDS-INDEX.json. T4527 Signature

checkCommandsSync()

Check commands index vs scripts directory for sync. T4527 Signature

checkWrapperSync()

Check wrapper template sync with COMMANDS-INDEX. T4527 Signature

detectDrift()

Run full drift detection across scripts, index, wrapper, and README. T4527 Signature

shouldRunDriftDetection()

Check if drift detection should run automatically based on config. T4527 Signature

getCacheFilePath()

Get cache file path. T4525 Signature

initCacheFile()

Initialize empty cache file. T4525 Signature

loadCache()

Load cache file or return null if missing/invalid. T4525 Signature

getFileHash()

Get file hash for cache invalidation. T4525 Signature

getCachedValidation()

Check if project validation is cached and valid. Returns the cache entry if valid, null if cache miss. T4525 Signature

cacheValidationResult()

Cache project validation results. T4525 Signature

clearProjectCache()

Clear cache for a specific project. T4525 Signature

clearEntireCache()

Clear entire cache. T4525 Signature

isTempProject()

Check if a project path is a temporary/test directory. T4525 Signature

categorizeProjects()

Filter projects into categories: active, temp, orphaned. T4525 Signature

getProjectCategoryName()

Get human-readable project category name. T4525 Signature

formatProjectHealthSummary()

Format project health summary for display. T4525 Signature

getProjectGuidance()

Get actionable guidance for project issues. T4525 Signature

getUserJourneyStage()

Check user journey stage based on system state. T4525 Signature

getJourneyGuidance()

Get journey-specific guidance text. T4525 Signature

sanitizeFilePath()

Sanitize a file path for safe shell usage. Prevents command injection via malicious file names. T4523 Signature

validateTitle()

Validate a task title. Checks for emptiness, newlines, invisible characters, control chars, and length. T4523 Signature

validateDescription()

T4523 Signature

validateNote()

T4523 Signature

validateBlockedBy()

T4523 Signature

validateSessionNote()

T4523 Signature

validateCancelReason()

Validate a cancellation reason. T4523 Signature

validateStatusTransition()

Validate that a status transition is allowed. T4523 Signature

isValidStatus()

Check if a status string is valid. T4523 Signature

checkTimestampSanity()

Check timestamp format and sanity. T4523 Signature

isMetadataOnlyUpdate()

Check if an update contains only metadata fields (safe for done tasks). T4523 Signature

normalizeLabels()

Deduplicate and normalize labels. T4523 Signature

checkIdUniqueness()

Check ID uniqueness within and across files. T4523 Signature

validateTask()

Validate a single task object. T4523 Signature

validateNoCircularDeps()

Check for circular dependencies using DFS. T4523 Signature

validateSingleActivePhase()

Validate only one phase is active. T4523 Signature

validateCurrentPhaseConsistency()

Validate currentPhase matches an active phase. T4523 Signature

validatePhaseTimestamps()

Validate phase timestamp ordering. T4523 Signature

validatePhaseStatusRequirements()

Validate phase status requirements (e.g., active phases must have startedAt). T4523 Signature

validateAll()

Run all validation checks on a TaskFile. T4523 Signature

parseManifest()

Parse a MANIFEST.jsonl file into entries. Skips invalid JSON lines gracefully. T4524 Signature

findReviewDocs()

Find documents in review status. T4524 Signature

extractTopics()

Extract markdown headings from file content. T4524 Signature

searchCanonicalCoverage()

Search for topic coverage in a docs directory. Returns count of matching files. T4524 Signature

analyzeCoverage()

Analyze documentation coverage for review documents. T4524 Signature

formatGapReport()

Format a gap report for human-readable display. T4524 Signature

findManifestEntry()

Find a manifest entry for a task ID in a JSONL file. T4526 Signature

validateManifestEntry()

Run validation on a manifest entry for a specific task. T4526 Signature

logRealCompliance()

Log validation results to the compliance JSONL file. T4526 Signature

validateAndLog()

Find, validate, and log compliance for a task in one call. T4526 Signature

checkOutputFileExists()

Check if expected output file exists. T4527 Signature

checkDocumentationSections()

Check if file contains required documentation sections. T4527 Signature

checkReturnMessageFormat()

Check if return message follows protocol format. Expected: ” . See MANIFEST.jsonl for .” T4527 Signature

checkManifestFieldPresent()

Check if manifest entry has a required field (non-null, non-empty). T4527 Signature

checkManifestFieldType()

Check if manifest field has expected type. T4527 Signature

checkKeyFindingsCount()

Check if key_findings array has valid count (3-7). T4527 Signature

checkStatusValid()

Check if status is valid enum value. T4527 Signature

checkAgentType()

Check if agent_type matches expected value. T4527 Signature

checkLinkedTasksPresent()

Check if linked_tasks array contains required task IDs. T4527 Signature

checkProvenanceTags()

Check if file contains provenance tag. T4527 Signature

validateCommonManifestRequirements()

Validate common manifest requirements across all protocols. T4527 Signature

isValidGateName()

T4526 Signature

isValidAgentName()

T4526 Signature

getGateOrder()

T4526 Signature

getGateIndex()

T4526 Signature

getDownstreamGates()

T4526 Signature

initVerification()

Initialize a new verification object with default values. T4526 Signature

computePassed()

Compute whether verification has passed based on required gates. T4526 Signature

setVerificationPassed()

Update the passed field on a verification object. T4526 Signature

updateGate()

Update a single gate value. T4526 Signature

resetDownstreamGates()

Reset all downstream gates to null after a gate failure. T4526 Signature

incrementRound()

Increment the round counter. Returns null if max rounds exceeded. T4526 Signature

logFailure()

Log a failure to the failureLog array. T4526 Signature

checkAllGatesPassed()

Check if all required gates have passed. T4526 Signature

isVerificationComplete()

Check if verification is complete (passed = true). T4526 Signature

getVerificationStatus()

Get verification status for display. T4526 Signature

shouldRequireVerification()

Check if a task type should require verification. T4526 Signature

getMissingGates()

Get gate names that are not yet true. T4526 Signature

getGateSummary()

Get gate summary for display. T4526 Signature

checkCircularValidation()

Check for circular validation (self-approval prevention). Prevents: creator validating own work, validator re-testing, tester self-creating. T4526 Signature

allEpicChildrenVerified()

Check if all children of an epic have verification.passed = true. T4526 Signature

allSiblingsVerified()

Check if all siblings of a task are verified. T4526 Signature

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

ProtocolEnforcer

Main protocol enforcement class Signature
Methods

validateProtocol()

Validate protocol compliance for a manifest entry

validateRule()

Validate a single rule

checkLifecycleGate()

Check lifecycle gate prerequisites

recordViolation()

Record a protocol violation

getViolations()

Get recent violations

calculatePenalty()

Calculate penalty for violation severity

enforceProtocol()

Middleware function for domain router Intercepts operations and validates protocol compliance before execution.

requiresProtocolValidation()

Determine if operation requires protocol validation

detectProtocol()

Detect protocol type from request/response

extractManifestEntry()

Extract manifest entry from response

setStrictMode()

Set strict mode

isStrictMode()

Get strict mode status

getHookCapableProviders(event)

Get all providers that support a specific hook event Signature
Parameters Returns — Array of provider IDs that support this event

getSharedHookEvents(providerIds)

Get hook events supported by all specified providers Signature
Parameters 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

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

validateChain()

Validate a complete WarpChain definition. Orchestrates shape validation and gate satisfiability checks, returning a unified ChainValidation result. T5401 Signature

addChain()

Store a validated WarpChain definition. Validates the chain before storing. Throws if validation fails. T5403 Signature

showChain()

Retrieve a WarpChain definition by ID. T5403 Signature

listChains()

List all stored WarpChain definitions. T5403 Signature

findChains()

Find WarpChain definitions by criteria. T5403 Signature

createInstance()

Create a chain instance binding a chain to an epic. T5403 Signature

showInstance()

Retrieve a chain instance by ID. T5403 Signature

listInstanceGateResults()

Read persisted gate results for a chain instance. Signature

advanceInstance()

Advance a chain instance to the next stage, recording gate results. T5403 Signature

validateResearchProtocol()

T4499 Signature

validateConsensusProtocol()

T4499 Signature

validateSpecificationProtocol()

T4499 Signature

validateDecompositionProtocol()

T4499 Signature

validateImplementationProtocol()

T4499 Signature

validateContributionProtocol()

T4499 Signature

validateReleaseProtocol()

T4499 Signature

validateArtifactPublishProtocol()

T4499 Signature

validateProvenanceProtocol()

T4499 Signature

validateProtocol()

Validate a manifest entry against a specific protocol. Throws CleoError with appropriate exit code on strict failure. T4499 Signature

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

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

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

listTesseraTemplates()

List all registered Tessera templates. T5409 Signature

showTessera()

Find a Tessera template by ID. T5409 Signature

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
Parameters

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

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
Parameters Returns — Array of similar entries ranked by distance/relevance

memoryShow()

memory.show - Look up a brain.db entry by ID Signature

memoryBrainStats()

memory.stats - Aggregate stats from brain.db across all tables Signature

memoryDecisionFind()

memory.decision.find - Search decisions in brain.db Signature

memoryDecisionStore()

memory.decision.store - Store a decision to brain.db Signature

memoryFind()

memory.find - Token-efficient brain search Signature

memoryTimeline()

memory.timeline - Chronological context around anchor Signature

memoryFetch()

memory.fetch - Batch fetch brain entries by IDs Signature

memoryObserve()

memory.observe - Save observation to brain Signature

memoryPatternStore()

memory.pattern.store - Store a pattern to BRAIN memory Signature

memoryPatternFind()

memory.pattern.find - Search patterns in BRAIN memory Signature

memoryPatternStats()

memory.pattern.stats - Get pattern memory statistics Signature

memoryLearningStore()

memory.learning.store - Store a learning to BRAIN memory Signature

memoryLearningFind()

memory.learning.find - Search learnings in BRAIN memory Signature

memoryLearningStats()

memory.learning.stats - Get learning memory statistics Signature

memoryContradictions()

memory.contradictions - Find contradictory entries in brain.db Signature

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
memory.link - Link a brain entry to a task Signature
memory.unlink - Remove a link between a brain entry and a task Signature

memoryGraphAdd()

memory.graph.add - Add a node or edge to the PageIndex graph Signature

memoryGraphShow()

memory.graph.show - Get a node and its edges from the PageIndex graph Signature

memoryGraphNeighbors()

memory.graph.neighbors - Get neighbor nodes from the PageIndex graph Signature

memoryReasonWhy()

memory.reason.why - Causal trace through task dependency chains Signature

memoryReasonSimilar()

memory.reason.similar - Find semantically similar entries Signature

memorySearchHybrid()

memory.search.hybrid - Hybrid search across FTS5, vector, and graph Signature

memoryGraphRemove()

memory.graph.remove - Remove a node or edge from the PageIndex graph Signature

pipelineManifestShow()

pipeline.manifest.show - Get manifest entry details by ID Signature

pipelineManifestList()

pipeline.manifest.list - List manifest entries with filters Signature

pipelineManifestFind()

pipeline.manifest.find - Find manifest entries by text (LIKE search on content + type) Signature

pipelineManifestPending()

pipeline.manifest.pending - Get pending manifest items Signature

pipelineManifestStats()

pipeline.manifest.stats - Manifest statistics Signature

pipelineManifestRead()

pipeline.manifest.read - Read manifest entries with optional filter Signature

pipelineManifestAppend()

pipeline.manifest.append - Append entry to pipeline_manifest table Signature

pipelineManifestArchive()

pipeline.manifest.archive - Archive old manifest entries by date Signature

pipelineManifestCompact()

pipeline.manifest.compact - Dedup by contentHash (keep newest by createdAt) Signature

pipelineManifestValidate()

pipeline.manifest.validate - Validate manifest entries for a task Signature

pipelineManifestContradictions()

pipeline.manifest.contradictions - Find entries with overlapping topics but conflicting key_findings Signature

pipelineManifestSuperseded()

pipeline.manifest.superseded - Identify entries replaced by newer work on same topic Signature
pipeline.manifest.link - Link manifest entry to a task Signature

readManifestEntries()

Read all manifest entries from the pipeline_manifest table. Replaces readManifestEntries() from pipeline-manifest-compat. Signature

filterEntries()

Filter manifest entries by criteria (alias for backward compatibility). Signature

distillManifestEntry()

Distill a manifest entry to brain.db observation (Phase 3, pending). Signature

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
Returns — Count of migrated and skipped entries.

resolveProviderFromModelIndex()

Signature

resolveProviderFromModelRegistry()

Signature

resetModelsDevCache()

Signature

measureTokenExchange()

Signature

recordTokenExchange()

Signature

showTokenUsage()

Signature

listTokenUsage()

Signature

summarizeTokenUsage()

Signature

deleteTokenUsage()

Signature

clearTokenUsage()

Signature

autoRecordDispatchTokenUsage()

Signature

getLatestTokenRecord()

Signature

getTokenUsageAggregateSql()

Signature

startParallelExecution()

Start parallel execution for a wave. Signature

endParallelExecution()

End parallel execution for a wave. Signature

getParallelStatus()

Get current parallel execution state. Signature

listSkills()

List available skills. Signature

getSkillContent()

Read skill content for injection into agent context. Signature

getUnblockOpportunities()

Analyze dependency graph for unblocking opportunities. Signature

validateSpawnReadiness()

Validate spawn readiness for a task. Signature

injectContext()

Read protocol injection content for a given protocol type. Core logic for session.context.inject. Signature

generateSessionId()

Generate a canonical session ID. Format: ses_YYYYMMDDHHmmss_6hex Example: ses_20260227171900_a1b2c3 Signature

isValidSessionId()

Check if a string is a valid session ID (any format). Signature

isCanonicalSessionId()

Check if a session ID uses the canonical format. Signature

extractSessionTimestamp()

Extract an approximate timestamp from any valid session ID format. Returns null if the ID format is not recognized. Signature

createSession()

Create a new session. Signature

getSession()

Get a session by ID. Signature

updateSession()

Update a session. Signature

listSessions()

List sessions with optional filters. Signature

endSession()

End a session. Signature

startTask()

Start working on a task within a session. Signature

getCurrentTask()

Get current task for a session. Signature

stopTask()

Stop working on the current task for a session. Signature

workHistory()

Get work history for a session. Signature

gcSessions()

Garbage collect old sessions (mark ended sessions as orphaned after threshold). Signature

getActiveSession()

Get the currently active session (if any). Signature

computeDependencyWaves()

Compute dependency waves for parallel execution. Tasks in the same wave can run in parallel; waves must be sequential. Signature

getNextTask()

Get the next task to work on (highest priority ready task). Signature

getCriticalPath()

Calculate the critical path (longest dependency chain). Returns task IDs along the critical path. Signature

getTaskOrder()

Get task ordering by dependency + priority. Signature

getParallelTasks()

Get parallelizable tasks (tasks with no unmet dependencies). Signature

suggestRelated()

Suggest related tasks based on shared attributes. Signature

addRelation()

Add a relation between tasks. Signature

discoverRelated()

Discover related tasks using various methods. Signature

listRelations()

List existing relations for a task. Signature

canCancel()

Check if a task can be cancelled. Signature

cancelTask()

Cancel a task in the tasks array (returns updated array). Does NOT handle children - use deletion-strategy for that. Signature

cancelMultiple()

Batch cancel multiple tasks. Signature

coreTaskNext()

Suggest next task to work on based on priority, phase, age, and deps. T4790 Signature

coreTaskBlockers()

Show blocked tasks and analyze blocking chains. T4790 Signature

coreTaskTree()

Build hierarchy tree. T4790 Signature

coreTaskDeps()

Show dependencies for a task. T4790 Signature

coreTaskRelates()

Show task relations. T4790 Signature

coreTaskRelatesAdd()

Add a relation between two tasks. T4790 Signature

coreTaskAnalyze()

Analyze tasks for priority and leverage. T4790 Signature

coreTaskRestore()

Restore a cancelled task back to pending. T4790 Signature

coreTaskCancel()

Cancel a task (sets status to ‘cancelled’, a soft terminal state). Use restore to reverse. Use delete for permanent removal. T4529 Signature

coreTaskUnarchive()

Move an archived task back to active tasks. T4790 Signature

coreTaskReorder()

Change task position within its sibling group. T4790 Signature

coreTaskReparent()

Move task under a different parent. T4790 Signature

coreTaskPromote()

Promote a subtask to task or task to root. T4790 Signature

coreTaskReopen()

Reopen a completed task. T4790 Signature

coreTaskComplexityEstimate()

Deterministic complexity scoring from task metadata. T4790 Signature

coreTaskDepsOverview()

Overview of all dependencies across the project. T5157 Signature

coreTaskDepsCycles()

Detect circular dependencies across the project. T5157 Signature

coreTaskDepends()

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

coreTaskStats()

Compute task statistics. T4790 Signature

coreTaskExport()

Export tasks as JSON or CSV. T4790 Signature

coreTaskHistory()

Get task history from the log file. T4790 Signature

coreTaskLint()

Lint tasks for common issues. T4790 Signature

coreTaskBatchValidate()

Validate multiple tasks at once. T4790 Signature

coreTaskImport()

Import tasks from a JSON source string. T4790 Signature

analyzeTaskPriority()

Analyze task priority with leverage scoring. Signature

listLabels()

List all labels with task counts. Signature

showLabelTasks()

Show tasks with a specific label. Signature

getLabelStats()

Get detailed label statistics. Signature

createStoreProvider()

Create a store provider. Always creates SQLite provider (ADR-006). T4647 Signature

getStore()

Get a StoreProvider instance for the given working directory. Convenience wrapper around createStoreProvider with auto-detection. T4645 T4638 Signature

countJsonRecords()

Count records in JSON source files. Signature

migrateJsonToSqliteAtomic(cwd, tempDbPath, logger)

Migrate JSON data to SQLite with atomic rename pattern. Writes to a temporary database file first, then atomically renames. Signature
Parameters Returns — Migration result

migrateJsonToSqlite()

Signature

exportToJson()

Export SQLite data back to JSON format (for inspection or emergency recovery). Signature

repairMissingSizes()

Set size=‘medium’ on tasks that have no size value. Operates directly on the SQLite tasks table. Signature

repairMissingCompletedAt()

Set completedAt=now() on done/cancelled tasks that are missing a completedAt timestamp. Operates directly on the SQLite tasks table. Signature

runAllRepairs()

Run all repair functions. Returns all actions taken (or previewed in dry-run mode). Signature

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
Parameters

VerificationGate

Main Verification Gate class Orchestrates 4-layer validation and determines pass/fail status. Each layer must pass before proceeding to the next. Signature
Methods

verifyOperation()

Execute all 4 gate layers sequentially Stops at first failure unless in advisory mode.

runLayer()

Run a single validation layer with timing

buildSuccessResult()

Build success result when all gates pass

buildFailureResult()

Build failure result when a gate fails

determineSemanticExitCode()

Determine semantic layer exit code from violations

determineReferentialExitCode()

Determine referential layer exit code from violations

determineProtocolExitCode()

Determine protocol layer exit code from violations

requiresValidation()

Check if an operation requires gate validation All mutate operations require validation. Query operations skip validation for performance.

getLayerName()

Get human-readable layer name

createVerificationGate()

Factory function for creating verification gates Signature

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
Methods

getGateStatus()

Get the status of a specific gate

getGateState()

Get the full state of a specific gate

getAllGates()

Get all gate states

canAttempt()

Check if a gate can be attempted (all dependencies passed)

passGate()

Mark a gate as passed.

failGate()

Mark a gate as failed. Per Section 7.4: When a gate fails, all downstream gates reset to null.

cascadeReset()

Reset a gate and all downstream gates to null.

updateBlockedStatus()

Update blocked status for all gates based on current state.

allPassed()

Check if all gates have passed

getPendingGates()

Get all gates that are currently blocked or have null status

getNextAttemptable()

Get the next gate that can be attempted

getDownstreamGates()

Get downstream gates of a given gate (not including the gate itself)

toRecord()

Serialize gate states to a plain record

fromRecord()

Restore gate states from a record

isValidGate()

Check if a gate name is valid

isValidWorkflowGateName()

Validate a workflow gate name string Signature

getWorkflowGateDefinition()

Get the definition for a workflow gate Signature

validateLayer1Schema()

Layer 1: Schema Validation Validates operation parameters against JSON Schema definitions. Checks required fields, data types, and format constraints. Signature

validateLayer2Semantic()

Layer 2: Semantic Validation Validates business rules and logical constraints. Signature

validateLayer3Referential()

Layer 3: Referential Validation Validates cross-entity references and relationships. Signature

validateLayer4Protocol()

Layer 4: Protocol Validation Validates RCASD-IVTR+C lifecycle compliance and protocol requirements. Signature

isFieldRequired()

Helper to check if a field is required for an operation Signature

validateWorkflowGateName()

Validate a workflow gate name T3141 Signature

validateWorkflowGateStatus()

Validate a workflow gate status value per Section 7.3 T3141 Signature

validateWorkflowGateUpdate()

Validate a gate update operation. T3141 Signature

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

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

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

camelToKebab()

Convert a camelCase string to kebab-case. e.g. ‘includeArchive’ → ‘include-archive’ Signature

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

validateConsensusTask()

Validate consensus protocol for a task. Signature

checkConsensusManifest()

Validate consensus protocol from manifest file. Signature

validateContributionTask()

Validate contribution protocol for a task. Signature

checkContributionManifest()

Validate contribution protocol from manifest file. Signature

validateDecompositionTask()

Validate decomposition protocol for a task. Signature

checkDecompositionManifest()

Validate decomposition protocol from manifest file. Signature

validateImplementationTask()

Validate implementation protocol for a task. Signature

checkImplementationManifest()

Validate implementation protocol from manifest file. Signature

validateSpecificationTask()

Validate specification protocol for a task. Signature

checkSpecificationManifest()

Validate specification protocol from manifest file. Signature

validateSchema(schemaType, data)

Validate data against a CLEO schema Signature
Parameters 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
Parameters Returns — Validation result

clearSchemaCache()

Clear the schema cache (useful for testing) Signature

validateTitleDescription()

Validate that title and description are both present and different. This is a critical anti-hallucination check. Signature

validateTimestamps()

Validate that timestamps are not in the future Signature

validateIdUniqueness()

Validate ID uniqueness across all tasks (todo + archive) Signature

validateNoDuplicateDescription()

Validate no duplicate task descriptions Signature

validateHierarchy()

Validate hierarchy constraints. Accepts optional limits to override defaults (from config). Signature

validateStatusTransition()

Validate status transition Signature

validateNewTask()

Run all validation rules on a task being created Signature

hasErrors()

Check if violations contain any errors (not just warnings) Signature

coreValidateReport()

Run comprehensive validation report on tasks database — checks business rules, dependencies, checksums, data integrity, and schema compliance. T4795 Signature

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

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

coreValidateTask()

Validate a single task against anti-hallucination rules. T4786 Signature

coreValidateProtocol()

Check basic protocol compliance for a task. T4786 Signature

coreValidateManifest()

Validate manifest JSONL entries for required fields. T4786 Signature

coreValidateOutput()

Validate an output file for required sections. T4786 Signature

coreComplianceSummary()

Get aggregated compliance metrics. T4786 Signature

coreComplianceViolations()

List compliance violations. T4786 Signature

coreComplianceRecord()

Record a compliance check result to COMPLIANCE.jsonl. T4786 Signature

coreTestStatus()

Check test suite availability. T4786 Signature

coreCoherenceCheck()

Cross-validate task graph for consistency. T4786 Signature

coreTestRun()

Execute test suite via subprocess. T4786 Signature

coreBatchValidate()

Batch validate all tasks against schema and rules. T4786 Signature

coreTestCoverage()

Get test coverage metrics. T4786 Signature

buildBrainState()

Build brain state for agent bootstrapping. Signature

getCriticalPath()

Find the critical path (longest dependency chain) in the task graph. Signature

resolveSkillPathsForProvider(providerId, scope, projectRoot)

Get effective skill paths for a provider considering precedence Signature
Parameters 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
Parameters Returns — Array of provider IDs using the specified precedence

getSkillsMapWithPrecedence()

Build complete skills map with precedence information Signature
Returns — Array of provider skill configurations with precedence data

determineInstallationTargets(context)

Determine target installation paths for a skill Signature
Parameters Returns — Array of installation targets with provider ID and path

supportsAgentsPath(providerId)

Check if provider supports agents path Signature
Parameters Returns — True if provider has agents path configuration

coreTaskPlan()

Build composite planning view. T4914 Signature

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
Parameters Returns — Populated RcasdIndex T4801

writeIndex(index, cwd)

Write RCASD-INDEX.json to disk. Signature
Parameters

readIndex(cwd)

Read RCASD-INDEX.json from disk. Signature
Parameters Returns — The index or null if not found T4801

rebuildIndex(cwd)

Rebuild and write the index from current disk state. Signature
Parameters Returns — The rebuilt index T4801

getTaskAnchor(taskId, cwd)

Get task anchor by task ID. Signature
Parameters Returns — TaskAnchor or null T4801

findByStage(stage, cwd)

Find tasks by pipeline stage. Signature
Parameters Returns — Array of [taskId, anchor] pairs T4801

findByStatus(status, cwd)

Find tasks by status. Signature
Parameters Returns — Array of [taskId, anchor] pairs T4801

getIndexTotals(cwd)

Get index summary statistics. Signature
Parameters Returns — Index totals or null T4801

generateCodebaseMapSummary()

Signature

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

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

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

resolveEpicFromFilename()

Extract an epic ID from a filename pattern like T####-* or T####_*. Signature

normalizeDirectoryNames()

Rename suffixed epic directories (e.g. T4881_install-channelsT4881). Signature

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

migrateContributionFiles()

Migrate .cleo/contributions/ files to appropriate epic’s contributions/ subdirectory. Files follow the pattern T####-session-*.json with epicId in content. Signature

migrateLooseFiles()

Migrate loose T####_*.md files from .cleo/rcasd/ root into rcasd/\{epicId\}/research/ subdirectories. Signature

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
Parameters

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
Parameters Returns — Promise resolving to the created Pipeline Throws
  • CleoError If pipeline already exists or database operation fails
Example

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
Parameters Returns — Promise resolving to Pipeline or null Throws
  • CleoError If database query fails
Example

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
Parameters Returns — Promise resolving when transition is complete Throws
  • CleoError If transition is invalid or prerequisites not met
Example

getCurrentStage(taskId)

Get the current stage of a pipeline. Convenience method to quickly check which stage a task is currently in. Signature
Parameters Returns — Promise resolving to the current Stage Throws
  • CleoError If database query fails
Example

listPipelines(options)

List pipelines with optional filtering. Signature
Parameters Returns — Promise resolving to array of Pipelines Throws
  • CleoError If database query fails
Example

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
Parameters 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
Parameters 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
Parameters Returns — Promise resolving to boolean T4800 T4912 - Implemented SQLite wiring

getPipelineStatistics()

Get pipeline statistics. Returns aggregate counts of pipelines by status and stage. Signature
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
Parameters 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
Parameters Returns — Promise resolving to array of resumable pipelines Example

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
Parameters Returns — Promise resolving to pipeline context Example

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
Parameters Returns — Promise resolving to resume result Example

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
Parameters Returns — Promise resolving to auto-resume result Example

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
Parameters Returns — Promise resolving to resume check result Example

formatResumeSummary(pipelines)

Get resume summary for display to user. Formats resumable pipelines into a human-readable summary. Signature
Parameters Returns — Formatted summary string T4805

handleCompletedStage(context)

Handle completed stage edge case. If the current stage is completed, suggests advancing to next stage. Signature
Parameters 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
Parameters Returns — Block analysis and resolution hints T4805

checkBlockedStageDetails(taskId, cwd)

Handle blocked stage edge case - async version with database lookup. Signature
Parameters 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
Parameters Returns — Promise resolving to PrereqCheck result Throws
  • CleoError If validation fails
Example

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
Parameters Returns — Promise resolving to TransitionValidation Throws
  • CleoError If validation fails unexpectedly
Example

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
Parameters Returns — Promise resolving to StateTransitionResult Throws
  • CleoError If transition is invalid
Example

setStageStatus(stage, status, context)

Set the status of a stage. Updates stage status with validation of allowed state transitions. Signature
Parameters Returns — Updated StageState T4800 Throws
  • CleoError If status transition is invalid

getStageStatus(stage, context)

Get the status of a stage. Signature
Parameters 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
Parameters Returns — Object with valid flag and reason T4800

createInitialContext(pipelineId, assignedAgent)

Create initial state machine context for a pipeline. Signature
Parameters Returns — Initial StateMachineContext T4800

getValidNextStages(context, includeForce)

Get stages that can be transitioned to from the current stage. Signature
Parameters Returns — Array of valid next stages T4800

getCurrentStageState(context)

Get the current stage state. Signature
Parameters Returns — Current StageState T4800

isTerminalState(context)

Check if the pipeline is in a terminal state. Signature
Parameters Returns — True if in release stage and completed T4800

isBlocked(context)

Check if the pipeline is blocked. Signature
Parameters Returns — True if current stage is blocked T4800

validateTransitions(transitions, context)

Validate multiple transitions. Signature
Parameters Returns — Array of validation results T4800

canSkipStage(stage)

Check if a stage can be skipped. Signature
Parameters Returns — True if stage is skippable T4800

skipStage(stage, reason, context)

Skip a stage with validation. Signature
Parameters Returns — Updated StageState T4800 Throws
  • CleoError If stage cannot be skipped

getContextStatusFromPercentage()

Determine status from percentage. Signature

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

isHITLEnabled()

Check if HITL warnings are enabled. Signature

generateHITLWarnings()

Generate HITL warnings based on lock state. Signature

getHighestLevel()

Get highest warning level from warnings. Signature

getConcurrencyJson()

Get concurrency data for analyze JSON output. Signature

getEnforcementMode()

Get the current enforcement mode. Signature

isSessionEnforcementEnabled()

Check if session enforcement is enabled. Signature

getActiveSessionInfo()

Get active session info. Returns null if no active session. Signature

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

validateTaskInScope()

Validate that a task is within the current session’s scope. Only enforced when a session is active. Signature

checkStatuslineIntegration()

Check if statusline integration is configured. Returns the current integration status. Signature

getStatuslineConfig()

Get the statusline setup command for Claude Code settings. Signature

getSetupInstructions()

Get human-readable setup instructions. Signature

getPreferredChannel(domain, operation)

Look up the preferred channel for a given domain + operation. Signature
Parameters Returns — Preferred channel (‘mcp’, ‘cli’, or ‘either’ as fallback)

getRoutingForDomain(domain)

Get routing entries for a specific domain. Signature
Parameters Returns — All routing entries for the domain

getOperationsByChannel(channel)

Get all operations that prefer a specific channel. Signature
Parameters Returns — Matching routing entries

generateMemoryProtocol(context)

Generate dynamic memory protocol instructions based on provider capabilities. Signature
Parameters Returns — Markdown content for memory protocol guidance

generateRoutingGuide(context)

Generate a dynamic routing guide based on operation preferences. Signature
Parameters Returns — Markdown content showing preferred channels per operation

generateDynamicSkillContent(context)

Generate complete dynamic skill content for the current provider. Signature
Parameters Returns — Complete dynamic skill markdown content

TaskCache

In-memory cache for task indices with checksum-based staleness detection. Signature
Methods

computeChecksum()

Compute a checksum from task data for staleness detection.

init()

Initialize or rebuild cache from tasks. Returns true if cache was rebuilt, false if already valid.

buildLabelIndex()

buildPhaseIndex()

buildHierarchyIndex()

getTasksByLabel()

Get task IDs by label.

getTasksByPhase()

Get task IDs by phase.

getAllLabels()

Get all labels.

getAllPhases()

Get all phases.

getLabelCount()

Get label count for a specific label.

getParent()

Get parent ID for a task.

getChildren()

Get children IDs for a task.

getDepth()

Get depth for a task.

getChildCount()

Get child count.

getRootTasks()

Get root tasks (no parent).

getLeafTasks()

Get leaf tasks (no children).

invalidate()

Force invalidation and rebuild.

getStats()

Get cache statistics.

extractPackageMeta()

Extract package metadata from an export file. T4552 Signature

logImportStart()

Log import operation start with package metadata. T4552 Signature

logImportSuccess()

Log import operation completion with full metadata. T4552 Signature

logImportError()

Log import operation error with diagnostic details. T4552 Signature

logImportConflict()

Log import conflict detection and resolution. T4552 Signature

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

detectCycles()

Detect cycles in task dependency graph. Returns true if no cycles, false if cycles detected. T4552 Signature

findActivePipelinesWithStagesAndTasks(taskIds, cwd)

Find active pipelines joined with their stages and tasks. Optionally filters by specific task IDs. Signature
Parameters 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
Parameters Returns — Matching rows (typically 0 or 1)

findPipelineWithStage(taskId, stageName, cwd)

Find a pipeline and a specific stage by taskId and stageName. Signature
Parameters Returns — Matching rows (typically 0 or 1)

updatePipelineCurrentStage(pipelineId, currentStageId, cwd)

Update pipeline’s currentStageId. Signature
Parameters

getStagesByPipelineId(pipelineId, cwd)

Get all stages for a pipeline, ordered by sequence. Signature
Parameters Returns — All stage rows for the pipeline

activateStage(stageId, startedAt, cwd)

Update a stage’s status to ‘in_progress’ and clear block fields. Signature
Parameters

findPipelineWithCurrentStage(taskId, cwd)

Find pipeline with current stage (no task join) by taskId. Used by checkBlockedStageDetails. Signature
Parameters Returns — Matching rows

getGateResultsByStageId(stageId, cwd)

Get gate results for a stage, ordered by checkedAt descending. Signature
Parameters Returns — Gate result rows

getGateResultsByStageIdUnordered(stageId, cwd)

Get gate results for a stage without ordering (for simple checks). Signature
Parameters Returns — Gate result rows

getEvidenceByStageId(stageId, cwd)

Get evidence for a stage, ordered by recordedAt descending. Signature
Parameters Returns — Evidence rows

getRecentTransitions(pipelineId, limit, cwd)

Get recent transitions for a pipeline, ordered by createdAt descending. Signature
Parameters Returns — Transition rows

insertTransition(transition, cwd)

Insert a new transition record. Signature
Parameters

checkAtomicity()

Check task atomicity using 6-point heuristic test. Default threshold: 4 (passing requires = 4/6 criteria met). Signature

extractTaskRefs()

Extract task IDs from text content. Scans for patterns like T1234, T001, T42 (T followed by 3+ digits). Signature

createRelatesEntries()

Create relates entries from extracted task IDs. Signature

mergeRelatesArrays()

Merge new relates entries with existing ones. Existing entries take precedence (dedup by taskId). Signature

validateRelatesRefs()

Validate that referenced task IDs exist. Returns array of invalid (non-existent) task IDs. Signature

extractAndCreateRelates()

Convenience: extract task refs from text and create relates entries. Signature

calculateAffectedTasks()

Calculate which tasks would be affected by a delete operation. Signature

calculateImpact()

Calculate impact of deletion. Signature

generateWarnings()

Generate warnings based on impact analysis. Signature

previewDelete()

Main preview function - coordinates all preview calculations. Signature

isValidStrategy()

Validate a strategy name. Signature

handleChildren()

Handle children using the specified strategy. Returns the modified tasks array and the strategy result. Signature

GraphCache

Graph cache for expensive dependency calculations. Automatically invalidates when tasks change. Signature
Methods

computeChecksum()

Compute a simple checksum from task data to detect changes.

isValid()

Check if cache is still valid for given tasks.

isExpired()

Check if a cache entry has expired.

invalidate()

Invalidate all caches.

ensureFresh()

Ensure cache is fresh for the given task set.

getDescendants()

Get descendants of a task (cached).

getChildren()

Get children of a task (cached).

getDependents()

Get dependents of a task (cached).

getWaves()

Get dependency waves (cached).

getStats()

Get cache statistics.

discoverByLabels()

Discover related tasks by shared labels. Signature

discoverByDescription()

Discover related tasks by description similarity (keyword-based Jaccard). Signature

discoverByFiles()

Discover related tasks by shared files. Signature

discoverByHierarchy()

Discover related tasks by hierarchical proximity (siblings and cousins). Signature

discoverRelatedTasks()

Discover related tasks using all methods combined. Signature

suggestRelates()

Suggest relates entries filtered by threshold. Signature

getCurrentPhase()

Get the current active phase from project metadata. Signature

getTasksByPhase()

Get tasks belonging to a specific phase. Signature

calculatePhaseProgress()

Calculate progress for a phase. Signature

getAllPhaseProgress()

Get progress for all phases. Signature

validatePhaseTransition()

Signature

createPhaseTransition()

Create a phase transition record. Signature

applyPhaseTransition()

Apply a phase transition to project metadata. Returns updated project data. Signature

getNextPhase()

Get the next phase in order. Signature

allPhasesComplete()

Check if all phases are complete. Signature

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
Parameters Returns — Result with old/new parent and new type

getSizeWeight()

Get weight for a task size. Signature

getPriorityWeight()

Get weight for a task priority. Signature

calculateTaskScore()

Calculate a composite score for task ordering. Higher score = should be worked on first. Signature

sortByWeight()

Sort tasks by weighted score (highest first). Signature

calculateTotalEffort()

Calculate total weighted effort for a set of tasks. Signature

calculateWeightedProgress()

Calculate completion percentage by weight. Signature

calculateRemainingEffort()

Estimate remaining effort (weighted sum of non-complete tasks). Signature

getLastActivity()

Get the most recent activity timestamp for a task. Signature

classifyStaleness()

Classify staleness level for a task. Signature

getStalenessInfo()

Get staleness info for a single task. Signature

findStaleTasks()

Find all stale tasks (stale, critical, or abandoned). Signature

getStalenessSummary()

Signature

validateReleaseTask()

Validate release protocol for a task. Signature

checkReleaseManifest()

Validate release protocol from manifest file. Signature

validateResearchTask()

Validate research protocol for a task. Signature

checkResearchManifest()

Validate research protocol from manifest file. Signature

validateTestingTask()

Validate testing protocol for a task. Signature

checkTestingManifest()

Validate testing protocol from manifest file. Signature

validateValidationTask()

Validate verification/validation protocol for a task. Signature

checkValidationManifest()

Validate validation protocol from manifest file. Signature