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| Name | Type | Description |
|---|---|---|
cleoDir | string | Absolute path to .cleo directory |
config | LoggerConfig | Logging configuration from CleoConfig.logging |
projectHash | : string | undefined | Stable project identity token bound to every log entry. Optional for backward compatibility; warns if absent. |
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| Name | Type | Description |
|---|---|---|
subsystem | string | Logical subsystem name (e.g. ‘audit’, ‘mcp’, ‘migration’) |
getLogDir()
Get the current log directory path. Useful for read APIs that need to scan log files. SignaturecloseLogger()
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. SignaturegetPlatformPaths()
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. SignaturegetSystemInfo()
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. SignatureisProjectInitialized()
Check if a CLEO project is initialized at the given root. Checks for tasks.db. SignaturegetCleoHome()
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). SignaturegetCleoTemplatesDir()
Get the global CLEO templates directory. SignaturegetCleoSchemasDir()
Get the global CLEO schemas directory. SignaturegetCleoDocsDir()
Get the global CLEO docs directory. SignaturegetCleoDir()
Get the project CLEO data directory (relative). Respects CLEO_DIR env var, defaults to “.cleo”. SignaturegetCleoDirAbsolute()
Get the absolute path to the project CLEO directory. SignaturegetProjectRoot()
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. SignatureresolveProjectPath()
Resolve a project-relative path to an absolute path. SignaturegetTaskPath()
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. SignaturegetSessionsPath()
Get the path to the project’s sessions.json file. SignaturegetArchivePath()
Get the path to the project’s archive file. SignaturegetLogPath()
Get the path to the project’s log file. Canonical structured runtime log path (pino). T4644 SignaturegetBackupDir()
Get the backup directory for operational backups. SignaturegetGlobalConfigPath()
Get the global config file path. SignaturegetAgentOutputsDir()
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 SignaturegetAgentOutputsAbsolute()
Get the absolute path to the agent outputs directory. T4700 SignaturegetManifestPath()
Get the absolute path to the MANIFEST.jsonl file. Checks config.agentOutputs.manifestFile for custom filename, defaults to ‘MANIFEST.jsonl’. T4700 SignaturegetManifestArchivePath()
Get the absolute path to the MANIFEST.archive.jsonl file. T4700 SignatureisAbsolutePath()
Check if a path is absolute (POSIX or Windows). SignaturegetCleoLogDir()
Get the OS log directory for CLEO global logs. Linux: ~/.local/state/cleo | macOS: ~/Library/Logs/cleo | Windows: %LOCALAPPDATA%cleoLog SignaturegetCleoCacheDir()
Get the OS cache directory for CLEO. Linux: ~/.cache/cleo | macOS: ~/Library/Caches/cleo | Windows: %LOCALAPPDATA%cleoCache SignaturegetCleoTempDir()
Get the OS temp directory for CLEO ephemeral files. SignaturegetCleoConfigDir()
Get the OS config directory for CLEO. Linux: ~/.config/cleo | macOS: ~/Library/Preferences/cleo | Windows: %APPDATA%cleoConfig SignaturegetAgentsHome()
Get the global agents hub directory. Respects AGENTS_HOME env var, defaults to ~/.agents. SignaturegetClaudeAgentsDir()
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). Passforce: 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. SignaturegetBrainDbPath()
Get the path to the brain.db SQLite database file. SignatureresolveBrainMigrationsFolder()
Resolve the path to the drizzle-brain migrations folder. Works from both src/ (dev via tsx) and dist/ (compiled). SignatureisBrainVecLoaded()
Check whether the sqlite-vec extension is loaded for the current brain.db. SignaturegetBrainDb()
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). SignaturecloseBrainDb()
Close the brain.db database connection and release resources. SignatureresetBrainDbState()
Reset brain.db singleton state without saving. Used during tests or when database file is recreated. Safe to call multiple times. SignaturegetBrainNativeDb()
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. SignaturegetNexusDbPath()
Get the path to the nexus.db SQLite database file. nexus.db lives in the global ~/.cleo/ directory. SignatureresolveNexusMigrationsFolder()
Resolve the path to the drizzle-nexus migrations folder. Works from both src/ (dev via tsx) and dist/ (compiled). SignaturegetNexusDb()
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). SignaturecloseNexusDb()
Close the nexus.db database connection and release resources. SignatureresetNexusDbState()
Reset nexus.db singleton state without saving. Used during tests or when database file is recreated. Safe to call multiple times. SignaturegetNexusNativeDb()
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. SignatureopenNativeDatabase()
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. SignaturegetDbPath()
Get the path to the SQLite database file. SignaturegetDb()
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). SignatureresolveMigrationsFolder()
Resolve the path to the drizzle migrations folder. Works from both src/ (dev via tsx) and dist/ (compiled). SignatureisSqliteBusy()
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 SignaturecloseDb()
Close the database connection and release resources. SignatureresetDbState()
Reset database singleton state without saving. Used during migrations when database file is deleted and recreated. Safe to call multiple times. SignaturegetSchemaVersion()
Get the schema version from the database. SignaturedbExists()
Check if the database file exists. SignaturegetNativeDb()
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. SignaturegetNativeTasksDb()
Get the underlying node:sqlite DatabaseSync instance for tasks.db. Alias for getNativeDb() — mirrors getBrainNativeDb() naming convention. SignaturecloseAllDatabases()
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 SignaturesafeParseJson()
Parse a JSON string, returning undefined on null/undefined input or parse error. SignaturesafeParseJsonArray()
Parse a JSON string expected to contain an array. Returns undefined for null/undefined input, empty arrays, or parse errors. SignaturerowToTask()
Convert a database TaskRow to a domain Task object. SignaturetaskToRow()
Convert a domain Task to a database row for insert/upsert. SignaturearchivedTaskToRow()
Convert a domain Task to a row suitable for archived tasks. SignaturerowToSession()
Convert a SessionRow to a domain Session. SignaturegetErrorDefinition()
Look up an error definition by exit code. SignaturegetErrorDefinitionByLafsCode()
Look up an error definition by LAFS string code. SignaturegetAllErrorDefinitions()
Get all error definitions as an array. SignatureCleoError
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(). SignaturetoLAFSError()
Produce a LAFS-conformant error object. T4655toProblemDetails()
Produce an RFC 9457 Problem Details object. T5240toJSON()
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). SignatureupsertSession()
Upsert a single session row into the sessions table. SignatureupdateDependencies()
Update dependencies for a task: delete existing, then re-insert. Optionally filters by a set of valid IDs. SignaturebatchUpdateDependencies()
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. SignatureloadDependenciesForTasks()
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. SignatureloadRelationsForTasks()
Batch-load relations for a list of tasks and apply them in-place. Mirrors loadDependenciesForTasks pattern for task_relations table (T5168). SignaturesetMetaValue()
Write a JSON blob to the schema_meta table by key. SignaturecreateSqliteDataAccessor(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
| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Working directory for path resolution (defaults to process.cwd()) |
atomicWrite()
Write data to a file atomically. Creates parent directories if they don’t exist. Uses write-file-atomic for crash-safe writes (temp file - rename). SignaturesafeReadFile()
Read a file and return its contents. Returns null if the file does not exist. SignatureatomicWriteJson()
Write JSON data atomically with consistent formatting. SignatureatomicDatabaseMigration(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| Name | Type | Description |
|---|---|---|
dbPath | string | Path to the database file (e.g., tasks.db) |
tempPath | string | Path to temporary database (e.g., tasks.db.new) |
validateFn | (path: string | Async function to validate the temp database |
restoreDatabaseFromBackup(dbPath, backupPath)
Restore database from backup after failed migration. Signature| Name | Type | Description |
|---|---|---|
dbPath | string | Path to the database file |
backupPath | string | Path to the backup file |
cleanupMigrationArtifacts(backupPath)
Clean up migration artifacts after successful migration. Signature| Name | Type | Description |
|---|---|---|
backupPath | string | Path to backup file to delete |
validateSqliteDatabase(dbPath)
Validate SQLite database integrity by attempting to open it. Signature| Name | Type | Description |
|---|---|---|
dbPath | string | Path to database file |
createBackup()
Create a numbered backup of a file. Rotates existing backups (file.1 - file.2, etc.) and removes excess. SignaturelistBackups()
List existing backups for a file, sorted by number (newest first). SignaturerestoreFromBackup()
Restore a file from its most recent backup. Returns the path of the backup that was restored. SignatureacquireLock()
Acquire an exclusive lock on a file. Returns a release function that must be called when done. SignatureisLocked()
Check if a file is currently locked. SignaturewithLock()
Execute a function while holding an exclusive lock on a file. The lock is automatically released when the function completes (or throws). SignatureisProviderHookEvent()
Type guard for CAAMP/provider-discoverable hook events. SignatureisInternalHookEvent()
Type guard for CLEO-local coordination hook events. SignatureHookRegistry
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. Signatureregister()
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. SignaturereadJsonRequired()
Read a JSON file, throwing if it doesn’t exist. SignaturecomputeChecksum()
Compute a truncated SHA-256 checksum of a value. Used for integrity verification (matches Bash CLI’s 16-char hex format). SignaturesaveJson()
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 SignatureappendJsonl()
Append a line to a JSONL file atomically. Used for manifest entries and audit logs. SignaturereadLogEntries()
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 SignaturecleoGitCommand()
Run a git command against the isolated .cleo/.git repo, suppressing errors. T4872 SignatureisCleoGitInitialized()
Check whether the isolated .cleo/.git repo has been initialized. T4872 SignatureloadStateFileAllowlist()
Load additional state file paths from config.jsoncheckpoint.stateFileAllowlist. Returns an empty array if config is missing, malformed, or the key is absent.
Signature
loadCheckpointConfig()
Load checkpoint configuration from config.json. T4552 SignatureshouldCheckpoint()
Check whether a checkpoint should be performed. Evaluates: enabled, .cleo/.git initialized, debounce elapsed, files changed. T4552 T4872 SignaturegitCheckpoint()
Stage .cleo/ state files and commit to the isolated .cleo/.git repo. Never fatal - all git errors are suppressed. T4552 T4872 SignaturegitCheckpointStatus()
Show checkpoint configuration and status. T4552 T4872 SignaturegitCheckpointDryRun()
Show what files would be committed (dry-run). T4552 T4872 SignatureDataSafetyError
Safety violation error SignaturegetSafetyStats()
Get current safety statistics SignatureresetSafetyStats()
Reset safety statistics (for testing) SignaturesafeSaveSessions()
Safe wrapper for DataAccessor.saveSessions() SignaturesafeSaveArchive()
Safe wrapper for DataAccessor.saveArchive() SignaturesafeSingleTaskWrite()
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. SignaturesafeAppendLog()
Safe wrapper for DataAccessor.appendLog() Note: Log appends are fire-and-forget (no verification) but we still checkpoint to ensure data is committed. SignaturerunDataIntegrityCheck()
Run comprehensive data integrity check. Validates all data files and sequence consistency. SignatureforceSafetyCheckpoint()
Force immediate checkpoint. Use before destructive operations. SignaturedisableSafety()
Disable all safety for current process. DANGEROUS - only use for recovery operations. SignatureenableSafety()
Re-enable safety after being disabled. SignatureSafetyDataAccessor
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). SignaturelogVerbose()
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| Name | Type | Description |
|---|---|---|
accessor | DataAccessor | The accessor to wrap |
cwd | : string | undefined | Working directory |
isSafetyEnabled()
Check if safety is currently enabled. SignaturegetSafetyStatus()
Get safety status information. SignaturecreateDataAccessor()
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). SignaturegetAccessor()
Convenience: get a DataAccessor with auto-detected engine. SignatureshowSequence()
Show current sequence state. SignaturecheckSequence()
Check sequence integrity. SignaturerepairSequence()
Repair sequence if behind. SignatureallocateNextTaskId()
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 SignatureSafetyError
Safety violation error. SignaturecheckTaskExists()
Check if a task ID already exists (collision detection). Signature- SafetyError if task exists and strict mode is enabled
verifyTaskWrite()
Verify a task was actually written to the database. Signature- SafetyError if verification fails
validateAndRepairSequence()
Validate and repair sequence if necessary. SignaturetriggerCheckpoint()
Trigger auto-checkpoint after successful write. SignaturesafeCreateTask()
Safely create a task with all safety mechanisms. Wraps the actual createTask operation. SignaturesafeUpdateTask()
Safely update a task with all safety mechanisms. SignaturesafeDeleteTask()
Safely delete a task with all safety mechanisms. SignatureverifySessionWrite()
Verify session write. SignaturesafeCreateSession()
Safely create a session with all safety mechanisms. SignatureforceCheckpointBeforeOperation()
Force a checkpoint before destructive operations. Use this before migrations, bulk updates, etc. SignaturerunDataIntegrityCheck()
Run comprehensive data integrity check. Reports all issues found. SignaturegetTask()
Get a task by ID, including its dependencies. SignatureupdateTask()
Update an existing task. SignaturedeleteTask()
Delete a task by ID. SignaturelistTasks()
List tasks with optional filters. SignaturefindTasks()
Find tasks by fuzzy text search. SignaturearchiveTask()
Archive a task (sets status to ‘archived’ with metadata). SignatureaddDependency()
Add a dependency between tasks. SignatureremoveDependency()
Remove a dependency. SignatureaddRelation()
Add a relation between tasks. SignaturegetRelations()
Get relations for a task. SignaturegetBlockerChain()
Get the dependency chain (blockers) for a task using recursive CTE. SignaturegetChildren()
Get children of a task (hierarchy). SignaturegetSubtree()
Build a tree from a root task using recursive CTE. SignaturecountByStatus()
Count tasks by status. SignaturecountTasks()
Get total task count (excluding archived). SignaturecreateTask()
Create a task with full safety protections. Includes: collision detection, write verification, sequence validation, auto-checkpoint. SignatureupdateTaskSafe()
Update a task with full safety protections. Includes: write verification, auto-checkpoint. SignaturedeleteTaskSafe()
Delete a task with full safety protections. Includes: delete verification, auto-checkpoint. SignatureshowTask()
Get a task by ID with enriched details. Checks active tasks first, then archive if not found. T4460 SignaturecreatePage()
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 Signaturepaginate()
Apply pagination to an array of items and return the sliced result with page metadata. T4668 T4663 SignaturetoCompact()
Convert a full Task to compact representation. SignaturelistTasks()
List tasks with optional filtering and pagination. T4460 SignaturefuzzyScore()
Calculate fuzzy match score between query and text. Higher score = better match. 0 = no match. T4460 SignaturefindTasks()
Search tasks by fuzzy matching, ID prefix, or exact title. Returns minimal fields only (context-efficient). T4460 SignatureextractAdrId()
Extract ADR ID from filename (e.g., ‘ADR-007-domain-consolidation.md’ - ‘ADR-007’) SignatureparseFrontmatter()
Parse bold-key frontmatter pattern: Key: value SignatureextractTitle()
Extract H1 title from markdown SignatureparseAdrFile()
Parse a single ADR markdown file into an AdrRecord SignaturelinkPipelineAdr(projectRoot, taskId)
Link ADRs to a pipeline task when the architecture_decision stage completes. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Absolute path to project root |
taskId | string | Task ID that owns the pipeline (e.g., ‘T4942’) |
syncAdrsToDb()
Sync all ADR markdown files into the architecture_decisions table AND regenerate MANIFEST.jsonl in one pass. SignaturerecordEvidence(epicId, stage, uri, type, options)
Record an evidence artifact linked to a lifecycle stage. Writes to the SQLitelifecycle_evidence table.
Signature
| Name | Type | Description |
|---|---|---|
epicId | string | Epic task ID (e.g. ‘T4881’) |
stage | string | Canonical stage name (e.g. ‘research’) |
uri | string | URI of the evidence artifact |
type | EvidenceType | Evidence type: ‘file’, ‘url’, or ‘manifest’ |
options | : \{ agent?: string | undefined; description?: string | undefined; cwd?: string | undefined; \} | undefined | Optional agent and description |
getEvidence(epicId, stage, cwd)
Query evidence records for an epic, optionally filtered by stage. Signature| Name | Type | Description |
|---|---|---|
epicId | string | Epic task ID |
stage | : string | undefined | Optional stage name filter |
cwd | : string | undefined | Optional working directory |
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
| Name | Type | Description |
|---|---|---|
epicId | string | Epic task ID |
stage | string | Canonical stage name |
filePath | string | Absolute or relative path to the file |
cwd | : string | undefined | Optional working directory |
getEvidenceSummary(epicId, cwd)
Aggregate evidence counts per stage for an epic. Signature| Name | Type | Description |
|---|---|---|
epicId | string | Epic task ID |
cwd | : string | undefined | Optional working directory |
normalizeEpicId(dirName)
Strip suffixes from epic directory names. E.g.T4881_install-channels - T4881
Signature
| Name | Type | Description |
|---|---|---|
dirName | string | Directory name that may contain a suffix |
getRcasdBaseDir(cwd)
Get the absolute path to the.cleo/rcasd/ base directory.
Signature
| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Optional working directory override |
getEpicDir(epicId, cwd)
Get the absolute path to.cleo/rcasd/\{epicId\}/. Uses the normalized epic ID (without suffixes).
Signature
| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier (e.g. T4881) |
cwd | : string | undefined | Optional working directory override |
findEpicDir(epicId, cwd)
Search bothrcasd/ and legacy rcsd/ for an existing epic directory. Also checks suffixed directory names (e.g. T4881_install-channels matches T4881).
Signature
| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier to search for |
cwd | : string | undefined | Optional working directory override |
getStagePath(epicId, stage, cwd)
Get the stage subdirectory path for an epic. Uses STAGE_SUBDIRS mapping, falling back to the raw stage name. Signature| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier |
stage | string | Canonical stage name (e.g. research, contribution) |
cwd | : string | undefined | Optional working directory override |
ensureStagePath(epicId, stage, cwd)
Get the stage subdirectory path, creating it if it does not exist. Signature| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier |
stage | string | Canonical stage name |
cwd | : string | undefined | Optional working directory override |
getManifestPath(epicId, cwd)
Get the manifest path for an epic under the default rcasd directory. Signature| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier |
cwd | : string | undefined | Optional working directory override |
.cleo/rcasd/\{epicId\}/_manifest.json
findManifestPath(epicId, cwd)
Search bothrcasd/ and rcsd/ for an existing manifest file. Checks suffixed directory names as well.
Signature
| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier |
cwd | : string | undefined | Optional working directory override |
getLooseResearchFiles(cwd)
Scan the rcasd root directory for looseT####_*.md files that are not inside subdirectories.
Signature
| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Optional working directory override |
listEpicDirs(cwd)
List all epic directories acrossrcasd/ and rcsd/.
Signature
| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Optional working directory override |
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
| Name | Type | Description |
|---|---|---|
content | string | Full markdown file content |
serializeFrontmatter(metadata)
Convert a FrontmatterMetadata object to a YAML frontmatter string. Output format: Signature| Name | Type | Description |
|---|---|---|
metadata | FrontmatterMetadata | The frontmatter metadata to serialize |
--- 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| Name | Type | Description |
|---|---|---|
content | string | Original markdown content |
metadata | FrontmatterMetadata | Frontmatter metadata to set |
buildFrontmatter(epicId, stage, options)
Convenience builder for common frontmatter patterns. Auto-setsupdated to the current ISO date string.
Signature
| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier (e.g. T4881) |
stage | string | RCASD stage name (e.g. research) |
options | : \{ task?: string | undefined; related?: RelatedLink[] | undefined; created?: string | undefined; \} | undefined | Optional fields: task, related links, created date |
getBacklinks(epicId, stage, cwd)
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
| Name | Type | Description |
|---|---|---|
epicId | string | Epic identifier to search for |
stage | string | Stage name to search for |
cwd | : string | undefined | Optional working directory override |
getStageOrder(stage)
Get the order/index of a stage (1-based). Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to look up |
isStageBefore(stageA, stageB)
Check if stage A comes before stage B in the pipeline. Signature| Name | Type | Description |
|---|---|---|
stageA | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | First stage to compare |
stageB | "research" | ... 7 more ... | "release" | Second stage to compare |
isStageAfter(stageA, stageB)
Check if stage A comes after stage B in the pipeline. Signature| Name | Type | Description |
|---|---|---|
stageA | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | First stage to compare |
stageB | "research" | ... 7 more ... | "release" | Second stage to compare |
getNextStage(stage)
Get the next stage in the pipeline. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | Current stage |
getPreviousStage(stage)
Get the previous stage in the pipeline. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | Current stage |
getStagesBetween(from, to)
Get all stages between two stages (inclusive). Signature| Name | Type | Description |
|---|---|---|
from | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | Starting stage |
to | "research" | "consensus" | ... 6 more ... | "release" | Ending stage |
getPrerequisites(stage)
Get prerequisites for a stage. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to get prerequisites for |
isPrerequisite(potentialPrereq, stage)
Check if one stage is a prerequisite of another. Signature| Name | Type | Description |
|---|---|---|
potentialPrereq | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | Stage that might be a prerequisite |
stage | "research" | ... 7 more ... | "release" | Stage to check against |
getDependents(stage)
Get all stages that depend on a given stage. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to find dependents for |
isValidStage(stage)
Check if a stage name is valid. Signature| Name | Type | Description |
|---|---|---|
stage | string | Stage name to validate |
validateStage(stage)
Validate a stage name and throw if invalid. Signature| Name | Type | Description |
|---|---|---|
stage | string | Stage name to validate |
- Error If stage is invalid
isValidStageStatus(status)
Check if a stage status is valid. Signature| Name | Type | Description |
|---|---|---|
status | string | Status to validate |
getStagesByCategory(category)
Get stages by category. Signature| Name | Type | Description |
|---|---|---|
category | StageCategory | Category to filter by |
getSkippableStages()
Get skippable stages. SignaturecheckTransition(from, to, force)
Check if a transition is allowed. Signature| Name | Type | Description |
|---|---|---|
from | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | Source stage |
to | "research" | "consensus" | ... 6 more ... | "release" | Target stage |
force | : boolean | Whether to allow forced transitions |
ensureStageArtifact()
Ensure stage artifact exists and frontmatter/backlinks are up to date. SignaturegetLifecycleState()
Get the current lifecycle state for an epic. T4467 SignaturestartStage()
Start a lifecycle stage. T4467 SignaturecompleteStage()
Complete a lifecycle stage. T4467 SignatureskipStage()
Skip a lifecycle stage. T4467 SignaturecheckGate()
Check lifecycle gate before starting a stage. T4467 SignaturegetLifecycleStatus()
Get lifecycle status for an epic from SQLite. Returns stage progress, current/next stage, and blockers. T4801 - SQLite-native implementation SignaturegetLifecycleHistory()
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 SignaturegetLifecycleGates()
Get all gate statuses for an epic. T4785 SignaturegetStagePrerequisites()
Get prerequisites for a target stage. Pure data function, no I/O. T4785 SignaturecheckStagePrerequisites()
Check if a stage’s prerequisites are met for an epic. T4785 SignaturerecordStageProgress()
Record a stage status transition (progress/record). SQLite-native implementation - T4801 T4785 T4801 SignatureskipStageWithReason()
Skip a stage with a reason (engine-compatible). T4785 SignatureresetStage()
Reset a stage to pending (emergency). T4785 SignaturepassGate()
Mark a gate as passed. SQLite-native implementation - T4801 T4785 T4801 SignaturefailGate()
Mark a gate as failed. SQLite-native implementation - T4801 T4785 T4801 SignaturelistEpicsWithLifecycle()
List all epic IDs that have lifecycle data. T4785 SignaturegetCurrentSessionId()
Get the current session ID. SignaturegetContextStatePath()
Get context state file path for a session. SignaturereadContextState()
Read context state for a session. Returns null if stale or missing. SignaturegetThresholdLevel()
Determine the threshold level for a given percentage. SignatureshouldAlert()
Determine if we should alert based on threshold crossing. Returns the alert level if a new threshold was crossed, null otherwise. SignaturegetRecommendedAction()
Get recommended action for an alert level. SignaturecheckContextAlert()
Main function to check and determine if an alert should fire. Non-blocking - always returns a result. SignaturepushWarning()
Push a deprecation or informational warning into the current envelope. Warnings are drained (consumed) by the next formatSuccess/formatError call. T4669 T4663 SignatureformatSuccess()
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 SignatureformatError()
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 SignatureformatOutput()
Format any result (success or error) as LAFS JSON. SignaturegetRegistryEntry()
Look up a registry entry by CLEO exit code. T4671 T4663 SignaturegetRegistryEntryByLafsCode()
Look up a registry entry by LAFS string code. T4671 T4663 SignaturegetCleoErrorRegistry()
Get the full CLEO error registry for conformance testing. T4671 T4663 SignatureisCleoRegisteredCode()
Check if a LAFS code is registered in the CLEO error registry. T4671 T4663 SignaturecreateTestDb()
Create a temporary directory with an initialized tasks.db. Usage: SignaturemakeTaskFile()
Build a TaskFile structure from a list of task partials. Useful for seeding test data via accessor.upsertSingleTask(). SignatureseedTasks()
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 SignaturegetChildren()
Get direct children of a task. SignaturegetChildIds()
Get direct child IDs. SignaturegetDescendants()
Get all descendants of a task (recursive). SignaturegetDescendantIds()
Get all descendant IDs (flat list). SignaturegetParentChain()
Get the parent chain (ancestors) from a task up to the root. Returns ordered from immediate parent to root. SignaturegetParentChainIds()
Get the parent chain as IDs. SignaturegetDepth()
Calculate depth of a task in the hierarchy (0-based). Root tasks have depth 0, their children depth 1, etc. SignaturegetRootAncestor()
Get the root ancestor of a task. SignatureisAncestorOf()
Check if a task is an ancestor of another. SignatureisDescendantOf()
Check if a task is a descendant of another. SignaturegetSiblings()
Get sibling tasks (same parent). SignaturevalidateHierarchy()
SignaturewouldCreateCircle()
Detect circular reference if parentId were set. SignaturebuildTree()
SignatureflattenTree()
Flatten a tree back to a list (depth-first). SignatureresolveHierarchyPolicy()
Resolve a full HierarchyPolicy from config, starting with a profile preset and overriding with any explicitly set config.hierarchy fields. SignatureassertParentExists()
Assert that a parent task exists in the task list. Returns an error result if not found, null if OK. SignatureassertNoCycle()
Assert that re-parenting would not create a cycle. Returns an error result if a cycle is detected, null if OK. SignaturecountActiveChildren()
Count active (non-done, non-cancelled, non-archived) children of a parent. SignaturevalidateHierarchyPlacement()
Validate whether a new task can be placed under the given parent according to the resolved hierarchy policy. SignatureloadConfig()
Load and merge configuration from all sources. Priority: defaults global config project config environment vars SignaturegetConfigValue()
Get a single config value with source tracking. Returns the value and which source it came from. SignaturegetRawConfigValue()
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 SignaturegetRawConfig()
Get the full raw project config (no cascade). Returns null if no config file exists. T4789 SignatureparseConfigValue()
Parse a string value into its appropriate JS type. Handles booleans, null, integers, floats, and JSON. T4789 SignaturesetConfigValue()
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 SignaturevalidateTitle()
Validate a task title. T4460 SignaturevalidateStatus()
Validate task status. T4460 SignaturenormalizePriority()
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 SignaturevalidatePriority()
Validate task priority. T4460 T4572 SignaturevalidateTaskType()
Validate task type. T4460 SignaturevalidateSize()
Validate task size. T4460 SignaturevalidateLabels()
Validate label format. T4460 SignaturevalidatePhaseFormat()
Validate phase slug format. T4460 SignaturevalidateDepends()
Validate dependency IDs exist. T4460 SignaturevalidateParent()
Validate parent hierarchy constraints. T4460 SignaturegetTaskDepth()
Get the depth of a task in the hierarchy. T4460 SignatureinferTaskType()
Infer task type from parent context. T4460 SignaturegetNextPosition()
Get the next position for a task within a parent scope. T4460 SignaturelogOperation()
Log an operation to the audit log. T4460 SignaturefindRecentDuplicate()
Check for recent duplicate task. T4460 SignatureaddTask()
Add a new task to the todo file. T4460 SignaturelistPhases()
List all phases with status summaries. T4464 SignatureshowPhase()
Show the current phase details. T4464 SignaturesetPhase()
Set the current project phase. T4464 SignaturestartPhase()
Start a phase (pending - active). T4464 SignaturecompletePhase()
Complete a phase (active - completed). T4464 SignatureadvancePhase()
Advance to the next phase. T4464 SignaturerenamePhase()
Rename a phase and update all task references. T4464 SignaturedeletePhase()
Delete a phase with optional task reassignment. T4464 SignaturepruneAuditLog(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| Name | Type | Description |
|---|---|---|
cleoDir | string | Absolute path to .cleo directory |
config | LoggingConfig | LoggingConfig with auditRetentionDays and archiveBeforePrune |
queryAudit()
Query audit entries from SQLite audit_log table. Used by session-grade.ts for behavioral analysis. Returns entries ordered chronologically (ASC) to preserve behavioral sequence for grading analysis. SignaturegenerateProjectHash()
Canonical project identity hash. SHA-256 of absolute path, first 12 hex chars. Single source of truth — do not duplicate this function elsewhere. SignaturevalidateAgainstSchema()
Validate data against a JSON Schema object. Throws CleoError on validation failure. SignaturevalidateAgainstSchemaFile()
Load a JSON Schema file and validate data against it. SignaturecheckSchema()
Check if data is valid against a schema without throwing. Returns an array of error messages (empty if valid). SignatureresolveSchemaPath(schemaName)
Resolve the absolute path to a schema file at runtime. Priority: 1. Global install: ~/.cleo/schemas/schemaName 2. Package bundled: /schemas/schemaName Signature| Name | Type | Description |
|---|---|---|
schemaName | string | Filename of the schema (e.g. “config.schema.json”) |
getSchemaVersion(schemaName)
Read the schema version from a resolved schema file. ChecksschemaVersion (top-level) and _meta.schemaVersion (canonical).
Signature
| Name | Type | Description |
|---|---|---|
schemaName | string | Filename of the schema (e.g. “config.schema.json”) |
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| Name | Type | Description |
|---|---|---|
opts | — | Optional settings (currently unused, reserved for future options) |
checkGlobalSchemas()
Verify that global schemas are installed and not stale. SignaturecheckSchemaStaleness()
Compare global schema versions against bundled package versions. SignaturelistInstalledSchemas()
List all schemas installed in ~/.cleo/schemas/. SignaturecleanProjectSchemas(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| Name | Type | Description |
|---|---|---|
projectRoot | string | Absolute path to the project root |
readSchemaVersionFromFile()
Read the top-levelschemaVersion 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| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Project root (defaults to process.cwd()) |
detectProjectType()
Detect project type from directory contents. Returns a schema-compliant ProjectContext object. SignatureBrainDataAccessor
SignatureaddDecision()
getDecision()
findDecisions()
updateDecision()
addPattern()
getPattern()
findPatterns()
updatePattern()
addLearning()
getLearning()
findLearnings()
updateLearning()
addObservation()
getObservation()
findObservations()
updateObservation()
addLink()
getLinksForMemory()
getLinksForTask()
removeLink()
addStickyNote()
getStickyNote()
findStickyNotes()
updateStickyNote()
deleteStickyNote()
addPageNode()
getPageNode()
findPageNodes()
removePageNode()
addPageEdge()
getPageEdges()
getNeighbors()
removePageEdge()
getBrainAccessor()
Factory: get a BrainDataAccessor backed by the brain.db singleton. SignaturesetEmbeddingProvider()
Register an embedding provider for the brain system. Validates that the provider’s dimensions match the vec0 table. Signature- Error if provider dimensions do not match EMBEDDING_DIMENSIONS
getEmbeddingProvider()
Get the currently registered embedding provider, or null. SignatureclearEmbeddingProvider()
Clear the current embedding provider (useful for testing). SignatureembedText()
Embed text into a float vector using the registered provider. Returns null when no provider is set or not available (FTS5-only fallback). SignatureisEmbeddingAvailable()
Check whether embedding is currently available. SignaturesearchSimilar(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| Name | Type | Description |
|---|---|---|
query | string | Text to find similar entries for |
projectRoot | string | Project root directory |
limit | : number | undefined | Maximum results to return (default 10) |
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 SignaturerebuildFts5Index()
Rebuild FTS5 indexes from the content tables. Useful after bulk inserts that bypass triggers. T5130 SignaturesearchBrain()
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 SignatureresetFts5Cache()
Reset the cached FTS5 availability flag. Used in tests to force re-detection. SignaturehybridSearch(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| Name | Type | Description |
|---|---|---|
query | string | Search query text |
projectRoot | string | Project root directory |
options | : HybridSearchOptions | undefined | Weight and limit configuration |
getInjectionTemplateContent()
Get the CLEO-INJECTION.md template content from the package templates/ directory. Returns null if the template file is not found. SignatureensureInjection()
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 SignaturebuildContributorInjectionBlock()
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. SignaturecheckInjection()
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. SignaturefileExists()
Check if a file exists and is readable. SignaturestripCLEOBlocks()
Strip legacy !— CLEO:START —…!— CLEO:END — blocks from a file. Called before CAAMP injection to prevent competing blocks. SignatureremoveCleoFromRootGitignore()
Remove .cleo/ or .cleo entries from the project root .gitignore. SignaturegetPackageRoot()
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. SignaturegetGitignoreContent()
Load the gitignore template from the package’s templates/ directory. Falls back to embedded content if file not found. SignaturegetCleoVersion()
Read CLEO version from package.json. SignaturecreateDefaultConfig()
SignatureensureCleoStructure()
Create .cleo/ directory and all required subdirectories. Idempotent: skips directories that already exist. SignatureensureGitignore()
Create or repair .cleo/.gitignore from template. Idempotent: skips if file already exists with correct content. SignatureensureConfig()
Create default config.json if missing. Idempotent: skips if file already exists. SignatureensureProjectInfo()
Create or refresh project-info.json. Idempotent: skips if file already exists (unless force). SignatureensureContributorMcp()
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. SignatureensureProjectContext()
Detect and write project-context.json. Idempotent: skips if file exists and is less than staleDays old (default: 30). SignatureensureCleoGitRepo()
Initialize isolated .cleo/.git checkpoint repository. Idempotent: skips if .cleo/.git already exists. SignatureensureSqliteDb()
Create SQLite database if missing. Idempotent: skips if tasks.db already exists. SignaturecheckCleoStructure()
Verify all required .cleo/ subdirectories exist. SignaturecheckGitignore()
Verify .cleo/.gitignore exists and matches template. SignaturecheckConfig()
Verify config.json exists and is valid JSON. SignaturecheckProjectInfo()
Verify project-info.json exists with required fields. SignaturecheckProjectContext()
Verify project-context.json exists and is not stale (default: 30 days). SignaturecheckCleoGitRepo()
Verify .cleo/.git checkpoint repository exists. SignaturecheckSqliteDb()
Verify .cleo/tasks.db exists and is non-empty. SignatureensureBrainDb()
Create brain.db if missing. Idempotent: skips if brain.db already exists. SignaturecheckBrainDb()
Verify .cleo/brain.db exists and is non-empty. SignaturecheckMemoryBridge()
Verify .cleo/memory-bridge.md exists. Warning level if missing (not failure) — it is auto-generated. SignatureensureGlobalHome()
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. SignatureensureGlobalTemplates()
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. SignatureensureGlobalScaffold()
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) SignaturecheckGlobalHome()
Check that the global ~/.cleo/ home and its required subdirectories exist. Read-only: no side effects. SignaturecheckGlobalTemplates()
Check that the global injection template is present and current. Read-only: no side effects. SignaturecheckLogDir()
Check that the project log directory exists. Read-only: no side effects. SignaturegetMcpServerName()
Resolve MCP server name by channel. SignaturedetectEnvMode()
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 SignaturegenerateMcpServerEntry()
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 SignatureensureGitHooks()
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 SignaturecheckGitHooks()
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. SignaturetoTaskFileExt()
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. SignaturerecordDecision()
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. SignaturecomputeHandoff()
Compute handoff data for a session. Gathers all session statistics and auto-computes structured state. SignaturepersistHandoff()
Persist handoff data to a session. SignaturegetHandoff()
Get handoff data for a session. SignaturegetLastHandoff()
Get handoff data for the most recent ended session. Filters by scope if provided. SignaturecomputeDebrief()
Compute rich debrief data for a session. Builds on computeHandoff() and adds decisions, git state, chain position. T4959 SignaturegenerateMemoryBridgeContent()
Generate memory bridge content from brain.db. Returns the markdown string (does not write to disk). SignaturewriteMemoryBridge()
Write memory bridge content to .cleo/memory-bridge.md. SignaturerefreshMemoryBridge()
Best-effort refresh: call from session.end, tasks.complete, or memory.observe. Never throws. SignaturedetectLegacyAgentOutputs(projectRoot, cleoDir)
Detect legacy agent-output directories in a project. Read-only check — never modifies the filesystem. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Absolute path to project root |
cleoDir | string | Absolute path to .cleo/ directory |
migrateAgentOutputs(projectRoot, cleoDir)
Run the full agent-outputs migration. Copies files from all legacy locations into .cleo/agent-outputs/, merges MANIFEST.jsonl entries with path rewriting and deduplication, updates config.json, and removes legacy directories. Safe to call when no legacy directories exist (returns early). Safe to call when canonical directory already exists (merges). Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Absolute path to project root |
cleoDir | string | Absolute path to .cleo/ directory |
migrateJsonToSqlite()
Migrate projects from legacy JSON registry to nexus.db. For each project entry in projects-registry.json: - Reads target/.cleo/project-info.json for a stable UUID (projectId) - Falls back to randomUUID() if project-info.json is absent - Upserts into project_registry (on conflict by projectHash → update path/name/lastSeen) On success, renames the JSON file to .migrated. SignaturegetNexusHome()
Get path to the NEXUS home directory (cache, etc.). SignaturegetNexusCacheDir()
Get path to the NEXUS cache directory. SignaturegetRegistryPath()
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. SignaturereadRegistryRequired()
Read the global registry, throwing if not initialized. SignaturenexusInit()
Initialize the NEXUS directory structure and nexus.db. Idempotent — safe to call multiple times. Migrates legacy JSON registry on first run if present. SignaturenexusRegister()
Register a project in the global registry (nexus.db). SignaturenexusUnregister()
Unregister a project from the global registry. SignaturenexusList()
List all registered projects. SignaturenexusGetProject()
Get a project by name or hash. Returns null if not found. SignaturenexusProjectExists()
Check if a project exists in the registry. SignaturenexusSync()
Sync project metadata (task count, labels) for a registered project. SignaturenexusSyncAll()
Sync all registered projects. SignaturenexusSetPermission()
Update a project’s permission level in the registry. Used by permissions.ts to avoid direct JSON file writes. SignaturenexusReconcile()
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 SignatureanalyzeStack()
SignatureanalyzeArchitecture()
SignatureanalyzeStructure()
SignatureanalyzeConventions()
SignatureanalyzeTesting()
SignatureanalyzeIntegrations()
SignatureanalyzeConcerns()
SignaturestorePattern()
Store a new pattern. If a similar pattern already exists (same type + matching text), increments frequency. T4768, T5241 SignaturesearchPatterns()
Search patterns by criteria. T4768, T5241 SignaturepatternStats()
Get pattern statistics. T4768, T5241 SignaturestoreLearning()
Store a new learning. T4769, T5241 SignaturesearchLearnings()
Search learnings by criteria. Results sorted by confidence (highest first). T4769, T5241 SignaturelearningStats()
Get learning statistics. T4769, T5241 SignaturesearchBrainCompact(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| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
params | SearchBrainCompactParams | Search parameters |
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| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
params | TimelineBrainParams | Timeline parameters with anchor ID and depth |
fetchBrainEntries(projectRoot, params)
Batch-fetch full details by IDs. Groups IDs by prefix to query the correct tables via BrainDataAccessor. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
params | FetchBrainEntriesParams | Fetch parameters with IDs |
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| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
params | ObserveBrainParams | Observation data |
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| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
options | : \{ batchSize?: number | undefined; \} | undefined | Optional batch size configuration |
storeMapToBrain()
SignaturemapCodebase()
SignatureisValidAdapter()
Validate that a loaded module export implements the CLEOProviderAdapter interface. Checks for required methods and properties without relying on instanceof. SignatureloadAdapterFromManifest(manifest)
Dynamically load and instantiate an adapter from its manifest. Uses the manifest’s packagePath to resolve the adapter module, then looks for acreateAdapter() factory or a default export class.
Signature
| Name | Type | Description |
|---|---|---|
manifest | AdapterManifest | The adapter manifest with a resolved packagePath |
- 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. SignaturedetectProvider()
Detect whether a provider is active in the current environment by checking its detection patterns. SignatureAdapterManager
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 SignaturegetInstance()
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 SignatureinitMcpServer()
Install MCP server config to all detected providers via CAAMP. T4706 SignatureinitCoreSkills()
Install CLEO core skills to the canonical skills directory via CAAMP. T4707 T4689 SignatureinitNexusRegistration()
Register/reconcile project with NEXUS. Uses nexusReconcile for idempotent handshake — auto-registers if new, updates path if moved, confirms identity if unchanged. T4684 T5368 SignatureinstallGitHubTemplates(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| Name | Type | Description |
|---|---|---|
projectRoot | string | Absolute path to the project root. |
created | string[] | Array to push “created: …” log entries into. |
skipped | string[] | Array to push “skipped: …” log entries into. |
updateDocs()
Run update-docs only: refresh all injections without reinitializing. Re-injects CLEO-INJECTION.md into all detected agent instruction files. T4686 SignatureinitProject()
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 SignatureisAutoInitEnabled()
Check if auto-init is enabled via environment variable. T4789 SignatureensureInitialized()
Check if a project is initialized and auto-init if configured. Returns initialized: true if ready, throws otherwise. T4789 SignaturegetVersion()
Get the current CLEO/project version. Checks VERSION file, then package.json. T4789 SignaturebootstrapGlobalCleo()
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. SignatureinstallMcpToProviders()
Install the CLEO MCP server config to all detected providers. SignatureinstallSkillsGlobally()
Install CLEO core skills globally via CAAMP. SignaturebootstrapCaamp()
SignatureexportTasks()
Export tasks to a portable format. Returns the formatted content and metadata. SignatureimportTasks()
Import tasks from an export file. SignaturevalidateSyntax()
Validate a query string matches expected syntax. SignatureparseQuery()
Parse a query string into its components. Signature- 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. SignatureresolveProjectPath()
Resolve a project name to its filesystem path. Handles special cases: ”.” (current), ”*” (wildcard marker). SignatureresolveTask()
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. SignaturegetProjectFromQuery()
Extract the project name from a query without full resolution. Useful for permission checks before task lookup. SignatureextractKeywords()
Extract meaningful keywords from text (filters stop words and short tokens). SignaturediscoverRelated()
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. SignaturesearchAcrossProjects()
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. SignaturepermissionLevel()
Convert a permission string to its numeric level. Returns 0 for invalid/unknown permissions. SignaturegetPermission()
Get the permission level for a registered project. Returns ‘read’ as default if the project has no explicit permission. SignaturecheckPermission()
Check if a project has sufficient permissions (non-throwing). Uses hierarchical comparison: execute = write = read. SignaturerequirePermission()
Require a permission level or throw CleoError. Used as a guard at the start of cross-project operations. SignaturecheckPermissionDetail()
Full permission check returning a structured result. SignaturesetPermission()
Set the permission level for a project. Validates the permission value and updates the registry. T4574 SignaturecanRead()
Convenience: check read access. SignaturecanWrite()
Convenience: check write access. SignaturecanExecute()
Convenience: check execute access. SignaturematchesPattern()
Match a file path against a glob-like pattern. Supports: ’*’ (single segment wildcard), ’**’ (recursive wildcard), and trailing ’/’ for directory matching. T4883 SignaturegetSharingStatus()
Get the sharing status: which .cleo/ files are tracked vs ignored. T4883 SignaturesyncGitignore()
Sync the project .gitignore to match the sharing config. Adds/updates a managed section between CLEO markers. T4883 SignatureinvalidateDepsCache()
Invalidate the cached TaskFile (call after writes). T4659 T4654 SignaturebuildGraph()
Build an adjacency graph from task dependencies. T4464 SignaturegetDepsOverview()
Get dependency overview for all tasks. T4464 SignaturegetTaskDeps()
Get dependencies for a specific task. T4464 SignaturetopologicalSort()
Topological sort of tasks respecting dependencies. Returns tasks in execution order. Throws on cycles. T4464 SignaturegetExecutionWaves()
Group tasks into parallelizable execution waves. T4464 SignaturegetCriticalPath()
Find the critical path (longest dependency chain) from a task. T4464 SignaturegetImpact()
Find all tasks affected by changes to a given task. T4464 SignaturedetectCycles()
Detect circular dependencies in the task graph. T4464 SignaturegetTaskTree()
Build task hierarchy tree. T4464 SignatureaddRelation()
Manage task relationships (relates/blocks). T4464 SignaturebuildDependencyGraph()
Build a dependency graph for a set of tasks. Returns a Map from task ID to the set of task IDs it depends on. SignaturedetectCircularDependencies(tasks, graph)
Detect circular dependencies using DFS traversal. Signature| Name | Type | Description |
|---|---|---|
tasks | Task[] | The set of tasks to analyze |
graph | : Map<string | Pre-built dependency graph (optional; built from tasks if not provided) |
findMissingDependencies(children, allTasks)
Find missing dependencies — deps that reference tasks outside the epic that are not yet completed. Signature| Name | Type | Description |
|---|---|---|
children | Task[] | Child tasks of the epic |
allTasks | Task[] | All tasks in the project (to check if deps are completed elsewhere) |
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| Name | Type | Description |
|---|---|---|
children | Task[] | Child tasks of the epic |
allTasks | Task[] | All tasks in the project |
countManifestEntries(projectRoot)
Count manifest entries from MANIFEST.jsonl. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | The project root directory |
estimateContext(taskCount, projectRoot, epicId)
Estimate context usage for orchestration. Signature| Name | Type | Description |
|---|---|---|
taskCount | number | Number of tasks to estimate for |
projectRoot | string | The project root directory |
epicId | : string | undefined | Optional epic ID for scoped estimation |
computeWaves()
Compute execution waves using topological sort. SignaturegetEnrichedWaves()
Get enriched wave data for an epic. SignaturecountByStatus()
Count tasks by status. SignaturecomputeEpicStatus(epicId, epicTitle, children)
Compute epic-specific status. Signature| Name | Type | Description |
|---|---|---|
epicId | string | The epic task ID |
epicTitle | string | The epic title |
children | Task[] | Child tasks of the epic |
computeOverallStatus(tasks)
Compute overall orchestration status across all tasks. Signature| Name | Type | Description |
|---|---|---|
tasks | Task[] | All tasks in the project |
computeProgress(tasks)
Compute progress metrics for all tasks. Signature| Name | Type | Description |
|---|---|---|
tasks | Task[] | All tasks to measure |
computeStartupSummary(epicId, epicTitle, children, readyCount)
Compute startup summary for an epic. Signature| Name | Type | Description |
|---|---|---|
epicId | string | The epic task ID |
epicTitle | string | The epic title |
children | Task[] | Child tasks of the epic |
readyCount | number | Number of ready tasks |
startOrchestration()
Start an orchestrator session for an epic. T4466 SignatureanalyzeEpic()
Analyze an epic’s dependency structure. T4466 SignaturegetReadyTasks()
Get parallel-safe ready tasks for an epic. T4466 SignaturegetNextTask()
Get the next task to work on for an epic. T4466 SignatureprepareSpawn()
Prepare a spawn context for a subagent. T4466 SignaturevalidateSpawnOutput()
Validate a subagent’s output. T4466 SignaturegetOrchestratorContext()
Get orchestrator context summary. T4466 SignatureautoDispatch()
Auto-dispatch: determine the protocol for a task based on metadata. T4466 SignatureresolveTokens()
Resolve tokens in a prompt string. T4466 SignaturebridgeSessionToMemory(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| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory for brain.db resolution |
sessionData | SessionBridgeData | Session metadata to record |
storeDecision()
Store a new decision or update an existing one if a duplicate is found. Duplicate detection: same decision text (case-insensitive). T5155 SignaturerecallDecision()
Recall a specific decision by ID. T5155 SignaturesearchDecisions()
Search decisions by type, confidence, outcome, and/or free-text query. Query searches across decision + rationale fields using LIKE. T5155 SignaturelistDecisions()
List decisions with pagination. T5155 SignatureupdateDecisionOutcome()
Update the outcome of a decision after learning from results. T5155 SignatureextractTaskCompletionMemory()
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. SignatureextractSessionEndMemory()
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. SignatureresolveTaskDetails()
Resolve an array of task IDs to their full Task objects. Tasks that cannot be found are silently excluded. SignaturecompleteTask()
Complete a task by ID. Handles dependency checking and optional auto-completion of epics. T4461 SignatureupdateTask()
Update a task’s fields. T4461 SignaturegetLinksByProvider()
Find all links for a given provider. SignaturegetLinkByExternalId()
Find a link by provider + external ID. SignaturegetLinksByTaskId()
Find all links for a given CLEO task. SignaturecreateLink()
Create a new external task link. SignaturetouchLink()
Update the lastSyncAt and optionally the title/metadata for an existing link. SignatureremoveLinksByProvider()
Remove all links for a provider (used during provider deregistration). Signaturereconcile(externalTasks, options, accessor)
Reconcile external task state with CLEO’s authoritative task store. Signature| Name | Type | Description |
|---|---|---|
externalTasks | ExternalTask[] | Normalized tasks from a provider adapter. |
options | ReconcileOptions | Reconciliation options. |
accessor | : DataAccessor | undefined | Optional DataAccessor override (for testing). |
getArtifactHandler()
Get handler for an artifact type. T4552 SignaturehasArtifactHandler()
Check if a handler is registered for an artifact type. T4552 SignaturebuildArtifact()
Build an artifact using the appropriate handler. T4552 SignaturevalidateArtifact()
Validate an artifact using the appropriate handler. T4552 SignaturepublishArtifact()
Publish an artifact using the appropriate handler. T4552 SignaturegetSupportedArtifactTypes()
Get all supported artifact types. T4552 SignatureparseChangelogBlocks()
Parse [custom-log]…[/custom-log] blocks from a CHANGELOG section. Returns the extracted block content (tags stripped) and the content with tags+content removed. SignaturewriteChangelogSection()
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)’ SignatureloadReleaseConfig()
Load release configuration with defaults. SignaturevalidateReleaseConfig()
Validate release configuration. SignaturegetArtifactType()
Get artifact type from config. SignaturegetReleaseGates()
Get release gates from config. SignaturegetChangelogConfig()
Get changelog configuration. SignaturegetDefaultGitFlowConfig()
Return the default GitFlow branch configuration. SignaturegetGitFlowConfig()
Merge caller-supplied GitFlow config with defaults. SignaturegetDefaultChannelConfig()
Return the default channel configuration. SignaturegetChannelConfig()
Merge caller-supplied channel config with defaults. SignaturegetPushMode()
Return the configured push mode, defaulting to ‘auto’. SignaturegetDefaultChannelConfig()
Return the default branch-to-channel mapping. SignatureresolveChannelFromBranch()
Resolve the release channel for a given Git branch name. Resolution order: 1. Exact match inconfig.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. SignaturevalidateVersionChannel()
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’ SignaturedescribeChannel()
Return a human-readable description of the given release channel. SignaturegetPlatformPath()
Get the output path for a CI platform. SignaturedetectCIPlatform()
Detect the CI platform from the project. SignaturegenerateCIConfig()
Generate CI config for a platform. SignaturewriteCIConfig()
Write CI config to the appropriate path. SignaturevalidateCIConfig()
Validate an existing CI config. SignatureisGhCliAvailable()
Check if thegh 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 SignaturedetectBranchProtection()
Detect whether a branch has protection rules enabled. Strategy 1 (preferred): usegh 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. SignatureformatManualPRInstructions()
Format human-readable instructions for creating a PR manually. SignaturecreatePullRequest()
Create a GitHub pull request using thegh 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. SignaturecheckDoubleListing()
Check if any tasks are listed in multiple releases. SignaturevalidateVersionFormat()
Validate version format (semver X.Y.Z or CalVer YYYY.M.patch, with optional pre-release). SignatureisCalVer()
Check if a version string is CalVer format. SignaturecalculateNewVersion()
Calculate new version from current + bump type. SignaturegetVersionBumpConfig()
Get version bump configuration, mapping config field names to VersionBumpTarget. SignatureisVersionBumpConfigured()
Check if version bump is configured. SignaturebumpVersionFromConfig()
Bump version in all configured files. SignatureprepareRelease()
Prepare a release (create a release manifest entry). T4788 SignaturegenerateReleaseChangelog()
Generate changelog for a release. T4788 SignaturelistManifestReleases()
List all releases. T4788 SignatureshowManifestRelease()
Show release details. T4788 SignaturecommitRelease()
Mark release as committed (metadata only). T4788 SignaturetagRelease()
Mark release as tagged (metadata only). T4788 SignaturerunReleaseGates()
Run release validation gates. T4788 T5586 SignaturecancelRelease()
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 SignaturerollbackRelease()
Rollback a release. T4788 SignaturepushRelease()
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 SignaturemarkReleasePushed()
Update release status after push, with optional provenance fields. T4788 T5580 SignaturemigrateReleasesJsonToSqlite()
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 SignaturegradeSession()
Grade a session by sessionId using the 5-dimension behavioral rubric. SignaturereadGrades()
Read past grade results from .cleo/metrics/GRADES.jsonl SignaturehandleSessionStart()
Handle onSessionStart - capture initial session context SignaturehandleSessionEnd()
Handle onSessionEnd - capture session summary SignaturehandleToolStart()
Handle onToolStart (maps to task.start in CLEO) SignaturehandleToolComplete()
Handle onToolComplete (maps to task.complete in CLEO) SignaturehandleError()
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. SignaturehandleFileChange()
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. SignaturehandlePromptSubmit()
Handle onPromptSubmit - optionally capture prompt events to BRAIN No-op by default. Set CLEO_BRAIN_CAPTURE_MCP=true to enable. SignaturehandleResponseComplete()
Handle onResponseComplete - optionally capture response events to BRAIN No-op by default. Set CLEO_BRAIN_CAPTURE_MCP=true to enable. SignaturerecordAssumption()
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. SignaturelinkMemoryToTask()
Link a memory entry to a task. T5156 SignatureunlinkMemoryFromTask()
Remove a link between a memory entry and a task. T5156 SignaturegetTaskLinks()
Get all memory entries linked to a specific task. T5156 SignaturegetMemoryLinks()
Get all tasks linked to a specific memory entry. T5156 SignaturebulkLink()
Batch create multiple links at once. T5156 SignaturegetLinkedDecisions()
Get all decisions linked to a task. Convenience method that fetches full decision rows. T5156 SignaturegetLinkedPatterns()
Get all patterns linked to a task. Convenience method that fetches full pattern rows. T5156 SignaturegetLinkedLearnings()
Get all learnings linked to a task. Convenience method that fetches full learning rows. T5156 SignatureextractMemoryItems()
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’ SignaturepersistSessionMemory(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| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
sessionId | string | The session that just ended |
debrief | DebriefData | null | undefined | Rich debrief data from sessionComputeDebrief() |
getSessionMemoryContext(projectRoot, scope, options)
Retrieve session memory for a given scope. Used by briefing/handoff to enrich response with brain context. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory |
scope | : \{ type: string; epicId?: string | undefined; rootTaskId?: string | undefined; \} | undefined | Session scope for filtering (epic:T### or global) |
options | : \{ limit?: number | undefined; includeDecisions?: boolean | undefined; includePatterns?: boolean | undefined; \} | undefined | Retrieval options |
depsReady(depends, taskLookup)
Check if all dependencies of a task are satisfied. Signature| Name | Type | Description |
|---|---|---|
depends | string[] | undefined | Array of dependency task IDs (may be undefined/empty) |
taskLookup | ReadonlyMap<string | Map from task ID to a task-like object with at least status: string |
computeBriefing()
Compute the complete session briefing. Aggregates data from all 6+ sources. SignaturefindSessions(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| Name | Type | Description |
|---|---|---|
accessor | DataAccessor | DataAccessor for loading sessions |
params | : FindSessionsParams | undefined | Optional filters (status, scope, query, limit) |
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. SignaturecleanupSessions()
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 fromretention.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. SignaturegetSessionHistory()
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. SignatureshowSession()
Show a specific session. Looks in active sessions first, then session history. Throws CleoError if not found. SignaturegetSessionStats()
Compute session statistics, optionally for a specific session. Throws CleoError if a specific session is requested but not found. SignaturesuspendSession()
Suspend an active session. Sets status to ‘suspended’ and records the reason. Throws if session not found or not active. SignatureswitchSession()
Switch to a different session. Suspends the current active session and activates the target. Throws if session not found or archived. SignatureSessionView
Signaturefrom()
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()
SignaturedetectRuntimeProviderContext()
SignatureresetRuntimeProviderContextCache()
SignatureparseScope()
Parse a scope string into a SessionScope. T4463 SignaturereadSessions()
Read sessions from accessor or JSON file. T4463 SignaturesaveSessions()
Save sessions via accessor or JSON file. T4463 SignaturestartSession()
Start a new session. T4463 SignatureendSession()
End a session. T4463 SignaturesessionStatus()
Get current session status. T4463 SignatureresumeSession()
Resume an existing session. T4463 SignaturelistSessions()
List sessions with optional filtering. T4463 SignaturegcSessions()
Garbage collect old sessions. Marks orphaned sessions that have been active too long. T4463 SignaturearchiveSticky(id, projectRoot)
Archive a sticky note. Signature| Name | Type | Description |
|---|---|---|
id | string | Sticky note ID |
projectRoot | string | Project root path |
convertStickyToTask(stickyId, taskTitle, projectRoot)
Convert a sticky note to a task. Signature| Name | Type | Description |
|---|---|---|
stickyId | string | Sticky note ID |
taskTitle | string | undefined | Optional task title (defaults to sticky content) |
projectRoot | string | Project root path |
convertStickyToMemory(stickyId, memoryType, projectRoot)
Convert a sticky note to a memory observation. Signature| Name | Type | Description |
|---|---|---|
stickyId | string | Sticky note ID |
memoryType | string | undefined | Optional memory type |
projectRoot | string | Project root path |
convertStickyToTaskNote(stickyId, taskId, projectRoot)
Convert a sticky note to a task note. Signature| Name | Type | Description |
|---|---|---|
stickyId | string | Sticky note ID |
taskId | string | Target task ID |
projectRoot | string | Project root path |
convertStickyToSessionNote(stickyId, sessionId, projectRoot)
Convert a sticky note to a session note. Signature| Name | Type | Description |
|---|---|---|
stickyId | string | Sticky note ID |
sessionId | string | undefined | Optional target session ID (defaults to current active session) |
projectRoot | string | Project root path |
generateStickyId(projectRoot)
Generate the next sticky note ID. Finds the highest existing SN-XXX ID and increments. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root path |
addSticky(params, projectRoot)
Create a new sticky note. Signature| Name | Type | Description |
|---|---|---|
params | CreateStickyParams | Creation parameters |
projectRoot | string | Project root path |
listStickies(params, projectRoot)
List sticky notes with optional filters. Signature| Name | Type | Description |
|---|---|---|
params | ListStickiesParams | Filter parameters |
projectRoot | string | Project root path |
purgeSticky(id, projectRoot)
Purge (permanently delete) a sticky note. Signature| Name | Type | Description |
|---|---|---|
id | string | Sticky note ID |
projectRoot | string | Project root path |
getSticky(id, projectRoot)
Get a sticky note by ID. Signature| Name | Type | Description |
|---|---|---|
id | string | Sticky note ID (e.g., “SN-042”) |
projectRoot | string | Project root path |
archiveTasks()
Archive completed (and optionally cancelled) tasks. Moves them from active task data to archive. T4461 SignaturedeleteTask()
Delete a task (soft delete - moves to archive). T4461 SignatureCleo
Signatureinit()
forProject()
calculateExportChecksum()
Calculate SHA-256 checksum for export integrity (truncated to 16 hex chars). SignatureverifyExportChecksum()
Verify export package checksum. SignaturebuildIdMap()
Build ID map from tasks. SignaturebuildRelationshipGraph()
Build relationship graph from tasks. SignaturebuildExportPackage()
Build a complete export package. SignatureexportSingle()
Export a single task. SignatureexportSubtree()
Export a subtree (task + all descendants). SignatureexportTasksPackage()
Export tasks to a portable cross-project package. SignaturegetCostHint()
Determine cost hint for an operation based on domain and operation name. SignaturegroupOperationsByDomain(ops)
Group operations by domain into a compact format. Signature| Name | Type | Description |
|---|---|---|
ops | HelpOperationDef[] | Operations filtered to the requested tier |
buildVerboseOperations(ops)
Build verbose operation entries with cost hints. Signature| Name | Type | Description |
|---|---|---|
ops | HelpOperationDef[] | Operations filtered to the requested tier |
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| Name | Type | Description |
|---|---|---|
allOperations | HelpOperationDef[] | The full operation registry |
tier | number | The tier level to filter to (0, 1, or 2) |
verbose | boolean | Whether to return full operation objects or compact grouped format |
getNextAvailableId()
Get the next available task ID number from existing tasks. SignaturegenerateRemapTable()
Generate a remap table for importing tasks. Maps source task IDs to new sequential IDs starting from nextAvailable. SignaturevalidateRemapTable()
Validate that a remap table is complete and consistent. SignatureremapTaskId()
Remap a single task ID, returning original if not in table. SignatureremapTaskReferences()
Remap all ID references in a task. SignaturedetectDuplicateTitles()
Detect duplicate titles between import and target. SignatureresolveDuplicateTitle()
Resolve duplicate title by appending suffix. SignatureimportTasksPackage()
Import tasks from a cross-project export package with ID remapping. SignaturefindAdrs()
SignaturelistAdrs()
List ADRs from .cleo/adrs/ directory with optional status filter SignatureshowAdr()
Retrieve a single ADR by ID (e.g., ‘ADR-007’) SignaturevalidateAllAdrs()
Validate all ADRs in .cleo/adrs/ against the schema SignatureproviderList()
List all registered providers. T4332 SignatureproviderGet()
Get a single provider by ID or alias. T4332 SignatureproviderDetect()
Detect all providers installed on the system. T4332 SignatureproviderInstalled()
Get providers that are installed on the system. T4332 SignatureproviderCount()
Get count of registered providers. T4332 SignatureregistryVersion()
Get CAAMP registry version. T4332 SignaturemcpList()
List MCP servers for a specific provider. T4332 SignaturemcpListAll()
List MCP servers across all installed providers. T4332 SignaturemcpInstall()
Install an MCP server to a provider’s config. T4332 SignaturemcpRemove()
Remove an MCP server from a provider’s config. T4332 SignaturemcpConfigPath()
Resolve the config file path for a provider. T4332 SignatureinjectionCheck()
Check injection status for a single file. T4332 SignatureinjectionCheckAll()
Check injection status across all providers. T4332 SignatureinjectionUpdate()
Inject or update content in a single file. T4332 SignatureinjectionUpdateAll()
Inject content to all providers’ instruction files. T4332 SignaturebatchInstallWithRollback()
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 SignaturedualScopeConfigure()
Configure a provider at both global and project scope simultaneously. Used during init to set up MCP configs in both scopes atomically. T4705 T4663 SignaturecheckProviderCapability(provider, capabilityPath)
Check if provider supports a specific capability Signature| Name | Type | Description |
|---|---|---|
provider | string | Provider | Provider object or ID |
capabilityPath | string | Dot notation path (e.g., ‘spawn.supportsSubagents’) |
checkProviderCapabilities()
Check multiple capabilities at once SignaturegetComplianceJsonlPath()
Resolve COMPLIANCE.jsonl path for a project root. SignaturereadComplianceJsonl()
Read COMPLIANCE.jsonl entries. Invalid JSON lines are skipped to preserve append-only log resilience. SignatureappendComplianceJsonl()
Append one entry to COMPLIANCE.jsonl, creating directories as needed. SignaturegetComplianceSummary()
Get compliance summary. SignaturelistComplianceViolations()
List compliance violations. SignaturegetComplianceTrend()
Get compliance trend. SignatureauditEpicCompliance()
Audit epic compliance. SignaturesyncComplianceMetrics()
Sync compliance metrics to a summary file. SignaturegetSkillReliability()
Get skill reliability stats. SignaturegetValueMetrics()
Get value metrics (T2833). SignaturegetContextStatus()
Get context status. SignaturecheckContextThreshold()
Check context threshold (returns exit code info). SignaturelistContextSessions()
List all context state files. SignatureinjectTasks()
Inject tasks for external consumption. SignaturecollectDiagnostics()
Collect system diagnostics for bug reports. SignatureformatDiagnosticsTable()
Format diagnostics as markdown table. SignatureparseIssueTemplates()
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) SignaturegetTemplateConfig()
Get template configuration - tries live parse, cache, then fallback. SignaturegetTemplateForSubcommand()
Get the template for a specific subcommand (bug, feature, etc.). SignaturecacheTemplates()
Cache parsed templates to .cleo/issue-templates.json. SignaturevalidateLabelsExist()
Validate that required labels exist (informational). SignaturebuildIssueBody()
Build structured issue body with template sections. SignaturecheckGhCli()
Check that gh CLI is installed and authenticated. SignatureaddIssue()
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”) SignatureapplyTemporalDecay(projectRoot, options)
Apply temporal decay to brain_learnings confidence values. Entries older thanolderThanDays 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
| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory for brain.db resolution |
options | : \{ decayRate?: number | undefined; olderThanDays?: number | undefined; \} | undefined | Decay configuration |
consolidateMemories(projectRoot, options)
Consolidate old observations by keyword similarity. Groups observations older thanolderThanDays 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
| Name | Type | Description |
|---|---|---|
projectRoot | string | Project root directory for brain.db resolution |
options | : \{ olderThanDays?: number | undefined; minClusterSize?: number | undefined; \} | undefined | Consolidation configuration |
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 SignatureaddResearch()
Add a research entry. T4465 SignatureshowResearch()
Show a specific research entry. T4465 SignaturelistResearch()
List research entries with optional filtering. T4465 SignaturependingResearch()
List pending research entries. T4465 SignaturelinkResearch()
Link a research entry to a task. T4465 SignatureupdateResearch()
Update research findings. T4465 SignaturestatsResearch()
Get research statistics. T4474 SignaturelinksResearch()
Get research entries linked to a specific task. T4474 SignaturearchiveResearch()
Archive old research entries by status. Moves ‘complete’ entries older than a threshold to an archive, or returns summary of archivable entries. T4474 SignaturereadManifest()
Read manifest entries from MANIFEST.jsonl. T4465 SignatureappendManifest()
Append a manifest entry. T4465 SignaturequeryManifest()
Query manifest entries. T4465 SignaturereadExtendedManifest()
Read all manifest entries as extended entries. T4787 SignaturefilterManifestEntries()
Filter manifest entries by criteria. T4787 SignatureshowManifestEntry()
Show a manifest entry by ID with optional file content. T4787 SignaturesearchManifest()
Search manifest entries by text with relevance scoring. T4787 SignaturependingManifestEntries()
Get pending manifest entries (partial, blocked, or needing followup). T4787 SignaturemanifestStats()
Get manifest-based research statistics. T4787 SignaturelinkManifestEntry()
Link a manifest entry to a task (adds taskId to linked_tasks array). T4787 SignatureappendExtendedManifest()
Append an extended manifest entry. Validates required fields before appending. T4787 SignaturearchiveManifestEntries()
Archive manifest entries older than a date. T4787 SignaturefindContradictions()
Find manifest entries with overlapping topics but conflicting key_findings. T4787 SignaturefindSuperseded()
Identify research entries replaced by newer work on same topic. T4787 SignaturereadProtocolInjection()
Read protocol injection content for a given protocol type. T4787 SignaturecompactManifest()
Compact MANIFEST.jsonl by removing duplicate/stale entries. T4787 SignaturevalidateManifestEntries()
Validate research entries for a task. T4787 SignatureensureMetricsDir()
Ensure metrics directory exists, returning its path. SignaturegetCompliancePath()
Get compliance log path. SignaturegetViolationsPath()
Get violations log path. SignaturegetSessionsMetricsPath()
Get sessions metrics log path. SignatureisoTimestamp()
Generate ISO 8601 UTC timestamp. SignatureisoDate()
Generate ISO 8601 date only. SignaturereadJsonlFile()
Read a JSONL file into an array of parsed objects. SignaturegetComplianceSummaryBase()
Get compliance summary from log file. SignatureisOtelEnabled()
Check if OTel telemetry is enabled. SignaturegetOtelSetupCommands()
Get environment variable commands for OTel capture setup. SignatureparseTokenMetrics()
Parse OTel token metrics from collected data. SignaturegetSessionTokens()
Get aggregated token counts from OTel data. SignaturerecordSessionStart()
Record token counts at session start. SignaturerecordSessionEnd()
Record token counts at session end. SignaturecompareSessions()
Compare token usage between two sessions. SignaturegetTokenStats()
Get statistics about token usage across sessions. SignaturelogABEvent()
Log an A/B test event. SignaturestartABTest()
Start an A/B test session. SignatureendABTest()
End an A/B test session with summary. SignaturegetABTestResults()
Get results for a specific test variant. SignaturelistABTests()
List all A/B tests. SignaturecompareABTest()
Compare two variants of the same test. SignaturegetABTestStats()
Get aggregate statistics of all A/B tests. SignaturesyncMetricsToGlobal()
Sync project metrics to global aggregation file. SignaturegetProjectComplianceSummary()
Get compliance summary for the current project. SignaturegetGlobalComplianceSummary()
Get compliance summary across all projects. SignaturegetComplianceTrend()
Get compliance trend over time. SignaturegetSkillReliability()
Get reliability stats per skill/agent. SignaturelogSessionMetrics()
Log session metrics to SESSIONS.jsonl. SignaturegetSessionMetricsSummary()
Get summary of session metrics. SignatureisValidEnumValue()
Validate that a value is a member of a given enum. SignatureestimateTokens()
Estimate token count from text. ~4 characters per token. SignatureestimateTokensFromFile()
Estimate token count from a file. SignaturelogTokenEvent()
Log a token usage event to the JSONL file. SignaturetrackFileRead()
Track a file read with token estimate. SignaturetrackManifestQuery()
Track a manifest query (partial read). SignaturetrackSkillInjection()
Track skill injection with tokens. SignaturetrackPromptBuild()
Track final prompt size. SignaturetrackSpawnOutput()
Track subagent output tokens. SignaturetrackSpawnComplete()
Track complete spawn cycle (prompt + output). SignaturestartTokenSession()
Start tracking tokens for a session. SignatureendTokenSession()
End token tracking session with summary. SignaturegetTokenSummary()
Get token usage summary for a time period. SignaturecompareManifestVsFull()
Compare manifest vs full file token usage strategies. SignaturegetTrackingStatus()
Get tracking status. SignaturecomputeChecksum(filePath)
Compute SHA-256 checksum of a file. Signature| Name | Type | Description |
|---|---|---|
filePath | string | Path to the file |
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| Name | Type | Description |
|---|---|---|
sourcePath | string | Path to the source database file |
backupPath | string | Path to the backup file |
compareChecksums(filePath1, filePath2)
Quick checksum comparison without SQLite verification. Use when you only need to compare file contents. Signature| Name | Type | Description |
|---|---|---|
filePath1 | string | First file path |
filePath2 | string | Second file path |
MigrationLogger
Structured logger for migration operations SignaturegetLevelPriority()
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. SignaturereadMigrationLog()
Read and parse a migration log file. SignaturelogFileExists()
Check if a log file exists and is readable. SignaturegetLatestMigrationLog()
Get the most recent migration log file for a cleo directory. SignaturecheckStorageMigration()
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. SignaturecreateMigrationState(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| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
sourceFiles | : \{ todoJson?: SourceFileInfo | undefined; sessionsJson?: SourceFileInfo | undefined; archiveJson?: SourceFileInfo | undefined; \} | undefined | Optional pre-computed source file info |
updateMigrationState(cleoDir, updates)
Update migration state with partial updates. Merges updates with existing state and writes atomically. Automatically adds timestamp to phase transitions. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
updates | Partial<MigrationState> | Partial state updates to apply |
updateMigrationPhase(cleoDir, phase)
Update just the migration phase. Convenience wrapper for common phase transition. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
phase | MigrationPhase | New phase |
updateMigrationProgress(cleoDir, progress)
Update progress counters during import. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
progress | Partial<MigrationProgress> | Progress updates (only changed counters needed) |
addMigrationError(cleoDir, error)
Add an error to the migration state. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
error | string | Error message |
addMigrationWarning(cleoDir, warning)
Add a warning to the migration state. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
warning | string | Warning message |
loadMigrationState(cleoDir)
Load existing migration state. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
isMigrationInProgress(cleoDir)
Check if a migration is in progress. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
canResumeMigration(cleoDir)
Check if migration can be resumed. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
completeMigration(cleoDir)
Mark migration as complete. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
failMigration(cleoDir, error)
Mark migration as failed with error details. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
error | string | Primary error message |
clearMigrationState(cleoDir)
Clear migration state file. Safe to call even if state doesn’t exist. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory T4726 |
getMigrationSummary(cleoDir)
Get a summary of migration state for display. Signature| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
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| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
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| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to the .cleo directory |
formatValidationResult(result)
Format validation result for human-readable output. Signature| Name | Type | Description |
|---|---|---|
result | JsonValidationResult | Validation result |
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| Name | Type | Description |
|---|---|---|
cleoDir | string | Path to .cleo directory |
jsonTaskCount | number | Number of tasks found in JSON |
detectVersion()
Detect schema version from a data file. T4468 SignaturecompareSemver()
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 SignaturegetMigrationStatus()
Get migration status for all data files. T4468 SignaturerunMigration()
Run migrations on a data file. T4468 SignaturerunAllMigrations()
Run all pending migrations. T4468 SignatureinvalidateGraphCache()
Invalidate the in-memory graph cache. SignaturebuildGlobalGraph()
Build the global dependency graph from all registered projects. Uses checksum-based caching to avoid unnecessary rebuilds. SignaturenexusDeps()
Show dependencies for a task across projects. Supports forward (what this depends on) and reverse (what depends on this) lookups. SignatureresolveCrossDeps()
Resolve an array of dependencies (local or cross-project). SignaturecriticalPath()
Calculate the critical path across project boundaries. Returns the longest dependency chain in the global graph. SignatureblockingAnalysis()
Analyze the blocking impact of a task across all projects. Uses BFS to find all direct and transitive dependents. SignatureorphanDetection()
Detect orphaned cross-project dependencies. Finds tasks with dependency references to projects or tasks that don’t exist. SignaturecompareLevels()
Compare two pino levels numerically. Returns negative if a b, 0 if equal, positive if a b. SignaturematchesFilter()
Check if a single entry matches the filter criteria. All specified fields must match (AND logic). SignaturefilterEntries()
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. Signaturepaginate()
Apply pagination (limit/offset) to a result set. SignatureisValidLevel()
Validate that a string is a valid PinoLevel. SignatureparseLogLine()
Parse a single JSONL line into a PinoLogEntry. Returns null for empty lines, non-JSON, or lines missing required fields. SignatureparseLogLines()
Parse multiple JSONL lines into PinoLogEntry array. Skips malformed lines. SignaturegetProjectLogDir()
Get the project log directory path. Uses getLogDir() from logger if available, falls back to config-based resolution. SignaturegetGlobalLogDir()
Get the global log directory path (~/.cleo/logs/). SignaturediscoverLogFiles()
Discover all log files in the specified scope. Returns file info sorted by date (newest first). SignaturereadLogFileLines()
Read all lines from a log file synchronously. Returns raw JSON strings (one per line). Suitable for small-to-medium files. SignaturestreamLogFileLines()
Create an async iterable over lines of a log file. Suitable for large files — does not load entire file into memory. SignaturequeryLogs()
High-level query: discover files, parse, filter, paginate. Convenience wrapper combining all three layers. SignaturestreamLogs()
Stream-based query for large log datasets. Yields matching entries one at a time. Respects limit. Does not support offset (streaming is forward-only). SignaturegetLogSummary()
Get a summary of log activity (counts by level, date range, subsystems). Reads all discovered files but does not return individual entries. SignaturegetOtelStatus()
Get token tracking status. SignaturegetOtelSummary()
Get combined token usage summary. SignaturegetOtelSessions()
Get session-level token data. SignaturegetOtelSpawns()
Get spawn-level token data. SignaturegetRealTokenUsage()
Get real token usage from Claude Code API. SignatureclearOtelData()
Clear token tracking data with backup. SignaturelistPhases()
List all phases with status summaries. T5326 SignatureshowPhase()
Show phase details by slug or current phase. T5326 SignaturegetCurrentBranch()
Get the current branch name in .cleo/.git. T4884 SignatureaddRemote()
Add a git remote to .cleo/.git. T4884 SignatureremoveRemote()
Remove a git remote from .cleo/.git. T4884 SignaturelistRemotes()
List configured remotes in .cleo/.git. T4884 Signaturepush()
Push .cleo/.git to a remote. T4884 Signaturepull()
Pull from a remote into .cleo/.git. Uses rebase strategy to maintain clean history. T4884 SignaturegetSyncStatus()
Get the sync status between local .cleo/.git and remote. T4884 SignaturegetRoadmap()
Get roadmap from pending epics and CHANGELOG history. SignaturegetOperationMode()
Lookup the execution mode for a specific operation SignaturecanRunNatively()
Check if an operation can run natively (without CLI) SignaturerequiresCLI()
Check if an operation requires CLI SignaturegetNativeOperations()
Get all native-capable operations for a domain SignaturegenerateCapabilityReport()
Generate a capability report for system.doctor SignaturegetCapabilityMatrix()
Get the full capability matrix (for testing/introspection) SignaturefindHighestId()
Find the highest existing task ID number SignaturegenerateNextIdFromSet()
Generate the next ID given an explicit set of existing IDs. Useful when caller has already loaded task data. SignatureisValidTaskId()
Validate that a task ID matches the expected format SignaturenormalizeTaskId()
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. SignatureSecurityError
Security validation error thrown when input fails sanitization SignaturesanitizeTaskId()
Sanitize and validate a task ID SignaturesanitizePath()
Sanitize and validate a file path SignaturesanitizeContent()
Sanitize content string SignaturevalidateEnum()
Validate that a value is in an allowed enum set SignatureRateLimiter
In-memory sliding window rate limiter Signaturecheck()
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. SignaturesanitizeParams()
Sanitize all params in a request before routing SignatureClaudeCodeTransport
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. Signatureregister()
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. Signatureregister()
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. SignaturegetSkillSearchPaths()
Build the CAAMP skill search paths in priority order. Uses CAAMP’s canonical path functions for standard locations. T4516 SignaturegetSkillsDir()
Get the primary skills directory (app-embedded). T4516 SignaturegetSharedDir()
Get the shared skills resources directory. T4516 SignaturemapSkillName()
Map a user-friendly skill name to the canonical ct-prefixed directory name. Supports: UPPER-CASE, lower-case, with/without ct- prefix. T4516 SignaturelistCanonicalSkillNames()
List all known canonical skill names (unique values from the map). T4516 SignatureparseFrontmatter()
Parse YAML-like frontmatter from a SKILL.md file. Handles the --- delimited header with key: value pairs. T4516 SignaturediscoverSkill()
Discover a single skill from a directory. Tries CAAMP’s parseSkillFile first, falls back to local parsing. T4516 SignaturediscoverSkillsInDir()
Discover all skills in a single directory. Scans for subdirectories containing SKILL.md. T4516 SignaturediscoverAllSkills()
Discover all skills across CAAMP search paths. Returns skills in priority order (earlier paths take precedence). T4516 SignaturefindSkill()
Find a specific skill by name across all search paths. T4516 SignaturetoSkillSummary()
Convert a Skill to a lightweight SkillSummary. T4516 SignaturegenerateManifest()
Generate a skill manifest from discovered skills. T4516 SignatureresolveTemplatePath()
Resolve a skill template path (SKILL.md) by name. T4516 SignaturegetAgentsDir()
Get the agents directory path. T4518 SignatureparseAgentConfig()
Parse an AGENT.md file into an AgentConfig. AGENT.md uses the same YAML frontmatter format as SKILL.md. T4518 SignatureloadAgentConfig()
Load agent configuration by name. Searches in the agents/ directory. T4518 SignaturegetSubagentConfig()
Get the cleo-subagent configuration (universal executor). T4518 SignatureagentExists()
Check if an agent definition exists. T4518 SignatureinstallAgent()
Install a single agent via symlink. T4518 SignatureinstallAllAgents()
Install all agents from the project agents/ directory. T4518 SignatureuninstallAgent()
Uninstall a single agent by removing its symlink. T4518 SignaturegetRegistryPath()
Get the agent registry file path. T4518 SignaturereadRegistry()
Read the agent registry, creating if needed. T4518 SignaturesaveRegistry()
Save the agent registry. T4518 SignatureregisterAgent()
Register an agent in the registry. T4518 SignatureunregisterAgent()
Unregister an agent from the registry. T4518 SignaturegetAgent()
Get an agent from the registry by name. T4518 SignaturelistAgents()
List all registered agents. T4518 SignaturesyncRegistry()
Scan the agents/ directory and register all found agents. T4518 SignatureloadPlaceholders()
Load token definitions from placeholders.json. T4521 SignaturebuildDefaults()
Build the full default values map (merging placeholders.json with hardcoded defaults). T4521 SignaturevalidateTokenValue()
Validate a single token value against its pattern. T4521 SignaturevalidateRequired()
Validate all required tokens are present and valid. T4521 SignaturevalidateAllTokens()
Validate all tokens in a values map (required + optional). T4521 SignatureinjectTokens()
Inject token values into a template string. Replaces all TOKEN_NAME patterns with corresponding values. Unresolved tokens are left as-is (for debugging). T4521 SignaturehasUnresolvedTokens()
Check if a template has unresolved tokens after injection. T4521 SignatureloadAndInject()
Load a skill template and inject tokens. T4521 SignaturesetFullContext()
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 SignatureautoDispatch()
Auto-dispatch a task to the most appropriate skill. Tries strategies in priority order: label - catalog - type - keyword - fallback. T4517 SignaturedispatchExplicit()
Dispatch with explicit skill override. Verifies the skill exists before returning. T4517 SignaturegetProtocolForDispatch()
Get the protocol type for a dispatch result. T4517 SignatureprepareSpawnContext()
Prepare spawn context for a dispatched skill. Returns the skill name and protocol needed for token injection. T4517 SignatureprepareSpawnMulti()
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 SignatureloadProtocolBase()
Load the subagent protocol base content. T4521 SignaturebuildTaskContext()
Build task context block for injection into a subagent prompt. T4521 SignaturefilterProtocolByTier()
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 SignatureinjectProtocol()
Inject the subagent protocol into skill content. Composes: skill content + protocol base + task context. T4521 SignatureorchestratorSpawnSkill()
Full orchestrator spawn workflow (skill-based). High-level function that loads the skill, injects protocol, and returns the prompt. T4521 SignatureprepareTokenValues()
Prepare standard token values for a task spawn. T4521 SignatureinstallSkill()
Install a single skill via CAAMP. SignaturegenerateContributionId()
Generate a unique contribution ID. T4520 SignaturevalidateContributionTask()
Validate that a task is suitable for contribution protocol. T4520 SignaturegetContributionInjection()
Generate the contribution injection block for a subagent prompt. T4520 SignaturedetectConflicts()
Detect conflicts between two sets of decisions. T4520 SignaturecomputeConsensus()
Compute weighted consensus from multiple agent decisions. T4520 SignaturecreateContributionManifestEntry()
Create a manifest entry for a contribution. T4520 SignatureensureOutputs()
Ensure agent outputs directory and manifest file exist. T4520 SignaturereadManifest()
Read all manifest entries. T4520 SignatureappendManifest()
Append a manifest entry (atomic JSONL append). T4520 SignaturefindEntry()
Find a manifest entry by ID. T4520 SignaturefilterEntries()
Filter manifest entries by criteria. T4520 SignaturegetPendingFollowup()
Get entries with pending follow-ups. T4520 SignaturegetFollowupTaskIds()
Get unique follow-up task IDs from all manifest entries. T4520 SignaturetaskHasResearch()
Check if a task has linked research. T4520 SignaturearchiveEntry()
Archive a manifest entry (move to archive status). T4520 SignaturerotateManifest()
Rotate manifest by archiving old entries. T4520 SignatureisCacheFresh()
Check if the cached manifest is fresh (within TTL). T4520 SignatureinvalidateCache()
Invalidate the cache (delete the cached manifest). T4520 SignatureresolveManifest()
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 SignatureregenerateCache()
Force regenerate the cache. T4520 SignatureloadConfig()
Load SkillsMP configuration from skillsmp.json. T4521 SignaturesearchSkills()
Search the skills marketplace. Delegates to CAAMP’s searchSkills for the actual API call. T4521 SignaturegetSkill()
Get a specific skill from the marketplace. Uses CAAMP’s MarketplaceClient for retrieval. T4521 SignatureisEnabled()
Check if the marketplace is enabled and reachable. T4521 SignaturebuildPrompt()
Build a fully-resolved prompt for spawning a subagent. T4519 Signaturespawn()
Generate full spawn command with metadata. T4519 SignaturecanParallelize()
Check if tasks can be spawned in parallel (no inter-dependencies). T4519 SignaturespawnBatch()
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 SignaturegetThresholds()
Get orchestrator context thresholds from config or defaults. T4519 SignaturegetContextState()
Read the current context state from session-aware files. T4519 SignaturesessionInit()
Initialize orchestrator session state. Determines the recommended action based on current state. T4519 SignatureshouldPause()
Check if orchestrator should pause based on context usage. T4519 SignatureanalyzeDependencies()
Analyze dependency graph and compute execution waves. T4519 SignaturegetNextTask()
Get the next task ready to spawn for an epic. T4519 SignaturegetReadyTasks()
Get all tasks ready to spawn in parallel (no inter-dependencies). T4519 SignaturegenerateHitlSummary()
Generate a Human-in-the-Loop summary for session handoff. T4519 SignaturevalidateSubagentOutput()
Validate a subagent’s manifest entry for protocol compliance. T4519 SignaturevalidateManifestIntegrity()
Validate the entire manifest file integrity. T4519 SignatureverifyCompliance()
Verify previous agent completed protocol compliance before spawning next. T4519 SignaturevalidateOrchestratorCompliance()
Validate orchestrator compliance (post-hoc behavioral checks). T4519 SignaturegetSkillSearchPaths()
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 SignatureresolveSkillPath()
Resolve a skill directory containing SKILL.md. Searches all paths from getSkillSearchPaths() in priority order. First match wins. T4552 SignatureresolveProtocolPath()
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 SignatureresolveSharedPath()
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 SignaturegetSkillSourceType()
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 SignatureformatIsoDate(inputDate)
Format a date string in ISO 8601 format. Converts a YYYY-MM-DD date string to a full ISO 8601 timestamp. Signature| Name | Type | Description |
|---|---|---|
inputDate | string | Date string in YYYY-MM-DD format |
- 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. SignatureisValidIsoDate()
Validate that a string is a valid ISO 8601 date. T4552 SignatureformatDateYMD()
Format a Date object to a YYYY-MM-DD string. T4552 SignaturevalidateSkill()
Validate a skill directory structure and content. T4517 SignaturevalidateSkills()
Validate multiple skills at once. T4517 SignaturevalidateReturnMessage()
Validate a return message against protocol-compliant patterns. T4517 SignaturegetInstalledVersionAsync()
Get the installed version of a skill from CAAMP lock state. SignaturecheckSkillUpdateAsync()
Check if a specific skill needs an update via CAAMP. SignaturecheckAllSkillUpdatesAsync()
Check all installed skills for available updates via CAAMP. SignatureexportSnapshot()
Export current task state to a snapshot. T4882 SignaturewriteSnapshot()
Write a snapshot to a file. T4882 SignaturereadSnapshot()
Read a snapshot from a file. T4882 SignaturegetDefaultSnapshotPath()
Generate a default snapshot file path. T4882 SignatureimportSnapshot()
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 SignatureSpawnAdapterRegistry
Registry to manage spawn adapters. Maintains mappings between adapter IDs, provider IDs, and adapter instances. Supports registration, lookup, and capability-based filtering. Signatureregister()
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| Name | Type | Description |
|---|---|---|
capability | SpawnCapability | The spawn capability to filter by |
hasParallelSpawnProvider()
Check if any provider supports parallel spawn SignatureinitializeSpawnAdapters(manifests)
Initialize spawn adapters dynamically from discovered adapter manifests. Scans all discovered manifests for adapters withcapabilities.supportsSpawn, dynamically imports their spawn provider, and bridges it into the spawn registry. Zero hardcoded adapter names — everything derives from manifests.
Signature
| Name | Type | Description |
|---|---|---|
manifests | AdapterManifest[] | Discovered adapter manifests (from AdapterManager.discover()) |
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. SignaturegetProjectStats()
Get project statistics. SignaturerankBlockedTask()
Compute a ranking score for a blocked task. Higher score = more urgent = sort first. SignaturegetDashboard()
Get project dashboard data. SignaturegetCompletionHistory()
Get completion history data. SignaturefilterByDate()
Filter tasks by date range on archivedAt. SignaturesummaryReport()
Generate summary statistics. SignaturebyPhaseReport()
Group tasks by phase with cycle time averages. SignaturebyLabelReport()
Group tasks by label frequency. SignaturebyPriorityReport()
Group tasks by priority with cycle time averages. SignaturecycleTimesReport()
Compute cycle time statistics with distribution buckets. SignaturetrendsReport()
Compute archive trends by day and month. SignatureanalyzeArchive()
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. SignaturegetArchiveStats()
Get archive statistics. SignatureauditData()
Audit data integrity. SignaturecreateBackup()
Create a backup of CLEO data files. SignaturerestoreBackup()
Restore from a backup. SignaturecleanupSystem()
Cleanup stale data (sessions, backups, logs). SignaturewriteJsonFileAtomic(filePath, data, indent)
Write a JSON file atomically with backup rotation. Pattern: write temp - backup original - rename temp to target Signature| Name | Type | Description |
|---|---|---|
filePath | string | Target file path |
data | T | Data to serialize as JSON |
indent | : number | JSON indentation (default: 2 spaces) |
readJsonFile(filePath)
Read a JSON file, returning parsed content or null if not found. Signature| Name | Type | Description |
|---|---|---|
filePath | string | Path to the JSON file |
getDataPath(projectRoot, filename)
Get the path to a CLEO data file within a project root. Signature| Name | Type | Description |
|---|---|---|
projectRoot | string | Root directory of the project |
filename | string | Filename within .cleo/ directory |
resolveProjectRoot()
Resolve the project root directory. Checks CLEO_ROOT env, then falls back to cwd. SignaturewithLock(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| Name | Type | Description |
|---|---|---|
filePath | string | File to lock and modify |
transform | (current: T | null | Function that receives current data and returns new 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. SignaturewithMultiLock(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| Name | Type | Description |
|---|---|---|
filePaths | string[] | Files to lock |
operation | ( | Function to execute while locks are held |
isProjectInitialized()
Check if a CLEO project directory exists at the given path SignaturelistBackups()
List backup files for a given data file SignaturedetectPlatform()
Detect the current platform. SignaturecommandExists()
Check if a command exists on PATH. SignaturerequireTool()
Require a tool to be available, returning an error message if missing. SignaturecheckRequiredTools()
Check all required tools. SignaturegetIsoTimestamp()
Get ISO 8601 UTC timestamp. SignatureisoToEpoch()
Convert ISO timestamp to epoch seconds. SignaturedateDaysAgo()
Get ISO date for N days ago. SignaturegetFileSize()
Get file size in bytes. SignaturegetFileMtime()
Get file modification time as ISO string. SignaturegenerateRandomHex()
Generate N random hex characters. Signaturesha256()
Compute SHA-256 checksum of a string. SignaturecreateTempFilePath()
Create a temporary file path. SignaturegetNodeVersionInfo()
Get Node.js version info. SignaturegetNodeUpgradeInstructions()
Get platform-specific Node.js upgrade instructions. Returns actionable install/upgrade guidance based on OS and available tools. SignaturegetSystemInfo()
Gather a snapshot of the host system. This is the SSoT for system information. Use this instead of scatteringprocess.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 SignaturecheckCliVersion()
T4525 SignaturecheckDocsAccessibility()
T4525 SignaturecheckAtReferenceResolution()
T4525 SignaturecheckAgentsMdHub()
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. SignaturecheckRootGitignore()
Check if project root .gitignore is blocking the entire .cleo/ directory. This prevents core CLEO data from being tracked by git. T4641 T4637 SignaturecheckCleoGitignore()
Check if .cleo/.gitignore exists and matches the template. T4700 SignaturecheckVitalFilesTracked()
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 SignaturecheckCoreFilesNotIgnored()
Check that core CLEO files are not being ignored by .gitignore. Usesgit 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 SignaturecheckLegacyAgentOutputs()
Check if any legacy output directories still exist. Delegates detection to the migration/agent-outputs utility. T4700 SignaturecheckCaampMarkerIntegrity()
Verify balanced CAAMP:START/END markers in CLAUDE.md and AGENTS.md. T5153 SignaturecheckAtReferenceTargetExists()
Parse references from AGENTS.md CAAMP block and verify each target file exists. T5153 SignaturecheckTemplateFreshness()
Compare templates/CLEO-INJECTION.md vs ~/.cleo/templates/CLEO-INJECTION.md. T5153 SignaturecheckTierMarkersPresent()
Verify all 3 tier markers exist with matching close tags in deployed template. T5153 SignaturecheckNodeVersion()
Check that Node.js meets the minimum required version. Provides OS-specific upgrade instructions when below minimum. SignaturecheckGlobalSchemaHealth()
Check that global schemas at ~/.cleo/schemas/ are installed and not stale. Delegates to checkGlobalSchemas() from schema-management.ts. SignaturecheckNoLocalSchemas()
Warn if deprecated .cleo/schemas/ directory still exists in the project. Schemas should live in ~/.cleo/schemas/ (global), not in project directories. SignaturecheckJsonSchemaIntegrity()
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. SignaturerunAllGlobalChecks()
Run all global health checks and return results array. T4525 SignaturecalculateHealthStatus()
Calculate overall status from check results. Returns: 0=passed, 50=warning, 52=critical. T4525 SignaturegetSystemHealth()
Run system health checks (SQLite-first per ADR-006). SignaturegetSystemDiagnostics()
Run extended diagnostics with fix suggestions. SignaturecoreDoctorReport()
Run comprehensive doctor diagnostics combining dependency checks, directory checks, data file checks, gitignore checks, and environment info. T4795 SignaturerunDoctorFixes()
Run auto-fix for failed doctor checks by calling the corresponding ensure* functions. Returns a list of fix results for each attempted repair. SignaturestartupHealthCheck(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| Name | Type | Description |
|---|---|---|
projectRoot | : string | undefined | Absolute path to the project root (defaults to cwd) |
generateInjection()
Generate Minimum Viable Injection (MVI) markdown. SignaturegetLabels()
Get all labels with counts and task IDs per label. SignaturegetSystemMetrics()
Get system metrics: token usage, compliance summary, session counts. SignaturegetMigrationStatus()
Check/report schema migration status. SignaturegetRuntimeDiagnostics()
Signaturesafestop()
Safe stop: signal clean shutdown for agents. SignatureuncancelTask()
Uncancel a cancelled task (restore to pending). SignaturedetectCircularDeps()
Detect circular dependencies using DFS. Returns the cycle path if found, empty array otherwise. SignaturewouldCreateCycle()
Check if adding a dependency would create a cycle. SignaturegetBlockedTasks()
Get tasks that are blocked (have unmet dependencies). SignaturegetReadyTasks()
Get tasks that are ready (all dependencies met). SignaturegetDependents()
Get tasks that depend on a given task. SignaturegetDependentIds()
Get dependent IDs. SignaturegetUnresolvedDeps()
Get unresolved dependencies for a task (deps that are not done/cancelled). SignaturevalidateDependencyRefs()
Validate dependencies for missing references. SignaturevalidateDependencies()
Full dependency graph validation. SignaturetopologicalSort()
Topological sort of tasks by dependencies. Returns sorted task IDs or null if cycle detected. SignaturegetTransitiveBlockers()
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. SignaturegetLeafBlockers()
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. SignaturecurrentTask()
Show current task work state. T4462 T4750 SignaturestartTask()
Start working on a specific task. T4462 T4750 SignaturestopTask()
Stop working on the current task. T4462 T4750 SignaturegetWorkHistory()
Get task work history from session notes. T4462 T4750 SignatureparseIssueTemplates()
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. SignaturegetTemplateForSubcommand()
Get template config for a specific subcommand (bug/feature/help). Performs a live parse and filters to the matching template. SignaturegenerateTemplateConfig()
Generate and cache the config as .cleo/issue-templates.json. Performs a live parse, then writes the result using writeJsonFileAtomic. SignaturevalidateLabels()
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. SignaturegetCurrentShell()
Detect the current shell. SignaturegetRcFilePath()
Get the RC file path for a shell. SignaturedetectAvailableShells()
Detect which shells are available on the system. SignaturegenerateBashAliases()
Generate bash/zsh alias content. SignaturegeneratePowershellAliases()
Generate PowerShell alias content. SignaturehasAliasBlock()
Check if aliases are already injected in a file. SignaturegetInstalledVersion()
Get the installed alias version from an RC file. SignatureinjectAliases()
Inject aliases into a shell RC file. SignatureremoveAliases()
Remove aliases from a shell RC file. SignaturecheckAliasesStatus()
Get alias status for the current shell. SignaturediscoverReleaseTasks()
Discover task IDs for a release from completed tasks. Optionally filtered by date range or specific task IDs. SignaturegroupTasksIntoSections()
Group tasks into changelog sections. SignaturegenerateChangelogMarkdown()
Generate changelog markdown for a version. SignatureformatChangelogJson()
Format changelog data as JSON. SignaturewriteChangelogFile()
Write changelog content to a file. SignatureappendToChangelog()
Append a new release section to an existing CHANGELOG.md. SignaturegenerateChangelog()
Full changelog generation: discover tasks, group, generate, write. SignatureparseCommandHeader()
Parse a ###CLEO header block from a script file. SignaturescanAllCommands()
Scan a scripts directory and build a command registry. Returns a map of command name to metadata. SignaturevalidateHeader()
Validate a command header has required fields. SignaturegetCommandScriptMap()
Get command-to-script mapping. SignaturegetCommandsByCategory()
Group commands by category. SignaturegetCommandsByRelevance()
Filter commands by relevance level. SignaturedefaultFlags()
Default flag values. SignatureparseCommonFlags()
Parse common CLI flags from an argument array. Returns flags and remaining positional arguments. SignatureresolveFormat()
Resolve output format based on flags and TTY detection. Returns ‘json’ for non-TTY (piped), ‘human’ for TTY. SignatureisJsonOutput()
Check if output should be JSON. SignaturegetValidationKey()
Get the validation key for a target filename. SignatureextractMarkerVersion()
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. SignaturecheckManifestEntry()
Verify a manifest entry for a task has valid required fields. T4524 SignaturecheckReturnFormat()
Check if a response matches the expected return format. T4524 SignaturescoreSubagentCompliance()
Calculate comprehensive compliance score for a subagent. T4524 SignaturecalculateTokenEfficiency()
Calculate token efficiency metrics. T4524 SignaturecalculateOrchestrationOverhead()
Calculate orchestration overhead metrics. T4524 SignaturegetScriptCommands()
Get command names from scripts directory. Returns sorted list of script basenames without .sh extension. T4527 SignaturegetIndexScripts()
Get script names from COMMANDS-INDEX.json. T4527 SignaturegetIndexCommands()
Get command names from COMMANDS-INDEX.json. T4527 SignaturecheckCommandsSync()
Check commands index vs scripts directory for sync. T4527 SignaturecheckWrapperSync()
Check wrapper template sync with COMMANDS-INDEX. T4527 SignaturedetectDrift()
Run full drift detection across scripts, index, wrapper, and README. T4527 SignatureshouldRunDriftDetection()
Check if drift detection should run automatically based on config. T4527 SignaturegetCacheFilePath()
Get cache file path. T4525 SignatureinitCacheFile()
Initialize empty cache file. T4525 SignatureloadCache()
Load cache file or return null if missing/invalid. T4525 SignaturegetFileHash()
Get file hash for cache invalidation. T4525 SignaturegetCachedValidation()
Check if project validation is cached and valid. Returns the cache entry if valid, null if cache miss. T4525 SignaturecacheValidationResult()
Cache project validation results. T4525 SignatureclearProjectCache()
Clear cache for a specific project. T4525 SignatureclearEntireCache()
Clear entire cache. T4525 SignatureisTempProject()
Check if a project path is a temporary/test directory. T4525 SignaturecategorizeProjects()
Filter projects into categories: active, temp, orphaned. T4525 SignaturegetProjectCategoryName()
Get human-readable project category name. T4525 SignatureformatProjectHealthSummary()
Format project health summary for display. T4525 SignaturegetProjectGuidance()
Get actionable guidance for project issues. T4525 SignaturegetUserJourneyStage()
Check user journey stage based on system state. T4525 SignaturegetJourneyGuidance()
Get journey-specific guidance text. T4525 SignaturesanitizeFilePath()
Sanitize a file path for safe shell usage. Prevents command injection via malicious file names. T4523 SignaturevalidateTitle()
Validate a task title. Checks for emptiness, newlines, invisible characters, control chars, and length. T4523 SignaturevalidateDescription()
T4523 SignaturevalidateNote()
T4523 SignaturevalidateBlockedBy()
T4523 SignaturevalidateSessionNote()
T4523 SignaturevalidateCancelReason()
Validate a cancellation reason. T4523 SignaturevalidateStatusTransition()
Validate that a status transition is allowed. T4523 SignatureisValidStatus()
Check if a status string is valid. T4523 SignaturecheckTimestampSanity()
Check timestamp format and sanity. T4523 SignatureisMetadataOnlyUpdate()
Check if an update contains only metadata fields (safe for done tasks). T4523 SignaturenormalizeLabels()
Deduplicate and normalize labels. T4523 SignaturecheckIdUniqueness()
Check ID uniqueness within and across files. T4523 SignaturevalidateTask()
Validate a single task object. T4523 SignaturevalidateNoCircularDeps()
Check for circular dependencies using DFS. T4523 SignaturevalidateSingleActivePhase()
Validate only one phase is active. T4523 SignaturevalidateCurrentPhaseConsistency()
Validate currentPhase matches an active phase. T4523 SignaturevalidatePhaseTimestamps()
Validate phase timestamp ordering. T4523 SignaturevalidatePhaseStatusRequirements()
Validate phase status requirements (e.g., active phases must have startedAt). T4523 SignaturevalidateAll()
Run all validation checks on a TaskFile. T4523 SignatureparseManifest()
Parse a MANIFEST.jsonl file into entries. Skips invalid JSON lines gracefully. T4524 SignaturefindReviewDocs()
Find documents in review status. T4524 SignatureextractTopics()
Extract markdown headings from file content. T4524 SignaturesearchCanonicalCoverage()
Search for topic coverage in a docs directory. Returns count of matching files. T4524 SignatureanalyzeCoverage()
Analyze documentation coverage for review documents. T4524 SignatureformatGapReport()
Format a gap report for human-readable display. T4524 SignaturefindManifestEntry()
Find a manifest entry for a task ID in a JSONL file. T4526 SignaturevalidateManifestEntry()
Run validation on a manifest entry for a specific task. T4526 SignaturelogRealCompliance()
Log validation results to the compliance JSONL file. T4526 SignaturevalidateAndLog()
Find, validate, and log compliance for a task in one call. T4526 SignaturecheckOutputFileExists()
Check if expected output file exists. T4527 SignaturecheckDocumentationSections()
Check if file contains required documentation sections. T4527 SignaturecheckReturnMessageFormat()
Check if return message follows protocol format. Expected: ” . See MANIFEST.jsonl for .” T4527 SignaturecheckManifestFieldPresent()
Check if manifest entry has a required field (non-null, non-empty). T4527 SignaturecheckManifestFieldType()
Check if manifest field has expected type. T4527 SignaturecheckKeyFindingsCount()
Check if key_findings array has valid count (3-7). T4527 SignaturecheckStatusValid()
Check if status is valid enum value. T4527 SignaturecheckAgentType()
Check if agent_type matches expected value. T4527 SignaturecheckLinkedTasksPresent()
Check if linked_tasks array contains required task IDs. T4527 SignaturecheckProvenanceTags()
Check if file contains provenance tag. T4527 SignaturevalidateCommonManifestRequirements()
Validate common manifest requirements across all protocols. T4527 SignatureisValidGateName()
T4526 SignatureisValidAgentName()
T4526 SignaturegetGateOrder()
T4526 SignaturegetGateIndex()
T4526 SignaturegetDownstreamGates()
T4526 SignatureinitVerification()
Initialize a new verification object with default values. T4526 SignaturecomputePassed()
Compute whether verification has passed based on required gates. T4526 SignaturesetVerificationPassed()
Update the passed field on a verification object. T4526 SignatureupdateGate()
Update a single gate value. T4526 SignatureresetDownstreamGates()
Reset all downstream gates to null after a gate failure. T4526 SignatureincrementRound()
Increment the round counter. Returns null if max rounds exceeded. T4526 SignaturelogFailure()
Log a failure to the failureLog array. T4526 SignaturecheckAllGatesPassed()
Check if all required gates have passed. T4526 SignatureisVerificationComplete()
Check if verification is complete (passed = true). T4526 SignaturegetVerificationStatus()
Get verification status for display. T4526 SignatureshouldRequireVerification()
Check if a task type should require verification. T4526 SignaturegetMissingGates()
Get gate names that are not yet true. T4526 SignaturegetGateSummary()
Get gate summary for display. T4526 SignaturecheckCircularValidation()
Check for circular validation (self-approval prevention). Prevents: creator validating own work, validator re-testing, tester self-creating. T4526 SignatureallEpicChildrenVerified()
Check if all children of an epic have verification.passed = true. T4526 SignatureallSiblingsVerified()
Check if all siblings of a task are verified. T4526 SignaturegetProjectInfo()
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- 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. SignatureProtocolEnforcer
Main protocol enforcement class SignaturevalidateProtocol()
Validate protocol compliance for a manifest entryvalidateRule()
Validate a single rulecheckLifecycleGate()
Check lifecycle gate prerequisitesrecordViolation()
Record a protocol violationgetViolations()
Get recent violationscalculatePenalty()
Calculate penalty for violation severityenforceProtocol()
Middleware function for domain router Intercepts operations and validates protocol compliance before execution.requiresProtocolValidation()
Determine if operation requires protocol validationdetectProtocol()
Detect protocol type from request/responseextractManifestEntry()
Extract manifest entry from responsesetStrictMode()
Set strict modeisStrictMode()
Get strict mode statusgetHookCapableProviders(event)
Get all providers that support a specific hook event Signature| Name | Type | Description |
|---|---|---|
event | HookEvent | The hook event to query |
getSharedHookEvents(providerIds)
Get hook events supported by all specified providers Signature| Name | Type | Description |
|---|---|---|
providerIds | : string[] | undefined | Optional array of provider IDs (uses all active providers if omitted) |
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 SignaturevalidateGateSatisfiability()
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 SignaturevalidateChain()
Validate a complete WarpChain definition. Orchestrates shape validation and gate satisfiability checks, returning a unified ChainValidation result. T5401 SignatureaddChain()
Store a validated WarpChain definition. Validates the chain before storing. Throws if validation fails. T5403 SignatureshowChain()
Retrieve a WarpChain definition by ID. T5403 SignaturelistChains()
List all stored WarpChain definitions. T5403 SignaturefindChains()
Find WarpChain definitions by criteria. T5403 SignaturecreateInstance()
Create a chain instance binding a chain to an epic. T5403 SignatureshowInstance()
Retrieve a chain instance by ID. T5403 SignaturelistInstanceGateResults()
Read persisted gate results for a chain instance. SignatureadvanceInstance()
Advance a chain instance to the next stage, recording gate results. T5403 SignaturevalidateResearchProtocol()
T4499 SignaturevalidateConsensusProtocol()
T4499 SignaturevalidateSpecificationProtocol()
T4499 SignaturevalidateDecompositionProtocol()
T4499 SignaturevalidateImplementationProtocol()
T4499 SignaturevalidateContributionProtocol()
T4499 SignaturevalidateReleaseProtocol()
T4499 SignaturevalidateArtifactPublishProtocol()
T4499 SignaturevalidateProvenanceProtocol()
T4499 SignaturevalidateProtocol()
Validate a manifest entry against a specific protocol. Throws CleoError with appropriate exit code on strict failure. T4499 SignaturebuildDefaultChain()
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 SignaturebuildDefaultTessera()
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 SignatureinstantiateTessera()
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 SignaturelistTesseraTemplates()
List all registered Tessera templates. T5409 SignatureshowTessera()
Find a Tessera template by ID. T5409 SignaturemigrateClaudeMem(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| Name | Type | Description |
|---|---|---|
projectRoot | string | The CLEO project root (for brain.db resolution) |
options | : ClaudeMemMigrationOptions | Migration options |
reasonWhy()
Build a causal trace for why a task is blocked. Walks upstream throughdepends 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| Name | Type | Description |
|---|---|---|
entryId | string | ID of the brain.db entry to find similar entries for |
projectRoot | string | Project root directory |
limit | : number | undefined | Maximum results to return (default 10) |
memoryShow()
memory.show - Look up a brain.db entry by ID SignaturememoryBrainStats()
memory.stats - Aggregate stats from brain.db across all tables SignaturememoryDecisionFind()
memory.decision.find - Search decisions in brain.db SignaturememoryDecisionStore()
memory.decision.store - Store a decision to brain.db SignaturememoryFind()
memory.find - Token-efficient brain search SignaturememoryTimeline()
memory.timeline - Chronological context around anchor SignaturememoryFetch()
memory.fetch - Batch fetch brain entries by IDs SignaturememoryObserve()
memory.observe - Save observation to brain SignaturememoryPatternStore()
memory.pattern.store - Store a pattern to BRAIN memory SignaturememoryPatternFind()
memory.pattern.find - Search patterns in BRAIN memory SignaturememoryPatternStats()
memory.pattern.stats - Get pattern memory statistics SignaturememoryLearningStore()
memory.learning.store - Store a learning to BRAIN memory SignaturememoryLearningFind()
memory.learning.find - Search learnings in BRAIN memory SignaturememoryLearningStats()
memory.learning.stats - Get learning memory statistics SignaturememoryContradictions()
memory.contradictions - Find contradictory entries in brain.db SignaturememorySuperseded()
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 SignaturememoryLink()
memory.link - Link a brain entry to a task SignaturememoryUnlink()
memory.unlink - Remove a link between a brain entry and a task SignaturememoryGraphAdd()
memory.graph.add - Add a node or edge to the PageIndex graph SignaturememoryGraphShow()
memory.graph.show - Get a node and its edges from the PageIndex graph SignaturememoryGraphNeighbors()
memory.graph.neighbors - Get neighbor nodes from the PageIndex graph SignaturememoryReasonWhy()
memory.reason.why - Causal trace through task dependency chains SignaturememoryReasonSimilar()
memory.reason.similar - Find semantically similar entries SignaturememorySearchHybrid()
memory.search.hybrid - Hybrid search across FTS5, vector, and graph SignaturememoryGraphRemove()
memory.graph.remove - Remove a node or edge from the PageIndex graph SignaturepipelineManifestShow()
pipeline.manifest.show - Get manifest entry details by ID SignaturepipelineManifestList()
pipeline.manifest.list - List manifest entries with filters SignaturepipelineManifestFind()
pipeline.manifest.find - Find manifest entries by text (LIKE search on content + type) SignaturepipelineManifestPending()
pipeline.manifest.pending - Get pending manifest items SignaturepipelineManifestStats()
pipeline.manifest.stats - Manifest statistics SignaturepipelineManifestRead()
pipeline.manifest.read - Read manifest entries with optional filter SignaturepipelineManifestAppend()
pipeline.manifest.append - Append entry to pipeline_manifest table SignaturepipelineManifestArchive()
pipeline.manifest.archive - Archive old manifest entries by date SignaturepipelineManifestCompact()
pipeline.manifest.compact - Dedup by contentHash (keep newest by createdAt) SignaturepipelineManifestValidate()
pipeline.manifest.validate - Validate manifest entries for a task SignaturepipelineManifestContradictions()
pipeline.manifest.contradictions - Find entries with overlapping topics but conflicting key_findings SignaturepipelineManifestSuperseded()
pipeline.manifest.superseded - Identify entries replaced by newer work on same topic SignaturepipelineManifestLink()
pipeline.manifest.link - Link manifest entry to a task SignaturereadManifestEntries()
Read all manifest entries from the pipeline_manifest table. Replaces readManifestEntries() from pipeline-manifest-compat. SignaturefilterEntries()
Filter manifest entries by criteria (alias for backward compatibility). SignaturedistillManifestEntry()
Distill a manifest entry to brain.db observation (Phase 3, pending). SignaturemigrateManifestJsonlToSqlite()
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. SignatureresolveProviderFromModelIndex()
SignatureresolveProviderFromModelRegistry()
SignatureresetModelsDevCache()
SignaturemeasureTokenExchange()
SignaturerecordTokenExchange()
SignatureshowTokenUsage()
SignaturelistTokenUsage()
SignaturesummarizeTokenUsage()
SignaturedeleteTokenUsage()
SignatureclearTokenUsage()
SignatureautoRecordDispatchTokenUsage()
SignaturegetLatestTokenRecord()
SignaturegetTokenUsageAggregateSql()
SignaturestartParallelExecution()
Start parallel execution for a wave. SignatureendParallelExecution()
End parallel execution for a wave. SignaturegetParallelStatus()
Get current parallel execution state. SignaturelistSkills()
List available skills. SignaturegetSkillContent()
Read skill content for injection into agent context. SignaturegetUnblockOpportunities()
Analyze dependency graph for unblocking opportunities. SignaturevalidateSpawnReadiness()
Validate spawn readiness for a task. SignatureinjectContext()
Read protocol injection content for a given protocol type. Core logic for session.context.inject. SignaturegenerateSessionId()
Generate a canonical session ID. Format: ses_YYYYMMDDHHmmss_6hex Example: ses_20260227171900_a1b2c3 SignatureisValidSessionId()
Check if a string is a valid session ID (any format). SignatureisCanonicalSessionId()
Check if a session ID uses the canonical format. SignatureextractSessionTimestamp()
Extract an approximate timestamp from any valid session ID format. Returns null if the ID format is not recognized. SignaturecreateSession()
Create a new session. SignaturegetSession()
Get a session by ID. SignatureupdateSession()
Update a session. SignaturelistSessions()
List sessions with optional filters. SignatureendSession()
End a session. SignaturestartTask()
Start working on a task within a session. SignaturegetCurrentTask()
Get current task for a session. SignaturestopTask()
Stop working on the current task for a session. SignatureworkHistory()
Get work history for a session. SignaturegcSessions()
Garbage collect old sessions (mark ended sessions as orphaned after threshold). SignaturegetActiveSession()
Get the currently active session (if any). SignaturecomputeDependencyWaves()
Compute dependency waves for parallel execution. Tasks in the same wave can run in parallel; waves must be sequential. SignaturegetNextTask()
Get the next task to work on (highest priority ready task). SignaturegetCriticalPath()
Calculate the critical path (longest dependency chain). Returns task IDs along the critical path. SignaturegetTaskOrder()
Get task ordering by dependency + priority. SignaturegetParallelTasks()
Get parallelizable tasks (tasks with no unmet dependencies). SignaturesuggestRelated()
Suggest related tasks based on shared attributes. SignatureaddRelation()
Add a relation between tasks. SignaturediscoverRelated()
Discover related tasks using various methods. SignaturelistRelations()
List existing relations for a task. SignaturecanCancel()
Check if a task can be cancelled. SignaturecancelTask()
Cancel a task in the tasks array (returns updated array). Does NOT handle children - use deletion-strategy for that. SignaturecancelMultiple()
Batch cancel multiple tasks. SignaturecoreTaskNext()
Suggest next task to work on based on priority, phase, age, and deps. T4790 SignaturecoreTaskBlockers()
Show blocked tasks and analyze blocking chains. T4790 SignaturecoreTaskTree()
Build hierarchy tree. T4790 SignaturecoreTaskDeps()
Show dependencies for a task. T4790 SignaturecoreTaskRelates()
Show task relations. T4790 SignaturecoreTaskRelatesAdd()
Add a relation between two tasks. T4790 SignaturecoreTaskAnalyze()
Analyze tasks for priority and leverage. T4790 SignaturecoreTaskRestore()
Restore a cancelled task back to pending. T4790 SignaturecoreTaskCancel()
Cancel a task (sets status to ‘cancelled’, a soft terminal state). Use restore to reverse. Use delete for permanent removal. T4529 SignaturecoreTaskUnarchive()
Move an archived task back to active tasks. T4790 SignaturecoreTaskReorder()
Change task position within its sibling group. T4790 SignaturecoreTaskReparent()
Move task under a different parent. T4790 SignaturecoreTaskPromote()
Promote a subtask to task or task to root. T4790 SignaturecoreTaskReopen()
Reopen a completed task. T4790 SignaturecoreTaskComplexityEstimate()
Deterministic complexity scoring from task metadata. T4790 SignaturecoreTaskDepsOverview()
Overview of all dependencies across the project. T5157 SignaturecoreTaskDepsCycles()
Detect circular dependencies across the project. T5157 SignaturecoreTaskDepends()
List dependencies for a task in a given direction. T4790 SignaturecoreTaskStats()
Compute task statistics. T4790 SignaturecoreTaskExport()
Export tasks as JSON or CSV. T4790 SignaturecoreTaskHistory()
Get task history from the log file. T4790 SignaturecoreTaskLint()
Lint tasks for common issues. T4790 SignaturecoreTaskBatchValidate()
Validate multiple tasks at once. T4790 SignaturecoreTaskImport()
Import tasks from a JSON source string. T4790 SignatureanalyzeTaskPriority()
Analyze task priority with leverage scoring. SignaturelistLabels()
List all labels with task counts. SignatureshowLabelTasks()
Show tasks with a specific label. SignaturegetLabelStats()
Get detailed label statistics. SignaturecreateStoreProvider()
Create a store provider. Always creates SQLite provider (ADR-006). T4647 SignaturegetStore()
Get a StoreProvider instance for the given working directory. Convenience wrapper around createStoreProvider with auto-detection. T4645 T4638 SignaturecountJsonRecords()
Count records in JSON source files. SignaturemigrateJsonToSqliteAtomic(cwd, tempDbPath, logger)
Migrate JSON data to SQLite with atomic rename pattern. Writes to a temporary database file first, then atomically renames. Signature| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Optional working directory |
tempDbPath | : string | undefined | Optional temporary database path for atomic migration |
logger | : MigrationLogger | undefined | Optional migration logger for audit trail (task T4727) |
migrateJsonToSqlite()
SignatureexportToJson()
Export SQLite data back to JSON format (for inspection or emergency recovery). SignaturerepairMissingSizes()
Set size=‘medium’ on tasks that have no size value. Operates directly on the SQLite tasks table. SignaturerepairMissingCompletedAt()
Set completedAt=now() on done/cancelled tasks that are missing a completedAt timestamp. Operates directly on the SQLite tasks table. SignaturerunAllRepairs()
Run all repair functions. Returns all actions taken (or previewed in dry-run mode). SignaturerunUpgrade(, , , )
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| Name | Type | Description |
|---|---|---|
| “ | : \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \} | options.dryRun Preview changes without applying |
| “ | : \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \} | options.includeGlobal Also check global ~/.cleo |
| “ | : \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \} | options.autoMigrate Auto-migrate storage if needed (default: true) |
| “ | : \{ dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; \} | options.cwd Project directory override |
VerificationGate
Main Verification Gate class Orchestrates 4-layer validation and determines pass/fail status. Each layer must pass before proceeding to the next. SignatureverifyOperation()
Execute all 4 gate layers sequentially Stops at first failure unless in advisory mode.runLayer()
Run a single validation layer with timingbuildSuccessResult()
Build success result when all gates passbuildFailureResult()
Build failure result when a gate failsdetermineSemanticExitCode()
Determine semantic layer exit code from violationsdetermineReferentialExitCode()
Determine referential layer exit code from violationsdetermineProtocolExitCode()
Determine protocol layer exit code from violationsrequiresValidation()
Check if an operation requires gate validation All mutate operations require validation. Query operations skip validation for performance.getLayerName()
Get human-readable layer namecreateVerificationGate()
Factory function for creating verification gates SignatureWorkflowGateTracker
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 SignaturegetGateStatus()
Get the status of a specific gategetGateState()
Get the full state of a specific gategetAllGates()
Get all gate statescanAttempt()
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 passedgetPendingGates()
Get all gates that are currently blocked or have null statusgetNextAttemptable()
Get the next gate that can be attemptedgetDownstreamGates()
Get downstream gates of a given gate (not including the gate itself)toRecord()
Serialize gate states to a plain recordfromRecord()
Restore gate states from a recordisValidGate()
Check if a gate name is validisValidWorkflowGateName()
Validate a workflow gate name string SignaturegetWorkflowGateDefinition()
Get the definition for a workflow gate SignaturevalidateLayer1Schema()
Layer 1: Schema Validation Validates operation parameters against JSON Schema definitions. Checks required fields, data types, and format constraints. SignaturevalidateLayer2Semantic()
Layer 2: Semantic Validation Validates business rules and logical constraints. SignaturevalidateLayer3Referential()
Layer 3: Referential Validation Validates cross-entity references and relationships. SignaturevalidateLayer4Protocol()
Layer 4: Protocol Validation Validates RCASD-IVTR+C lifecycle compliance and protocol requirements. SignatureisFieldRequired()
Helper to check if a field is required for an operation SignaturevalidateWorkflowGateName()
Validate a workflow gate name T3141 SignaturevalidateWorkflowGateStatus()
Validate a workflow gate status value per Section 7.3 T3141 SignaturevalidateWorkflowGateUpdate()
Validate a gate update operation. T3141 SignaturebuildMcpInputSchema()
Build a JSON Schemainput_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()
SplitOperationDef.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 ’ SignaturecamelToKebab()
Convert a camelCase string to kebab-case. e.g. ‘includeArchive’ → ‘include-archive’ SignaturevalidateRequiredParamsDef()
Validates that all required parameters are present in the request. Returns an array of missing parameter names. Replaces the oldrequiredParams: string[] check in registry.ts.
Signature
validateConsensusTask()
Validate consensus protocol for a task. SignaturecheckConsensusManifest()
Validate consensus protocol from manifest file. SignaturevalidateContributionTask()
Validate contribution protocol for a task. SignaturecheckContributionManifest()
Validate contribution protocol from manifest file. SignaturevalidateDecompositionTask()
Validate decomposition protocol for a task. SignaturecheckDecompositionManifest()
Validate decomposition protocol from manifest file. SignaturevalidateImplementationTask()
Validate implementation protocol for a task. SignaturecheckImplementationManifest()
Validate implementation protocol from manifest file. SignaturevalidateSpecificationTask()
Validate specification protocol for a task. SignaturecheckSpecificationManifest()
Validate specification protocol from manifest file. SignaturevalidateSchema(schemaType, data)
Validate data against a CLEO schema Signature| Name | Type | Description |
|---|---|---|
schemaType | "config" | Which schema to validate against |
data | unknown | The data to validate |
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| Name | Type | Description |
|---|---|---|
task | unknown | Task object to validate |
clearSchemaCache()
Clear the schema cache (useful for testing) SignaturevalidateTitleDescription()
Validate that title and description are both present and different. This is a critical anti-hallucination check. SignaturevalidateTimestamps()
Validate that timestamps are not in the future SignaturevalidateIdUniqueness()
Validate ID uniqueness across all tasks (todo + archive) SignaturevalidateNoDuplicateDescription()
Validate no duplicate task descriptions SignaturevalidateHierarchy()
Validate hierarchy constraints. Accepts optional limits to override defaults (from config). SignaturevalidateStatusTransition()
Validate status transition SignaturevalidateNewTask()
Run all validation rules on a task being created SignaturehasErrors()
Check if violations contain any errors (not just warnings) SignaturecoreValidateReport()
Run comprehensive validation report on tasks database — checks business rules, dependencies, checksums, data integrity, and schema compliance. T4795 SignaturecoreValidateAndFix()
Run validation report, then apply data repairs for fixable issues. Calls runAllRepairs() from src/core/repair.ts (same repairs used byupgrade). 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 rawdata is provided, validates directly with AJV (backward compat). T4786
Signature
coreValidateTask()
Validate a single task against anti-hallucination rules. T4786 SignaturecoreValidateProtocol()
Check basic protocol compliance for a task. T4786 SignaturecoreValidateManifest()
Validate manifest JSONL entries for required fields. T4786 SignaturecoreValidateOutput()
Validate an output file for required sections. T4786 SignaturecoreComplianceSummary()
Get aggregated compliance metrics. T4786 SignaturecoreComplianceViolations()
List compliance violations. T4786 SignaturecoreComplianceRecord()
Record a compliance check result to COMPLIANCE.jsonl. T4786 SignaturecoreTestStatus()
Check test suite availability. T4786 SignaturecoreCoherenceCheck()
Cross-validate task graph for consistency. T4786 SignaturecoreTestRun()
Execute test suite via subprocess. T4786 SignaturecoreBatchValidate()
Batch validate all tasks against schema and rules. T4786 SignaturecoreTestCoverage()
Get test coverage metrics. T4786 SignaturebuildBrainState()
Build brain state for agent bootstrapping. SignaturegetCriticalPath()
Find the critical path (longest dependency chain) in the task graph. SignatureresolveSkillPathsForProvider(providerId, scope, projectRoot)
Get effective skill paths for a provider considering precedence Signature| Name | Type | Description |
|---|---|---|
providerId | string | The ID of the provider |
scope | "global" | "project" | The scope (‘global’ or ‘project’) |
projectRoot | : string | undefined | Optional project root path for project-scoped resolution |
- Error if provider not found
getProvidersWithPrecedence(precedence)
Get all providers that use a specific precedence mode Signature| Name | Type | Description |
|---|---|---|
precedence | SkillsPrecedence | The precedence mode to filter by |
getSkillsMapWithPrecedence()
Build complete skills map with precedence information SignaturedetermineInstallationTargets(context)
Determine target installation paths for a skill Signature| Name | Type | Description |
|---|---|---|
context | SkillInstallationContext | The installation context including target providers and project root |
supportsAgentsPath(providerId)
Check if provider supports agents path Signature| Name | Type | Description |
|---|---|---|
providerId | string | The ID of the provider to check |
coreTaskPlan()
Build composite planning view. T4914 SignaturebuildIndex(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| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Working directory |
writeIndex(index, cwd)
Write RCASD-INDEX.json to disk. Signature| Name | Type | Description |
|---|---|---|
index | RcasdIndex | The index to write |
cwd | : string | undefined | Working directory T4801 |
readIndex(cwd)
Read RCASD-INDEX.json from disk. Signature| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Working directory |
rebuildIndex(cwd)
Rebuild and write the index from current disk state. Signature| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Working directory |
getTaskAnchor(taskId, cwd)
Get task anchor by task ID. Signature| Name | Type | Description |
|---|---|---|
taskId | string | The task ID to look up |
cwd | : string | undefined | Working directory |
findByStage(stage, cwd)
Find tasks by pipeline stage. Signature| Name | Type | Description |
|---|---|---|
stage | string | The pipeline stage to filter by |
cwd | : string | undefined | Working directory |
findByStatus(status, cwd)
Find tasks by status. Signature| Name | Type | Description |
|---|---|---|
status | "completed" | "failed" | "active" | "archived" | "paused" | The status to filter by |
cwd | : string | undefined | Working directory |
getIndexTotals(cwd)
Get index summary statistics. Signature| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Working directory |
generateCodebaseMapSummary()
SignaturesequenceChains()
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 SignatureparallelChains()
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 SignatureresolveEpicFromContent()
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 likeT####-* or T####_*.
Signature
normalizeDirectoryNames()
Rename suffixed epic directories (e.g.T4881_install-channels → T4881).
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 looseT####_*.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
| Name | Type | Description |
|---|---|---|
| “ | : ConsolidateOptions | options.dryRun - If true, log planned moves without executing them |
| “ | : ConsolidateOptions | options.cwd - Optional working directory override |
initializePipeline(taskId, options)
Initialize a new pipeline for a task. Creates a new pipeline record in the database with all 9 stages initialized to ‘not_started’ status. The pipeline starts at the research stage by default. Signature| Name | Type | Description |
|---|---|---|
taskId | string | The task ID (e.g., ‘T4800’) |
options | : InitializePipelineOptions | Optional configuration |
- CleoError If pipeline already exists or database operation fails
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| Name | Type | Description |
|---|---|---|
taskId | string | The task ID (e.g., ‘T4800’) |
- CleoError If database query fails
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| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
options | AdvanceStageOptions | Advance options including target stage and reason |
- CleoError If transition is invalid or prerequisites not met
getCurrentStage(taskId)
Get the current stage of a pipeline. Convenience method to quickly check which stage a task is currently in. Signature| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
- CleoError If database query fails
listPipelines(options)
List pipelines with optional filtering. Signature| Name | Type | Description |
|---|---|---|
options | : PipelineQueryOptions | Query options for filtering and pagination |
- CleoError If database query fails
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| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
_reason | : string | undefined | Optional completion reason (unused, for API compatibility) |
- 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| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
reason | string | Reason for cancellation |
- CleoError If pipeline not found or already completed
pipelineExists(taskId)
Check if a pipeline exists for a task. Signature| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
getPipelineStatistics()
Get pipeline statistics. Returns aggregate counts of pipelines by status and stage. Signature- CleoError If database query fails
getPipelineStages(taskId)
Get all stages for a pipeline. Signature| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
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| Name | Type | Description |
|---|---|---|
options | : FindResumableOptions | Query options for filtering |
cwd | : string | undefined | Working directory for database |
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| Name | Type | Description |
|---|---|---|
taskId | string | The task ID to load context for |
cwd | : string | undefined | Working directory for database |
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| Name | Type | Description |
|---|---|---|
taskId | string | The task ID |
targetStage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to resume |
options | : \{ ...; \} | Resume options |
cwd | : string | undefined | Working directory for database |
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| Name | Type | Description |
|---|---|---|
cwd | : string | undefined | Working directory for database |
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| Name | Type | Description |
|---|---|---|
options | : SessionResumeCheckOptions | Resume check options |
cwd | : string | undefined | Working directory for database |
formatResumeSummary(pipelines)
Get resume summary for display to user. Formats resumable pipelines into a human-readable summary. Signature| Name | Type | Description |
|---|---|---|
pipelines | ResumablePipeline[] | Resumable pipelines |
handleCompletedStage(context)
Handle completed stage edge case. If the current stage is completed, suggests advancing to next stage. Signature| Name | Type | Description |
|---|---|---|
context | PipelineContext | Pipeline context |
handleBlockedStage(context)
Handle blocked stage edge case. Provides information about why a stage is blocked and potential resolutions. Signature| Name | Type | Description |
|---|---|---|
context | PipelineContext | Pipeline context |
checkBlockedStageDetails(taskId, cwd)
Handle blocked stage edge case - async version with database lookup. Signature| Name | Type | Description |
|---|---|---|
taskId | string | Task ID to check |
cwd | : string | undefined | Working directory |
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| Name | Type | Description |
|---|---|---|
targetStage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to check prerequisites for |
currentStages | Record<"research" | ... 7 more ... | "release" | Current state of all stages |
- CleoError If validation fails
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| Name | Type | Description |
|---|---|---|
transition | StateTransition | The transition to validate |
context | StateMachineContext | Current state machine context |
- CleoError If validation fails unexpectedly
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| Name | Type | Description |
|---|---|---|
transition | StateTransition | The transition to execute |
context | StateMachineContext | Current state machine context |
- CleoError If transition is invalid
setStageStatus(stage, status, context)
Set the status of a stage. Updates stage status with validation of allowed state transitions. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to update |
status | "completed" | ... 4 more ... | "skipped" | The new status |
context | StateMachineContext | Current state machine context |
- CleoError If status transition is invalid
getStageStatus(stage, context)
Get the status of a stage. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to check |
context | StateMachineContext | Current state machine context |
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| Name | Type | Description |
|---|---|---|
from | "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped" | Current status |
to | "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped" | Target status |
createInitialContext(pipelineId, assignedAgent)
Create initial state machine context for a pipeline. Signature| Name | Type | Description |
|---|---|---|
pipelineId | string | The pipeline/task ID |
assignedAgent | : string | undefined | Optional agent to assign |
getValidNextStages(context, includeForce)
Get stages that can be transitioned to from the current stage. Signature| Name | Type | Description |
|---|---|---|
context | StateMachineContext | Current state machine context |
includeForce | : boolean | Whether to include transitions that require force |
getCurrentStageState(context)
Get the current stage state. Signature| Name | Type | Description |
|---|---|---|
context | StateMachineContext | State machine context |
isTerminalState(context)
Check if the pipeline is in a terminal state. Signature| Name | Type | Description |
|---|---|---|
context | StateMachineContext | State machine context |
isBlocked(context)
Check if the pipeline is blocked. Signature| Name | Type | Description |
|---|---|---|
context | StateMachineContext | State machine context |
validateTransitions(transitions, context)
Validate multiple transitions. Signature| Name | Type | Description |
|---|---|---|
transitions | StateTransition[] | Array of transitions to validate |
context | StateMachineContext | State machine context |
canSkipStage(stage)
Check if a stage can be skipped. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to check |
skipStage(stage, reason, context)
Skip a stage with validation. Signature| Name | Type | Description |
|---|---|---|
stage | "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release" | The stage to skip |
reason | — | Reason for skipping |
context | StateMachineContext | State machine context |
- CleoError If stage cannot be skipped
getContextStatusFromPercentage()
Determine status from percentage. SignatureprocessContextInput()
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. SignatureisHITLEnabled()
Check if HITL warnings are enabled. SignaturegenerateHITLWarnings()
Generate HITL warnings based on lock state. SignaturegetHighestLevel()
Get highest warning level from warnings. SignaturegetConcurrencyJson()
Get concurrency data for analyze JSON output. SignaturegetEnforcementMode()
Get the current enforcement mode. SignatureisSessionEnforcementEnabled()
Check if session enforcement is enabled. SignaturegetActiveSessionInfo()
Get active session info. Returns null if no active session. SignaturerequireActiveSession()
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. SignaturevalidateTaskInScope()
Validate that a task is within the current session’s scope. Only enforced when a session is active. SignaturecheckStatuslineIntegration()
Check if statusline integration is configured. Returns the current integration status. SignaturegetStatuslineConfig()
Get the statusline setup command for Claude Code settings. SignaturegetSetupInstructions()
Get human-readable setup instructions. SignaturegetPreferredChannel(domain, operation)
Look up the preferred channel for a given domain + operation. Signature| Name | Type | Description |
|---|---|---|
domain | string | Domain name |
operation | string | Operation name |
getRoutingForDomain(domain)
Get routing entries for a specific domain. Signature| Name | Type | Description |
|---|---|---|
domain | string | Domain name |
getOperationsByChannel(channel)
Get all operations that prefer a specific channel. Signature| Name | Type | Description |
|---|---|---|
channel | "cli" | "mcp" | "either" | Channel preference to filter by |
generateMemoryProtocol(context)
Generate dynamic memory protocol instructions based on provider capabilities. Signature| Name | Type | Description |
|---|---|---|
context | ProviderContext | Provider capability context |
generateRoutingGuide(context)
Generate a dynamic routing guide based on operation preferences. Signature| Name | Type | Description |
|---|---|---|
context | ProviderContext | Provider capability context |
generateDynamicSkillContent(context)
Generate complete dynamic skill content for the current provider. Signature| Name | Type | Description |
|---|---|---|
context | ProviderContext | Provider capability context |
TaskCache
In-memory cache for task indices with checksum-based staleness detection. SignaturecomputeChecksum()
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 SignaturelogImportStart()
Log import operation start with package metadata. T4552 SignaturelogImportSuccess()
Log import operation completion with full metadata. T4552 SignaturelogImportError()
Log import operation error with diagnostic details. T4552 SignaturelogImportConflict()
Log import conflict detection and resolution. T4552 SignaturetopologicalSortTasks()
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 SignaturedetectCycles()
Detect cycles in task dependency graph. Returns true if no cycles, false if cycles detected. T4552 SignaturefindActivePipelinesWithStagesAndTasks(taskIds, cwd)
Find active pipelines joined with their stages and tasks. Optionally filters by specific task IDs. Signature| Name | Type | Description |
|---|---|---|
taskIds | : string[] | undefined | Optional list of task IDs to filter by |
cwd | : string | undefined | Working directory for database |
findPipelineWithCurrentStageAndTask(taskId, cwd)
Find a pipeline with its current stage and task by taskId. Matches stages where stageName equals the pipeline’s currentStageId. Signature| Name | Type | Description |
|---|---|---|
taskId | string | Task ID to look up |
cwd | : string | undefined | Working directory for database |
findPipelineWithStage(taskId, stageName, cwd)
Find a pipeline and a specific stage by taskId and stageName. Signature| Name | Type | Description |
|---|---|---|
taskId | string | Task ID |
stageName | string | Stage name to match |
cwd | : string | undefined | Working directory for database |
updatePipelineCurrentStage(pipelineId, currentStageId, cwd)
Update pipeline’s currentStageId. Signature| Name | Type | Description |
|---|---|---|
pipelineId | string | Pipeline ID to update |
currentStageId | string | New current stage identifier |
cwd | : string | undefined | Working directory for database |
getStagesByPipelineId(pipelineId, cwd)
Get all stages for a pipeline, ordered by sequence. Signature| Name | Type | Description |
|---|---|---|
pipelineId | string | Pipeline ID |
cwd | : string | undefined | Working directory for database |
activateStage(stageId, startedAt, cwd)
Update a stage’s status to ‘in_progress’ and clear block fields. Signature| Name | Type | Description |
|---|---|---|
stageId | string | Stage ID to update |
startedAt | string | ISO timestamp for when the stage started |
cwd | : string | undefined | Working directory for database |
findPipelineWithCurrentStage(taskId, cwd)
Find pipeline with current stage (no task join) by taskId. Used by checkBlockedStageDetails. Signature| Name | Type | Description |
|---|---|---|
taskId | string | Task ID |
cwd | : string | undefined | Working directory for database |
getGateResultsByStageId(stageId, cwd)
Get gate results for a stage, ordered by checkedAt descending. Signature| Name | Type | Description |
|---|---|---|
stageId | string | Stage ID |
cwd | : string | undefined | Working directory for database |
getGateResultsByStageIdUnordered(stageId, cwd)
Get gate results for a stage without ordering (for simple checks). Signature| Name | Type | Description |
|---|---|---|
stageId | string | Stage ID |
cwd | : string | undefined | Working directory for database |
getEvidenceByStageId(stageId, cwd)
Get evidence for a stage, ordered by recordedAt descending. Signature| Name | Type | Description |
|---|---|---|
stageId | string | Stage ID |
cwd | : string | undefined | Working directory for database |
getRecentTransitions(pipelineId, limit, cwd)
Get recent transitions for a pipeline, ordered by createdAt descending. Signature| Name | Type | Description |
|---|---|---|
pipelineId | string | Pipeline ID |
limit | : number | Max rows to return (default: 10) |
cwd | : string | undefined | Working directory for database |
insertTransition(transition, cwd)
Insert a new transition record. Signature| Name | Type | Description |
|---|---|---|
transition | \{ id: string; pipelineId: string; fromStageId: string; toStageId: string; createdAt?: string | undefined; transitionType?: "automatic" | "manual" | "forced" | undefined; transitionedBy?: string | ... 1 more ... | undefined; \} | Transition data to insert |
cwd | : string | undefined | Working directory for database |
checkAtomicity()
Check task atomicity using 6-point heuristic test. Default threshold: 4 (passing requires = 4/6 criteria met). SignatureextractTaskRefs()
Extract task IDs from text content. Scans for patterns like T1234, T001, T42 (T followed by 3+ digits). SignaturecreateRelatesEntries()
Create relates entries from extracted task IDs. SignaturemergeRelatesArrays()
Merge new relates entries with existing ones. Existing entries take precedence (dedup by taskId). SignaturevalidateRelatesRefs()
Validate that referenced task IDs exist. Returns array of invalid (non-existent) task IDs. SignatureextractAndCreateRelates()
Convenience: extract task refs from text and create relates entries. SignaturecalculateAffectedTasks()
Calculate which tasks would be affected by a delete operation. SignaturecalculateImpact()
Calculate impact of deletion. SignaturegenerateWarnings()
Generate warnings based on impact analysis. SignaturepreviewDelete()
Main preview function - coordinates all preview calculations. SignatureisValidStrategy()
Validate a strategy name. SignaturehandleChildren()
Handle children using the specified strategy. Returns the modified tasks array and the strategy result. SignatureGraphCache
Graph cache for expensive dependency calculations. Automatically invalidates when tasks change. SignaturecomputeChecksum()
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. SignaturediscoverByDescription()
Discover related tasks by description similarity (keyword-based Jaccard). SignaturediscoverByFiles()
Discover related tasks by shared files. SignaturediscoverByHierarchy()
Discover related tasks by hierarchical proximity (siblings and cousins). SignaturediscoverRelatedTasks()
Discover related tasks using all methods combined. SignaturesuggestRelates()
Suggest relates entries filtered by threshold. SignaturegetCurrentPhase()
Get the current active phase from project metadata. SignaturegetTasksByPhase()
Get tasks belonging to a specific phase. SignaturecalculatePhaseProgress()
Calculate progress for a phase. SignaturegetAllPhaseProgress()
Get progress for all phases. SignaturevalidatePhaseTransition()
SignaturecreatePhaseTransition()
Create a phase transition record. SignatureapplyPhaseTransition()
Apply a phase transition to project metadata. Returns updated project data. SignaturegetNextPhase()
Get the next phase in order. SignatureallPhasesComplete()
Check if all phases are complete. SignaturereparentTask(data, opts)
Reparent a task within a TaskFile. Mutates the task in-place withindata.tasks. Updates parentId, type, and updatedAt on the target task, and lastUpdated on the TaskFile.
Signature
| Name | Type | Description |
|---|---|---|
data | TaskFile | The loaded TaskFile (mutated in place) |
opts | ReparentOptions | Reparent options (taskId, newParentId) |