> ## Documentation Index
> Fetch the complete documentation index at: https://codluv.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# core — Functions

> Functions and classes for the core package

Functions and classes exported by this package.

## initLogger(cleoDir, config, projectHash)

Initialize the root logger. Call once at startup.  Uses pino-roll for automatic size+daily rotation with built-in retention. No custom rotation code needed.

**Signature**

```typescript theme={null}
(cleoDir: string, config: LoggerConfig, projectHash?: string | undefined) => Logger<never, boolean>
```

**Parameters**

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

**Returns** — The root pino logger instance

## getLogger(subsystem)

Get a child logger bound to a subsystem name.  Safe to call before initLogger — returns a stderr fallback logger so early startup code and tests never crash.

**Signature**

```typescript theme={null}
(subsystem: string) => Logger<never, boolean>
```

**Parameters**

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

**Signature**

```typescript theme={null}
() => string | null
```

## closeLogger()

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

**Signature**

```typescript theme={null}
() => Promise<void>
```

## getPlatformPaths()

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

**Signature**

```typescript theme={null}
() => PlatformPaths
```

## getSystemInfo()

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

**Signature**

```typescript theme={null}
() => SystemInfo
```

## \_resetPlatformPathsCache()

Invalidate the path and system info caches. Use in tests after mutating CLEO\_HOME env var.

**Signature**

```typescript theme={null}
() => void
```

## isProjectInitialized()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => boolean
```

## getCleoHome()

Get the global CLEO home directory. Respects CLEO\_HOME env var; otherwise uses the OS-appropriate data path via env-paths (XDG\_DATA\_HOME on Linux, Library/Application Support on macOS, %LOCALAPPDATA% on Windows).

**Signature**

```typescript theme={null}
() => string
```

## getCleoTemplatesDir()

Get the global CLEO templates directory.

**Signature**

```typescript theme={null}
() => string
```

## getCleoSchemasDir()

Get the global CLEO schemas directory.

**Signature**

```typescript theme={null}
() => string
```

## getCleoDocsDir()

Get the global CLEO docs directory.

**Signature**

```typescript theme={null}
() => string
```

## getCleoDir()

Get the project CLEO data directory (relative). Respects CLEO\_DIR env var, defaults to ".cleo".

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getCleoDirAbsolute()

Get the absolute path to the project CLEO directory.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getProjectRoot()

Get the project root from the CLEO directory. Respects CLEO\_ROOT env var, then derives from CLEO\_DIR. If CLEO\_DIR is ".cleo", the project root is its parent.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## resolveProjectPath()

Resolve a project-relative path to an absolute path.

**Signature**

```typescript theme={null}
(relativePath: string, cwd?: string | undefined) => string
```

## getTaskPath()

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

Get the path to the project's tasks.db file (SQLite database).

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getConfigPath()

Get the path to the project's config.json file.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getSessionsPath()

Get the path to the project's sessions.json file.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getArchivePath()

Get the path to the project's archive file.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getLogPath()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getBackupDir()

Get the backup directory for operational backups.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getGlobalConfigPath()

Get the global config file path.

**Signature**

```typescript theme={null}
() => string
```

## getAgentOutputsDir()

Get the agent outputs directory (relative path) from config or default.  Config lookup priority:   1. config.agentOutputs.directory   2. config.research.outputDir (deprecated)   3. config.directories.agentOutputs (deprecated)   4. Default: '.cleo/agent-outputs'   T4700

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getAgentOutputsAbsolute()

Get the absolute path to the agent outputs directory.  T4700

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getManifestPath()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getManifestArchivePath()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## isAbsolutePath()

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

**Signature**

```typescript theme={null}
(path: string) => boolean
```

## getCleoLogDir()

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

**Signature**

```typescript theme={null}
() => string
```

## getCleoCacheDir()

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

**Signature**

```typescript theme={null}
() => string
```

## getCleoTempDir()

Get the OS temp directory for CLEO ephemeral files.

**Signature**

```typescript theme={null}
() => string
```

## getCleoConfigDir()

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

**Signature**

```typescript theme={null}
() => string
```

## getAgentsHome()

Get the global agents hub directory. Respects AGENTS\_HOME env var, defaults to \~/.agents.

**Signature**

```typescript theme={null}
() => string
```

## getClaudeAgentsDir()

> **Deprecated**: Use AdapterPathProvider.getAgentInstallDir() from the active adapter instead.

Get the Claude Code agents directory (\~/.claude/agents by default).

**Signature**

```typescript theme={null}
() => string
```

## getClaudeMemDbPath()

> **Deprecated**: Use AdapterPathProvider.getMemoryDbPath() from the active adapter instead. Respects CLAUDE\_MEM\_DB env var, defaults to \~/.claude-mem/claude-mem.db. This is a third-party tool path; homedir() is correct here (no env-paths standard).

Get the claude-mem SQLite database path.

**Signature**

```typescript theme={null}
() => string
```

## vacuumIntoBackup()

Create a VACUUM INTO snapshot of the SQLite database.  Debounced by default (30s). Pass `force: true` to bypass debounce. WAL checkpoint is run before the snapshot for consistency. Oldest snapshots are rotated out when MAX\_SNAPSHOTS is reached.  Non-fatal: all errors are swallowed.

**Signature**

```typescript theme={null}
(opts?: VacuumOptions) => Promise<void>
```

## listSqliteBackups()

List existing SQLite backup snapshots, newest first.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { name: string; path: string; mtimeMs: number; }[]
```

## getBrainDbPath()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## resolveBrainMigrationsFolder()

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

**Signature**

```typescript theme={null}
() => string
```

## isBrainVecLoaded()

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

**Signature**

```typescript theme={null}
() => boolean
```

## getBrainDb()

Initialize the brain.db SQLite database (lazy, singleton). Creates the database file and tables if they don't exist. Returns the drizzle ORM instance (async via sqlite-proxy).  Uses a promise guard so concurrent callers wait for the same initialization to complete (migrations are async).

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<NodeSQLiteDatabase<typeof import("/mnt/projects/cleocode/packages/core/src/store/brain-schema", { with: { "resolution-mode": "import" } }), EmptyRelations>>
```

## closeBrainDb()

Close the brain.db database connection and release resources.

**Signature**

```typescript theme={null}
() => void
```

## resetBrainDbState()

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

**Signature**

```typescript theme={null}
() => void
```

## getBrainNativeDb()

Get the underlying node:sqlite DatabaseSync instance for brain.db. Useful for direct PRAGMA calls or raw SQL operations. Returns null if the database hasn't been initialized.

**Signature**

```typescript theme={null}
() => DatabaseSync | null
```

## getNexusDbPath()

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

**Signature**

```typescript theme={null}
() => string
```

## resolveNexusMigrationsFolder()

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

**Signature**

```typescript theme={null}
() => string
```

## getNexusDb()

Initialize the nexus.db SQLite database (lazy, singleton). Creates the database file and tables if they don't exist. Returns the drizzle ORM instance (async via sqlite-proxy).  Uses a promise guard so concurrent callers wait for the same initialization to complete (migrations are async).

**Signature**

```typescript theme={null}
() => Promise<NodeSQLiteDatabase<typeof import("/mnt/projects/cleocode/packages/core/src/store/nexus-schema", { with: { "resolution-mode": "import" } }), EmptyRelations>>
```

## closeNexusDb()

Close the nexus.db database connection and release resources.

**Signature**

```typescript theme={null}
() => void
```

## resetNexusDbState()

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

**Signature**

```typescript theme={null}
() => void
```

## getNexusNativeDb()

Get the underlying node:sqlite DatabaseSync instance for nexus.db. Useful for direct PRAGMA calls or raw SQL operations. Returns null if the database hasn't been initialized.

**Signature**

```typescript theme={null}
() => DatabaseSync | null
```

## openNativeDatabase()

Open a node:sqlite DatabaseSync with CLEO standard pragmas.  CRITICAL: WAL mode is verified, not just requested. If another process holds an EXCLUSIVE lock in DELETE mode, PRAGMA journal\_mode=WAL silently returns 'delete'. This caused data loss (T5173) when concurrent MCP servers opened the same database — writes were silently dropped under lock contention.

**Signature**

```typescript theme={null}
(path: string, options?: { readonly?: boolean | undefined; timeout?: number | undefined; enableWal?: boolean | undefined; allowExtension?: boolean | undefined; } | undefined) => DatabaseSync
```

## getDbPath()

Get the path to the SQLite database file.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getDb()

Initialize the SQLite database (lazy, singleton). Creates the database file and tables if they don't exist. Returns the drizzle ORM instance (node-sqlite driver).  Uses a promise guard so concurrent callers wait for the same initialization to complete (migrations are async).

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<NodeSQLiteDatabase<typeof import("/mnt/projects/cleocode/packages/core/src/store/tasks-schema", { with: { "resolution-mode": "import" } }), EmptyRelations>>
```

## resolveMigrationsFolder()

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

**Signature**

```typescript theme={null}
() => string
```

## isSqliteBusy()

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

**Signature**

```typescript theme={null}
(err: unknown) => boolean
```

## closeDb()

Close the database connection and release resources.

**Signature**

```typescript theme={null}
() => void
```

## resetDbState()

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

**Signature**

```typescript theme={null}
() => void
```

## getSchemaVersion()

Get the schema version from the database.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<string | null>
```

## dbExists()

Check if the database file exists.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => boolean
```

## getNativeDb()

Get the underlying node:sqlite DatabaseSync instance. Useful for direct PRAGMA calls or raw SQL operations. Returns null if the database hasn't been initialized.

**Signature**

```typescript theme={null}
() => DatabaseSync | null
```

## getNativeTasksDb()

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

**Signature**

```typescript theme={null}
() => DatabaseSync | null
```

## closeAllDatabases()

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

**Signature**

```typescript theme={null}
() => Promise<void>
```

## safeParseJson()

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

**Signature**

```typescript theme={null}
<T>(str: string | null | undefined) => T | undefined
```

## safeParseJsonArray()

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

**Signature**

```typescript theme={null}
<T = string>(str: string | null | undefined) => T[] | undefined
```

## rowToTask()

Convert a database TaskRow to a domain Task object.

**Signature**

```typescript theme={null}
(row: { sessionId: string | null; id: string; description: string | null; createdAt: string; updatedAt: string | null; status: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived"; ... 24 more ...; modifiedBy: string | null; }) => Task
```

## taskToRow()

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

**Signature**

```typescript theme={null}
(task: Partial<Task> & { id: string; }) => { id: string; title: string; sessionId?: string | null | undefined; description?: string | null | undefined; createdAt?: string | undefined; ... 25 more ...; modifiedBy?: string | ... 1 more ... | undefined; }
```

## archivedTaskToRow()

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

**Signature**

```typescript theme={null}
(task: Task) => { id: string; title: string; sessionId?: string | null | undefined; description?: string | null | undefined; createdAt?: string | undefined; updatedAt?: string | null | undefined; ... 24 more ...; modifiedBy?: string | ... 1 more ... | undefined; }
```

## rowToSession()

Convert a SessionRow to a domain Session.

**Signature**

```typescript theme={null}
(row: { gradeMode: number | null; id: string; name: string; status: "active" | "ended" | "orphaned" | "suspended"; agent: string | null; notesJson: string | null; scopeJson: string; currentTask: string | null; ... 14 more ...; resumeCount: number | null; }) => Session
```

## getErrorDefinition()

Look up an error definition by exit code.

**Signature**

```typescript theme={null}
(code: number) => ErrorDefinition | undefined
```

## getErrorDefinitionByLafsCode()

Look up an error definition by LAFS string code.

**Signature**

```typescript theme={null}
(lafsCode: string) => ErrorDefinition | undefined
```

## getAllErrorDefinitions()

Get all error definitions as an array.

**Signature**

```typescript theme={null}
() => ErrorDefinition[]
```

## CleoError

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

**Signature**

```typescript theme={null}
typeof CleoError
```

**Methods**

### toLAFSError()

Produce a LAFS-conformant error object.   T4655

```typescript theme={null}
() => LAFSError
```

### toProblemDetails()

Produce an RFC 9457 Problem Details object.   T5240

```typescript theme={null}
() => ProblemDetails
```

### toJSON()

Structured JSON representation for LAFS output (backward compatible).

```typescript theme={null}
() => Record<string, unknown>
```

### getHttpStatus()

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

```typescript theme={null}
() => number
```

## upsertTask()

Upsert a single task row into the tasks table. Handles both active task upsert and archived task upsert via optional archiveFields.  Defensively nulls out parentId if it references a non-existent task, preventing orphaned FK violations from blocking bulk operations (T5034).

**Signature**

```typescript theme={null}
(db: DrizzleDb, row: { id: string; title: string; sessionId?: string | null | undefined; description?: string | null | undefined; createdAt?: string | undefined; updatedAt?: string | null | undefined; ... 24 more ...; modifiedBy?: string | ... 1 more ... | undefined; }, archiveFields?: ArchiveFields | undefined) => ...
```

## upsertSession()

Upsert a single session row into the sessions table.

**Signature**

```typescript theme={null}
(db: DrizzleDb, session: Session) => Promise<void>
```

## updateDependencies()

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

**Signature**

```typescript theme={null}
(db: DrizzleDb, taskId: string, depends: string[], validIds?: Set<string> | undefined) => Promise<void>
```

## batchUpdateDependencies()

Batch-update dependencies for multiple tasks in two bulk SQL operations. Replaces per-task updateDependencies() loops with: 1. Single DELETE for all task IDs 2. Single INSERT for all dependency rows  Callers are responsible for wrapping this in a transaction if needed.

**Signature**

```typescript theme={null}
(db: DrizzleDb, tasks: { taskId: string; deps: string[]; }[], validIds?: Set<string> | undefined) => Promise<void>
```

## loadDependenciesForTasks()

Batch-load dependencies for a list of tasks and apply them in-place. Uses inArray for efficient querying. Optionally filters by a set of valid IDs.

**Signature**

```typescript theme={null}
(db: DrizzleDb, tasks: Task[], validationIds?: Set<string> | undefined) => Promise<void>
```

## loadRelationsForTasks()

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

**Signature**

```typescript theme={null}
(db: DrizzleDb, tasks: Task[]) => Promise<void>
```

## setMetaValue()

Write a JSON blob to the schema\_meta table by key.

**Signature**

```typescript theme={null}
(cwd: string | undefined, key: string, value: unknown) => Promise<void>
```

## createSqliteDataAccessor(cwd)

Create a SQLite-backed DataAccessor.  Opens (or creates) the SQLite database at `.cleo/tasks.db` and returns a DataAccessor that materializes/dematerializes whole-file structures from the relational tables.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<DataAccessor>
```

**Parameters**

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

**Signature**

```typescript theme={null}
(filePath: string, data: string, options?: { mode?: number | undefined; encoding?: BufferEncoding | undefined; } | undefined) => Promise<void>
```

## safeReadFile()

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

**Signature**

```typescript theme={null}
(filePath: string) => Promise<string | null>
```

## atomicWriteJson()

Write JSON data atomically with consistent formatting.

**Signature**

```typescript theme={null}
(filePath: string, data: unknown, options?: { indent?: number | undefined; } | undefined) => Promise<void>
```

## atomicDatabaseMigration(dbPath, tempPath, validateFn)

Perform atomic database migration using rename operations.  Pattern:   1. Write new database to temp file (tasks.db.new)   2. Validate temp database integrity   3. Rename existing tasks.db → tasks.db.backup   4. Rename temp → tasks.db (atomic)   5. Only delete backup on success

**Signature**

```typescript theme={null}
(dbPath: string, tempPath: string, validateFn: (path: string) => Promise<boolean>) => Promise<AtomicMigrationResult>
```

**Parameters**

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

**Returns** — Result with paths and success status

## restoreDatabaseFromBackup(dbPath, backupPath)

Restore database from backup after failed migration.

**Signature**

```typescript theme={null}
(dbPath: string, backupPath: string) => Promise<boolean>
```

**Parameters**

| Name         | Type     | Description               |
| ------------ | -------- | ------------------------- |
| `dbPath`     | `string` | Path to the database file |
| `backupPath` | `string` | Path to the backup file   |

**Returns** — true if restore succeeded

## cleanupMigrationArtifacts(backupPath)

Clean up migration artifacts after successful migration.

**Signature**

```typescript theme={null}
(backupPath: string) => Promise<boolean>
```

**Parameters**

| Name         | Type     | Description                   |
| ------------ | -------- | ----------------------------- |
| `backupPath` | `string` | Path to backup file to delete |

**Returns** — true if cleanup succeeded

## validateSqliteDatabase(dbPath)

Validate SQLite database integrity by attempting to open it.

**Signature**

```typescript theme={null}
(dbPath: string) => Promise<boolean>
```

**Parameters**

| Name     | Type     | Description           |
| -------- | -------- | --------------------- |
| `dbPath` | `string` | Path to database file |

**Returns** — true if database is valid

## createBackup()

Create a numbered backup of a file. Rotates existing backups (file.1 - file.2, etc.) and removes excess.

**Signature**

```typescript theme={null}
(filePath: string, backupDir: string, maxBackups?: number) => Promise<string>
```

## listBackups()

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

**Signature**

```typescript theme={null}
(fileName: string, backupDir: string) => Promise<string[]>
```

## restoreFromBackup()

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

**Signature**

```typescript theme={null}
(fileName: string, backupDir: string, targetPath: string) => Promise<string>
```

## acquireLock()

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

**Signature**

```typescript theme={null}
(filePath: string, options?: { stale?: number | undefined; retries?: number | undefined; } | undefined) => Promise<ReleaseFn>
```

## isLocked()

Check if a file is currently locked.

**Signature**

```typescript theme={null}
(filePath: string) => Promise<boolean>
```

## withLock()

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

**Signature**

```typescript theme={null}
<T>(filePath: string, fn: () => Promise<T>, options?: { stale?: number | undefined; retries?: number | undefined; } | undefined) => Promise<T>
```

## isProviderHookEvent()

Type guard for CAAMP/provider-discoverable hook events.

**Signature**

```typescript theme={null}
(event: HookEvent) => event is HookEvent
```

## isInternalHookEvent()

Type guard for CLEO-local coordination hook events.

**Signature**

```typescript theme={null}
(event: HookEvent) => event is "onWorkAvailable" | "onAgentSpawn" | "onAgentComplete" | "onCascadeStart" | "onPatrol"
```

## HookRegistry

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

**Signature**

```typescript theme={null}
typeof HookRegistry
```

**Methods**

### register()

Register a hook handler for a specific event.  Handlers are sorted by priority (highest first) and executed in parallel when the event is dispatched.

```typescript theme={null}
<T extends HookPayload>(registration: HookRegistration<T>) => () => void
```

### dispatch()

Dispatch an event to all registered handlers.  Executes handlers in parallel using Promise.allSettled for best-effort execution. Errors in individual handlers are logged but do not block other handlers or propagate to the caller.

```typescript theme={null}
<T extends HookPayload>(event: HookEvent, projectRoot: string, payload: T) => Promise<void>
```

### isEnabled()

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

```typescript theme={null}
(event: HookEvent) => boolean
```

### setConfig()

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

```typescript theme={null}
(config: Partial<HookConfig>) => void
```

### getConfig()

Get the current hook configuration.

```typescript theme={null}
() => HookConfig
```

### listHandlers()

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

```typescript theme={null}
(event: HookEvent) => HookRegistration<HookPayload>[]
```

## readJson()

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

**Signature**

```typescript theme={null}
<T = unknown>(filePath: string) => Promise<T | null>
```

## readJsonRequired()

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

**Signature**

```typescript theme={null}
<T = unknown>(filePath: string) => Promise<T>
```

## computeChecksum()

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

**Signature**

```typescript theme={null}
(data: unknown) => string
```

## saveJson()

Save JSON data with optional locking, backup, and validation. Follows the CLEO atomic write pattern:   1. Acquire lock   2. Validate data   3. Create backup of existing file   4. Atomic write (temp file - rename)   5. Release lock

**Signature**

```typescript theme={null}
(filePath: string, data: unknown, options?: SaveJsonOptions | undefined) => Promise<void>
```

## appendJsonl()

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

**Signature**

```typescript theme={null}
(filePath: string, entry: unknown) => Promise<void>
```

## readLogEntries()

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

**Signature**

```typescript theme={null}
(filePath: string) => Promise<Record<string, unknown>[]>
```

## makeCleoGitEnv()

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

**Signature**

```typescript theme={null}
(cleoDir: string) => ProcessEnv
```

## cleoGitCommand()

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

**Signature**

```typescript theme={null}
(args: string[], cleoDir: string) => Promise<{ stdout: string; success: boolean; }>
```

## isCleoGitInitialized()

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

**Signature**

```typescript theme={null}
(cleoDir: string) => boolean
```

## loadStateFileAllowlist()

Load additional state file paths from config.json `checkpoint.stateFileAllowlist`. Returns an empty array if config is missing, malformed, or the key is absent.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<string[]>
```

## loadCheckpointConfig()

Load checkpoint configuration from config.json.  T4552

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<CheckpointConfig>
```

## shouldCheckpoint()

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

**Signature**

```typescript theme={null}
(options?: { force?: boolean | undefined; cwd?: string | undefined; } | undefined) => Promise<boolean>
```

## gitCheckpoint()

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

**Signature**

```typescript theme={null}
(trigger?: "manual" | "auto" | "session-end", context?: string | undefined, cwd?: string | undefined) => Promise<void>
```

## gitCheckpointStatus()

Show checkpoint configuration and status.  T4552  T4872

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<CheckpointStatus>
```

## gitCheckpointDryRun()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<ChangedFile[]>
```

## DataSafetyError

Safety violation error

**Signature**

```typescript theme={null}
typeof DataSafetyError
```

## getSafetyStats()

Get current safety statistics

**Signature**

```typescript theme={null}
() => SafetyStats
```

## resetSafetyStats()

Reset safety statistics (for testing)

**Signature**

```typescript theme={null}
() => void
```

## safeSaveSessions()

Safe wrapper for DataAccessor.saveSessions()

**Signature**

```typescript theme={null}
(accessor: DataAccessor, data: Session[], cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<void>
```

## safeSaveArchive()

Safe wrapper for DataAccessor.saveArchive()

**Signature**

```typescript theme={null}
(accessor: DataAccessor, data: ArchiveFile, cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<...>
```

## safeSingleTaskWrite()

Safe wrapper for single-task write operations (T5034).  Performs: 1. Sequence validation 2. Write operation (caller-provided function) 3. Git checkpoint  Verification is lightweight — no full-file read-back. The write itself is a targeted SQL operation that either succeeds or throws.

**Signature**

```typescript theme={null}
(_accessor: DataAccessor, taskId: string, writeFn: () => Promise<void>, cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<...>
```

## safeAppendLog()

Safe wrapper for DataAccessor.appendLog()  Note: Log appends are fire-and-forget (no verification) but we still checkpoint to ensure data is committed.

**Signature**

```typescript theme={null}
(accessor: DataAccessor, entry: Record<string, unknown>, cwd?: string | undefined, options?: Partial<SafetyOptions> | undefined) => Promise<...>
```

## runDataIntegrityCheck()

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

**Signature**

```typescript theme={null}
(accessor: DataAccessor, cwd?: string | undefined) => Promise<{ passed: boolean; errors: string[]; warnings: string[]; stats: SafetyStats; }>
```

## forceSafetyCheckpoint()

Force immediate checkpoint. Use before destructive operations.

**Signature**

```typescript theme={null}
(context: string, cwd?: string | undefined) => Promise<void>
```

## disableSafety()

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

**Signature**

```typescript theme={null}
() => void
```

## enableSafety()

Re-enable safety after being disabled.

**Signature**

```typescript theme={null}
() => void
```

## SafetyDataAccessor

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

**Signature**

```typescript theme={null}
typeof SafetyDataAccessor
```

**Methods**

### logVerbose()

Log safety operation if verbose mode is enabled.

```typescript theme={null}
(message: string) => void
```

### getSafetyOptions()

Get safety options for data-safety-central operations.

```typescript theme={null}
() => Partial<SafetyOptions>
```

### loadArchive()

```typescript theme={null}
() => Promise<ArchiveFile | null>
```

### loadSessions()

```typescript theme={null}
() => Promise<Session[]>
```

### saveSessions()

```typescript theme={null}
(data: Session[]) => Promise<void>
```

### saveArchive()

```typescript theme={null}
(data: ArchiveFile) => Promise<void>
```

### appendLog()

```typescript theme={null}
(entry: Record<string, unknown>) => Promise<void>
```

### upsertSingleTask()

```typescript theme={null}
(task: Task) => Promise<void>
```

### archiveSingleTask()

```typescript theme={null}
(taskId: string, fields: ArchiveFields) => Promise<void>
```

### removeSingleTask()

```typescript theme={null}
(taskId: string) => Promise<void>
```

### loadSingleTask()

```typescript theme={null}
(taskId: string) => Promise<Task | null>
```

### addRelation()

```typescript theme={null}
(taskId: string, relatedTo: string, relationType: string, reason?: string | undefined) => Promise<void>
```

### getMetaValue()

```typescript theme={null}
<T>(key: string) => Promise<T | null>
```

### setMetaValue()

```typescript theme={null}
(key: string, value: unknown) => Promise<void>
```

### getSchemaVersion()

```typescript theme={null}
() => Promise<string | null>
```

### queryTasks()

```typescript theme={null}
(filters: TaskQueryFilters) => Promise<QueryTasksResult>
```

### countTasks()

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

### getChildren()

```typescript theme={null}
(parentId: string) => Promise<Task[]>
```

### countChildren()

```typescript theme={null}
(parentId: string) => Promise<number>
```

### countActiveChildren()

```typescript theme={null}
(parentId: string) => Promise<number>
```

### getAncestorChain()

```typescript theme={null}
(taskId: string) => Promise<Task[]>
```

### getSubtree()

```typescript theme={null}
(rootId: string) => Promise<Task[]>
```

### getDependents()

```typescript theme={null}
(taskId: string) => Promise<Task[]>
```

### getDependencyChain()

```typescript theme={null}
(taskId: string) => Promise<string[]>
```

### taskExists()

```typescript theme={null}
(taskId: string) => Promise<boolean>
```

### loadTasks()

```typescript theme={null}
(taskIds: string[]) => Promise<Task[]>
```

### updateTaskFields()

```typescript theme={null}
(taskId: string, fields: TaskFieldUpdates) => Promise<void>
```

### getNextPosition()

```typescript theme={null}
(parentId: string | null) => Promise<number>
```

### shiftPositions()

```typescript theme={null}
(parentId: string | null, fromPosition: number, delta: number) => Promise<void>
```

### transaction()

```typescript theme={null}
<T>(fn: (tx: TransactionAccessor) => Promise<T>) => Promise<T>
```

### getActiveSession()

```typescript theme={null}
() => Promise<Session | null>
```

### upsertSingleSession()

```typescript theme={null}
(session: Session) => Promise<void>
```

### removeSingleSession()

```typescript theme={null}
(sessionId: string) => Promise<void>
```

### close()

```typescript theme={null}
() => Promise<void>
```

## wrapWithSafety(accessor, cwd)

Wrap a DataAccessor with safety.  This is the internal factory helper that wraps any accessor with the SafetyDataAccessor wrapper.

**Signature**

```typescript theme={null}
(accessor: DataAccessor, cwd?: string | undefined) => DataAccessor
```

**Parameters**

| Name       | Type                    | Description          |
| ---------- | ----------------------- | -------------------- |
| `accessor` | `DataAccessor`          | The accessor to wrap |
| `cwd`      | `: string \| undefined` | Working directory    |

**Returns** — SafetyDataAccessor wrapping the input

## isSafetyEnabled()

Check if safety is currently enabled.

**Signature**

```typescript theme={null}
() => boolean
```

**Returns** — true if safety checks are active

## getSafetyStatus()

Get safety status information.

**Signature**

```typescript theme={null}
() => { enabled: boolean; reason?: string | undefined; }
```

**Returns** — Object with safety status details

## createDataAccessor()

Create a DataAccessor for the given working directory. Always creates a SQLite accessor (ADR-006 canonical storage).  ALL accessors returned are safety-enabled by default via SafetyDataAccessor wrapper. Use CLEO\_DISABLE\_SAFETY=true to bypass (emergency only).

**Signature**

```typescript theme={null}
(_engine?: "sqlite" | undefined, cwd?: string | undefined) => Promise<DataAccessor>
```

## getAccessor()

Convenience: get a DataAccessor with auto-detected engine.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<DataAccessor>
```

## showSequence()

Show current sequence state.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## checkSequence()

Check sequence integrity.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## repairSequence()

Repair sequence if behind.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<RepairResult>
```

## allocateNextTaskId()

Atomically allocate the next task ID via SQLite.  Uses BEGIN IMMEDIATE to guarantee no two concurrent callers receive the same ID, even across processes (WAL mode).  Falls back to repair+retry if the sequence counter is behind the actual max task ID (e.g., stale counter from installations that never incremented it).   T5184

**Signature**

```typescript theme={null}
(cwd?: string | undefined, retryCount?: number) => Promise<string>
```

## SafetyError

Safety violation error.

**Signature**

```typescript theme={null}
typeof SafetyError
```

## checkTaskExists()

Check if a task ID already exists (collision detection).

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>
```

**Throws**

* SafetyError if task exists and strict mode is enabled

## verifyTaskWrite()

Verify a task was actually written to the database.

**Signature**

```typescript theme={null}
(taskId: string, expectedData?: Partial<Task> | undefined, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>
```

**Throws**

* SafetyError if verification fails

## validateAndRepairSequence()

Validate and repair sequence if necessary.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<{ valid: boolean; repaired: boolean; oldCounter?: number | undefined; newCounter?: number | undefined; }>
```

**Returns** — true if sequence was valid or successfully repaired

## triggerCheckpoint()

Trigger auto-checkpoint after successful write.

**Signature**

```typescript theme={null}
(context: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<void>
```

## safeCreateTask()

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

**Signature**

```typescript theme={null}
(createFn: () => Promise<Task>, task: Task, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<Task>
```

## safeUpdateTask()

Safely update a task with all safety mechanisms.

**Signature**

```typescript theme={null}
(updateFn: () => Promise<Task | null>, taskId: string, _updates: Partial<Task>, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<...>
```

## safeDeleteTask()

Safely delete a task with all safety mechanisms.

**Signature**

```typescript theme={null}
(deleteFn: () => Promise<boolean>, taskId: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>
```

## verifySessionWrite()

Verify session write.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<boolean>
```

## safeCreateSession()

Safely create a session with all safety mechanisms.

**Signature**

```typescript theme={null}
(createFn: () => Promise<Session>, session: Session, cwd?: string | undefined, config?: Partial<SafetyConfig>) => Promise<Session>
```

## forceCheckpointBeforeOperation()

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

**Signature**

```typescript theme={null}
(operation: string, cwd?: string | undefined) => Promise<void>
```

## runDataIntegrityCheck()

Run comprehensive data integrity check. Reports all issues found.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ passed: boolean; issues: string[]; repairs: string[]; }>
```

## getTask()

Get a task by ID, including its dependencies.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<Task | null>
```

## updateTask()

Update an existing task.

**Signature**

```typescript theme={null}
(taskId: string, updates: Partial<Task>, cwd?: string | undefined) => Promise<Task | null>
```

## deleteTask()

Delete a task by ID.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<boolean>
```

## listTasks()

List tasks with optional filters.

**Signature**

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

## findTasks()

Find tasks by fuzzy text search.

**Signature**

```typescript theme={null}
(query: string, limit?: number, cwd?: string | undefined) => Promise<Task[]>
```

## archiveTask()

Archive a task (sets status to 'archived' with metadata).

**Signature**

```typescript theme={null}
(taskId: string, reason?: string | undefined, cwd?: string | undefined) => Promise<boolean>
```

## addDependency()

Add a dependency between tasks.

**Signature**

```typescript theme={null}
(taskId: string, dependsOn: string, cwd?: string | undefined) => Promise<void>
```

## removeDependency()

Remove a dependency.

**Signature**

```typescript theme={null}
(taskId: string, dependsOn: string, cwd?: string | undefined) => Promise<void>
```

## addRelation()

Add a relation between tasks.

**Signature**

```typescript theme={null}
(taskId: string, relatedTo: string, relationType?: "related" | "blocks" | "duplicates" | "absorbs" | "fixes" | "extends" | "supersedes", cwd?: string | undefined, reason?: string | undefined) => Promise<...>
```

## getRelations()

Get relations for a task.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<{ relatedTo: string; type: string; reason?: string | undefined; }[]>
```

## getBlockerChain()

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

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<string[]>
```

## getChildren()

Get children of a task (hierarchy).

**Signature**

```typescript theme={null}
(parentId: string, cwd?: string | undefined) => Promise<Task[]>
```

## getSubtree()

Build a tree from a root task using recursive CTE.

**Signature**

```typescript theme={null}
(rootId: string, cwd?: string | undefined) => Promise<Task[]>
```

## countByStatus()

Count tasks by status.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<Record<string, number>>
```

## countTasks()

Get total task count (excluding archived).

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<number>
```

## createTask()

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

**Signature**

```typescript theme={null}
(task: Task, cwd?: string | undefined, config?: Partial<SafetyConfig> | undefined) => Promise<Task>
```

## updateTaskSafe()

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

**Signature**

```typescript theme={null}
(taskId: string, updates: Partial<Task>, cwd?: string | undefined, config?: Partial<SafetyConfig> | undefined) => Promise<Task | null>
```

## deleteTaskSafe()

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

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, config?: Partial<SafetyConfig> | undefined) => Promise<boolean>
```

## showTask()

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

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskDetail>
```

## createPage()

Create an LAFSPage object from pagination parameters.  Returns mode:"none" when no pagination is requested (no limit/offset). Returns mode:"offset" with hasMore/total when pagination is active.   T4668  T4663

**Signature**

```typescript theme={null}
(input: PaginateInput) => LAFSPage
```

## paginate()

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

**Signature**

```typescript theme={null}
<T>(items: T[], limit?: number | undefined, offset?: number | undefined) => { items: T[]; page: LAFSPage; }
```

## toCompact()

Convert a full Task to compact representation.

**Signature**

```typescript theme={null}
(task: Task) => CompactTask
```

## listTasks()

List tasks with optional filtering and pagination.  T4460

**Signature**

```typescript theme={null}
(options?: ListTasksOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ListTasksResult>
```

## fuzzyScore()

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

**Signature**

```typescript theme={null}
(query: string, text: string) => number
```

## findTasks()

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

**Signature**

```typescript theme={null}
(options: FindTasksOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<FindTasksResult>
```

## extractAdrId()

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

**Signature**

```typescript theme={null}
(filename: string) => string
```

## parseFrontmatter()

Parse bold-key frontmatter pattern: **Key**: value

**Signature**

```typescript theme={null}
(content: string) => AdrFrontmatter
```

## extractTitle()

Extract H1 title from markdown

**Signature**

```typescript theme={null}
(content: string) => string
```

## parseAdrFile()

Parse a single ADR markdown file into an AdrRecord

**Signature**

```typescript theme={null}
(filePath: string, projectRoot: string) => AdrRecord
```

## linkPipelineAdr(projectRoot, taskId)

Link ADRs to a pipeline task when the architecture\_decision stage completes.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<PipelineAdrLinkResult>
```

**Parameters**

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<AdrSyncResult>
```

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

Record an evidence artifact linked to a lifecycle stage.  Writes to the SQLite `lifecycle_evidence` table.

**Signature**

```typescript theme={null}
(epicId: string, stage: string, uri: string, type: EvidenceType, options?: { agent?: string | undefined; description?: string | undefined; cwd?: string | undefined; } | undefined) => Promise<...>
```

**Parameters**

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

**Returns** — The created evidence record

## getEvidence(epicId, stage, cwd)

Query evidence records for an epic, optionally filtered by stage.

**Signature**

```typescript theme={null}
(epicId: string, stage?: string | undefined, cwd?: string | undefined) => Promise<EvidenceRecord[]>
```

**Parameters**

| Name     | Type                    | Description                |
| -------- | ----------------------- | -------------------------- |
| `epicId` | `string`                | Epic task ID               |
| `stage`  | `: string \| undefined` | Optional stage name filter |
| `cwd`    | `: string \| undefined` | Optional working directory |

**Returns** — Array of evidence records

## linkProvenance(epicId, stage, filePath, cwd)

Convenience wrapper to record a file as provenance evidence.  Converts the file path to a URI relative to the `.cleo/` directory, sets the type to 'file', and extracts a description from the filename.

**Signature**

```typescript theme={null}
(epicId: string, stage: string, filePath: string, cwd?: string | undefined) => Promise<EvidenceRecord>
```

**Parameters**

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

**Returns** — The created evidence record

## getEvidenceSummary(epicId, cwd)

Aggregate evidence counts per stage for an epic.

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<{ stage: string; count: number; types: Record<EvidenceType, number>; }[]>
```

**Parameters**

| Name     | Type                    | Description                |
| -------- | ----------------------- | -------------------------- |
| `epicId` | `string`                | Epic task ID               |
| `cwd`    | `: string \| undefined` | Optional working directory |

**Returns** — Array of per-stage summaries with type breakdowns

## normalizeEpicId(dirName)

Strip suffixes from epic directory names. E.g. `T4881_install-channels` - `T4881`

**Signature**

```typescript theme={null}
(dirName: string) => string
```

**Parameters**

| Name      | Type     | Description                              |
| --------- | -------- | ---------------------------------------- |
| `dirName` | `string` | Directory name that may contain a suffix |

**Returns** — The normalized T#### epic ID

## getRcasdBaseDir(cwd)

Get the absolute path to the `.cleo/rcasd/` base directory.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

**Parameters**

| Name  | Type                    | Description                         |
| ----- | ----------------------- | ----------------------------------- |
| `cwd` | `: string \| undefined` | Optional working directory override |

**Returns** — Absolute path to the rcasd base directory

## getEpicDir(epicId, cwd)

Get the absolute path to `.cleo/rcasd/\{epicId\}/`. Uses the normalized epic ID (without suffixes).

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => string
```

**Parameters**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| `epicId` | `string`                | Epic identifier (e.g. `T4881`)      |
| `cwd`    | `: string \| undefined` | Optional working directory override |

**Returns** — Absolute path to the epic directory

## findEpicDir(epicId, cwd)

Search both `rcasd/` and legacy `rcsd/` for an existing epic directory. Also checks suffixed directory names (e.g. `T4881_install-channels` matches `T4881`).

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => string | null
```

**Parameters**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| `epicId` | `string`                | Epic identifier to search for       |
| `cwd`    | `: string \| undefined` | Optional working directory override |

**Returns** — Absolute path to the found directory, or null

## getStagePath(epicId, stage, cwd)

Get the stage subdirectory path for an epic. Uses STAGE\_SUBDIRS mapping, falling back to the raw stage name.

**Signature**

```typescript theme={null}
(epicId: string, stage: string, cwd?: string | undefined) => string
```

**Parameters**

| Name     | Type                    | Description                                            |
| -------- | ----------------------- | ------------------------------------------------------ |
| `epicId` | `string`                | Epic identifier                                        |
| `stage`  | `string`                | Canonical stage name (e.g. `research`, `contribution`) |
| `cwd`    | `: string \| undefined` | Optional working directory override                    |

**Returns** — Absolute path to the stage subdirectory

## ensureStagePath(epicId, stage, cwd)

Get the stage subdirectory path, creating it if it does not exist.

**Signature**

```typescript theme={null}
(epicId: string, stage: string, cwd?: string | undefined) => string
```

**Parameters**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| `epicId` | `string`                | Epic identifier                     |
| `stage`  | `string`                | Canonical stage name                |
| `cwd`    | `: string \| undefined` | Optional working directory override |

**Returns** — Absolute path to the (now existing) stage subdirectory

## getManifestPath(epicId, cwd)

Get the manifest path for an epic under the default rcasd directory.

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => string
```

**Parameters**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| `epicId` | `string`                | Epic identifier                     |
| `cwd`    | `: string \| undefined` | Optional working directory override |

**Returns** — Absolute path to `.cleo/rcasd/\{epicId\}/_manifest.json`

## findManifestPath(epicId, cwd)

Search both `rcasd/` and `rcsd/` for an existing manifest file. Checks suffixed directory names as well.

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => string | null
```

**Parameters**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| `epicId` | `string`                | Epic identifier                     |
| `cwd`    | `: string \| undefined` | Optional working directory override |

**Returns** — Absolute path to the found manifest, or null

## getLooseResearchFiles(cwd)

Scan the rcasd root directory for loose `T####_*.md` files that are not inside subdirectories.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { file: string; epicId: string; fullPath: string; }[]
```

**Parameters**

| Name  | Type                    | Description                         |
| ----- | ----------------------- | ----------------------------------- |
| `cwd` | `: string \| undefined` | Optional working directory override |

**Returns** — Array of file info with extracted epic ID

## listEpicDirs(cwd)

List all epic directories across `rcasd/` and `rcsd/`.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { epicId: string; dirName: string; fullPath: string; }[]
```

**Parameters**

| Name  | Type                    | Description                         |
| ----- | ----------------------- | ----------------------------------- |
| `cwd` | `: string \| undefined` | Optional working directory override |

**Returns** — Array of epic info with normalized IDs and original directory names

## parseFrontmatter(content)

Parse YAML frontmatter from a markdown string.  Finds the YAML block delimited by `---` at the start of the file, parses key-value pairs, and returns the structured metadata plus the remaining body content.

**Signature**

```typescript theme={null}
(content: string) => ParsedFrontmatter
```

**Parameters**

| Name      | Type     | Description                |
| --------- | -------- | -------------------------- |
| `content` | `string` | Full markdown file content |

**Returns** — Parsed frontmatter, body, and raw YAML block

## serializeFrontmatter(metadata)

Convert a FrontmatterMetadata object to a YAML frontmatter string.  Output format:

**Signature**

```typescript theme={null}
(metadata: FrontmatterMetadata) => string
```

**Parameters**

| Name       | Type                  | Description                           |
| ---------- | --------------------- | ------------------------------------- |
| `metadata` | `FrontmatterMetadata` | The frontmatter metadata to serialize |

**Returns** — YAML frontmatter string including `---` delimiters

## addFrontmatter(content, metadata)

Add or replace YAML frontmatter in markdown content.  If the content already has a frontmatter block, it is replaced. Otherwise the YAML block is prepended.

**Signature**

```typescript theme={null}
(content: string, metadata: FrontmatterMetadata) => string
```

**Parameters**

| Name       | Type                  | Description                 |
| ---------- | --------------------- | --------------------------- |
| `content`  | `string`              | Original markdown content   |
| `metadata` | `FrontmatterMetadata` | Frontmatter metadata to set |

**Returns** — Updated content with new frontmatter

## buildFrontmatter(epicId, stage, options)

Convenience builder for common frontmatter patterns.  Auto-sets `updated` to the current ISO date string.

**Signature**

```typescript theme={null}
(epicId: string, stage: string, options?: { task?: string | undefined; related?: RelatedLink[] | undefined; created?: string | undefined; } | undefined) => FrontmatterMetadata
```

**Parameters**

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

**Returns** — A FrontmatterMetadata object ready for serialization

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

```typescript theme={null}
(epicId: string, stage: string, cwd?: string | undefined) => { file: string; link: RelatedLink; }[]
```

**Parameters**

| Name     | Type                    | Description                         |
| -------- | ----------------------- | ----------------------------------- |
| `epicId` | `string`                | Epic identifier to search for       |
| `stage`  | `string`                | Stage name to search for            |
| `cwd`    | `: string \| undefined` | Optional working directory override |

**Returns** — Array of files with matching related links

## getStageOrder(stage)

Get the order/index of a stage (1-based).

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => number
```

**Parameters**

| Name    | Type                                                                                                                                                       | Description          |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `stage` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | The stage to look up |

**Returns** — The stage order (1-9)   T4800

## isStageBefore(stageA, stageB)

Check if stage A comes before stage B in the pipeline.

**Signature**

```typescript theme={null}
(stageA: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", stageB: "research" | ... 7 more ... | "release") => boolean
```

**Parameters**

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

**Returns** — True if stageA comes before stageB   T4800

## isStageAfter(stageA, stageB)

Check if stage A comes after stage B in the pipeline.

**Signature**

```typescript theme={null}
(stageA: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", stageB: "research" | ... 7 more ... | "release") => boolean
```

**Parameters**

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

**Returns** — True if stageA comes after stageB   T4800

## getNextStage(stage)

Get the next stage in the pipeline.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => "research" | ... 8 more ... | null
```

**Parameters**

| Name    | Type                                                                                                                                                       | Description   |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `stage` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | Current stage |

**Returns** — The next stage, or null if at the end   T4800

## getPreviousStage(stage)

Get the previous stage in the pipeline.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => "research" | ... 8 more ... | null
```

**Parameters**

| Name    | Type                                                                                                                                                       | Description   |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `stage` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | Current stage |

**Returns** — The previous stage, or null if at the start   T4800

## getStagesBetween(from, to)

Get all stages between two stages (inclusive).

**Signature**

```typescript theme={null}
(from: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", to: "research" | "consensus" | ... 6 more ... | "release") => ("research" | ... 7 more ... | "release")[]
```

**Parameters**

| Name   | Type                                                                                                                                                       | Description    |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
| `from` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | Starting stage |
| `to`   | `"research" \| "consensus" \| ... 6 more ... \| "release"`                                                                                                 | Ending stage   |

**Returns** — Array of stages between from and to   T4800

## getPrerequisites(stage)

Get prerequisites for a stage.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => ("research" | ... 7 more ... | "release")[]
```

**Parameters**

| Name    | Type                                                                                                                                                       | Description                        |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| `stage` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | The stage to get prerequisites for |

**Returns** — Array of prerequisite stages   T4800

## isPrerequisite(potentialPrereq, stage)

Check if one stage is a prerequisite of another.

**Signature**

```typescript theme={null}
(potentialPrereq: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", stage: "research" | ... 7 more ... | "release") => boolean
```

**Parameters**

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

**Returns** — True if potentialPrereq is required before stage   T4800

## getDependents(stage)

Get all stages that depend on a given stage.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => ("research" | ... 7 more ... | "release")[]
```

**Parameters**

| Name    | Type                                                                                                                                                       | Description                      |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| `stage` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | The stage to find dependents for |

**Returns** — Array of stages that require this stage   T4800

## isValidStage(stage)

Check if a stage name is valid.

**Signature**

```typescript theme={null}
(stage: string) => stage is "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"
```

**Parameters**

| Name    | Type     | Description            |
| ------- | -------- | ---------------------- |
| `stage` | `string` | Stage name to validate |

**Returns** — True if valid stage name   T4800

## validateStage(stage)

Validate a stage name and throw if invalid.

**Signature**

```typescript theme={null}
(stage: string) => "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release"
```

**Parameters**

| Name    | Type     | Description            |
| ------- | -------- | ---------------------- |
| `stage` | `string` | Stage name to validate |

**Returns** — The validated Stage   T4800

**Throws**

* Error If stage is invalid

## isValidStageStatus(status)

Check if a stage status is valid.

**Signature**

```typescript theme={null}
(status: string) => status is "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped"
```

**Parameters**

| Name     | Type     | Description        |
| -------- | -------- | ------------------ |
| `status` | `string` | Status to validate |

**Returns** — True if valid status   T4800

## getStagesByCategory(category)

Get stages by category.

**Signature**

```typescript theme={null}
(category: StageCategory) => ("research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release")[]
```

**Parameters**

| Name       | Type            | Description           |
| ---------- | --------------- | --------------------- |
| `category` | `StageCategory` | Category to filter by |

**Returns** — Array of stages in that category   T4800

## getSkippableStages()

Get skippable stages.

**Signature**

```typescript theme={null}
() => ("research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release")[]
```

**Returns** — Array of stages that can be skipped   T4800

## checkTransition(from, to, force)

Check if a transition is allowed.

**Signature**

```typescript theme={null}
(from: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", to: "research" | "consensus" | ... 6 more ... | "release", force?: boolean) => { ...; }
```

**Parameters**

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

**Returns** — Object with allowed flag and reason   T4800

## ensureStageArtifact()

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

**Signature**

```typescript theme={null}
(epicId: string, stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", cwd?: string | undefined) => Promise<...>
```

## getLifecycleState()

Get the current lifecycle state for an epic.  T4467

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<RcasdManifest>
```

## startStage()

Start a lifecycle stage.  T4467

**Signature**

```typescript theme={null}
(epicId: string, stage: string, cwd?: string | undefined) => Promise<StageTransitionResult>
```

## completeStage()

Complete a lifecycle stage.  T4467

**Signature**

```typescript theme={null}
(epicId: string, stage: string, artifacts?: string[] | undefined, cwd?: string | undefined) => Promise<StageTransitionResult>
```

## skipStage()

Skip a lifecycle stage.  T4467

**Signature**

```typescript theme={null}
(epicId: string, stage: string, reason: string, cwd?: string | undefined) => Promise<StageTransitionResult>
```

## checkGate()

Check lifecycle gate before starting a stage.  T4467

**Signature**

```typescript theme={null}
(epicId: string, targetStage: string, cwd?: string | undefined) => Promise<GateCheckResult>
```

## getLifecycleStatus()

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

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<{ epicId: string; title?: string | undefined; currentStage: "research" | "consensus" | "architecture_decision" | "specification" | ... 5 more ... | null; stages: { ...; }[]; nextStage: "research" | ... 8 more ... | null; blockedOn: string[]; initialized: boolean;...
```

## getLifecycleHistory()

Get lifecycle history for an epic. Returns stage transitions and gate events sorted by timestamp. SQLite-native implementation - queries lifecycle\_stages and lifecycle\_gate\_results tables.  T4785  T4801

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<{ epicId: string; history: LifecycleHistoryEntry[]; }>
```

## getLifecycleGates()

Get all gate statuses for an epic.  T4785

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<Record<string, Record<string, GateData>>>
```

## getStagePrerequisites()

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

**Signature**

```typescript theme={null}
(targetStage: string) => { prerequisites: string[]; stageInfo: { stage: string; name: string; description: string; order: number; } | undefined; }
```

## checkStagePrerequisites()

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

**Signature**

```typescript theme={null}
(epicId: string, targetStage: string, cwd?: string | undefined) => Promise<{ epicId: string; targetStage: string; valid: boolean; canProgress: boolean; missingPrerequisites: string[]; issues: { ...; }[]; }>
```

## recordStageProgress()

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

**Signature**

```typescript theme={null}
(epicId: string, stage: string, status: string, notes?: string | undefined, cwd?: string | undefined) => Promise<{ epicId: string; stage: string; status: string; timestamp: string; }>
```

## skipStageWithReason()

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

**Signature**

```typescript theme={null}
(epicId: string, stage: string, reason: string, cwd?: string | undefined) => Promise<{ epicId: string; stage: string; reason: string; timestamp: string; }>
```

## resetStage()

Reset a stage to pending (emergency).  T4785

**Signature**

```typescript theme={null}
(epicId: string, stage: string, reason: string, cwd?: string | undefined) => Promise<{ epicId: string; stage: string; reason: string; }>
```

## passGate()

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

**Signature**

```typescript theme={null}
(epicId: string, gateName: string, agent?: string | undefined, notes?: string | undefined, cwd?: string | undefined) => Promise<{ epicId: string; gateName: string; timestamp: string; }>
```

## failGate()

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

**Signature**

```typescript theme={null}
(epicId: string, gateName: string, reason?: string | undefined, cwd?: string | undefined) => Promise<{ epicId: string; gateName: string; reason?: string | undefined; timestamp: string; }>
```

## listEpicsWithLifecycle()

List all epic IDs that have lifecycle data.  T4785

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<string[]>
```

## getCurrentSessionId()

Get the current session ID.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string | null
```

## getContextStatePath()

Get context state file path for a session.

**Signature**

```typescript theme={null}
(sessionId?: string | undefined, cwd?: string | undefined) => string
```

## readContextState()

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

**Signature**

```typescript theme={null}
(sessionId?: string | undefined, cwd?: string | undefined) => Record<string, unknown> | null
```

## getThresholdLevel()

Determine the threshold level for a given percentage.

**Signature**

```typescript theme={null}
(percentage: number) => AlertLevel | null
```

## shouldAlert()

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

**Signature**

```typescript theme={null}
(currentPct: number, lastAlertedPct?: number, minThreshold?: AlertLevel) => AlertLevel | null
```

## getRecommendedAction()

Get recommended action for an alert level.

**Signature**

```typescript theme={null}
(percentage: number) => string | null
```

## checkContextAlert()

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

**Signature**

```typescript theme={null}
(currentCommand?: string | undefined, cwd?: string | undefined) => AlertCheckResult
```

## pushWarning()

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

**Signature**

```typescript theme={null}
(warning: Warning) => void
```

## formatSuccess()

Format a successful result as a full LAFS-conformant envelope.  Always produces the full LAFSEnvelope with \$schema and \_meta. When operation is omitted, defaults to 'cli.output'. Supports optional page (T4668) and \_extensions (T4670).   T4672  T4668  T4670  T4663

**Signature**

```typescript theme={null}
<T>(data: T, message?: string | undefined, operationOrOpts?: string | FormatOptions | undefined) => string
```

## formatError()

Format an error as a full LAFS-conformant envelope.  Always produces the full LAFSEnvelope with \$schema and \_meta. When operation is omitted, defaults to 'cli.output'.   T4672  T4663

**Signature**

```typescript theme={null}
(error: CleoError, operation?: string | undefined) => string
```

## formatOutput()

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

**Signature**

```typescript theme={null}
<T>(result: CleoError | T) => string
```

## getRegistryEntry()

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

**Signature**

```typescript theme={null}
(exitCode: ExitCode) => CleoRegistryEntry | undefined
```

## getRegistryEntryByLafsCode()

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

**Signature**

```typescript theme={null}
(lafsCode: string) => CleoRegistryEntry | undefined
```

## getCleoErrorRegistry()

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

**Signature**

```typescript theme={null}
() => CleoRegistryEntry[]
```

## isCleoRegisteredCode()

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

**Signature**

```typescript theme={null}
(lafsCode: string) => boolean
```

## createTestDb()

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

**Signature**

```typescript theme={null}
() => Promise<TestDbEnv>
```

## makeTaskFile()

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

**Signature**

```typescript theme={null}
(tasks: (Partial<Task> & { id: string; })[]) => TaskFile
```

## seedTasks()

Seed tasks into the test database via the accessor.  Uses a two-pass approach to avoid foreign key violations: 1. First pass: upsert all tasks without dependencies so FK targets exist 2. Second pass: upsert tasks again with dependencies (all FK targets now exist) 3. Initialize metadata for the test environment

**Signature**

```typescript theme={null}
(accessor: DataAccessor, tasks: (Partial<Task> & { id: string; })[]) => Promise<void>
```

## getChildren()

Get direct children of a task.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => Task[]
```

## getChildIds()

Get direct child IDs.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## getDescendants()

Get all descendants of a task (recursive).

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => Task[]
```

## getDescendantIds()

Get all descendant IDs (flat list).

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## getParentChain()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => Task[]
```

## getParentChainIds()

Get the parent chain as IDs.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## getDepth()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => number
```

## getRootAncestor()

Get the root ancestor of a task.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => Task | null
```

## isAncestorOf()

Check if a task is an ancestor of another.

**Signature**

```typescript theme={null}
(ancestorId: string, descendantId: string, tasks: Task[]) => boolean
```

## isDescendantOf()

Check if a task is a descendant of another.

**Signature**

```typescript theme={null}
(descendantId: string, ancestorId: string, tasks: Task[]) => boolean
```

## getSiblings()

Get sibling tasks (same parent).

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => Task[]
```

## validateHierarchy()

**Signature**

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

## wouldCreateCircle()

Detect circular reference if parentId were set.

**Signature**

```typescript theme={null}
(taskId: string, newParentId: string, tasks: Task[]) => boolean
```

## buildTree()

**Signature**

```typescript theme={null}
(tasks: Task[]) => TaskTreeNode[]
```

## flattenTree()

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

**Signature**

```typescript theme={null}
(nodes: TaskTreeNode[]) => Task[]
```

## resolveHierarchyPolicy()

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

**Signature**

```typescript theme={null}
(config: CleoConfig) => HierarchyPolicy
```

## assertParentExists()

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

**Signature**

```typescript theme={null}
(parentId: string, tasks: Task[]) => HierarchyValidationResult | null
```

## assertNoCycle()

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

**Signature**

```typescript theme={null}
(taskId: string, newParentId: string, tasks: Task[]) => HierarchyValidationResult | null
```

## countActiveChildren()

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

**Signature**

```typescript theme={null}
(parentId: string, tasks: Task[]) => number
```

## validateHierarchyPlacement()

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

**Signature**

```typescript theme={null}
(parentId: string | null, tasks: Task[], policy: HierarchyPolicy) => HierarchyValidationResult
```

## loadConfig()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<CleoConfig>
```

## getConfigValue()

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

**Signature**

```typescript theme={null}
<T>(path: string, cwd?: string | undefined) => Promise<ResolvedValue<T>>
```

## getRawConfigValue()

Get a raw config value from the project config file only (no cascade). Returns undefined if the key is not found. Used by the engine layer for simple key lookups without source tracking.  T4789

**Signature**

```typescript theme={null}
(key: string, cwd?: string | undefined) => Promise<unknown>
```

## getRawConfig()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<Record<string, unknown> | null>
```

## parseConfigValue()

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

**Signature**

```typescript theme={null}
(value: unknown) => unknown
```

## setConfigValue()

Set a config value in the project or global config file (dot-notation supported). Creates intermediate objects as needed. Parses string values into appropriate types (boolean, number, null, JSON).  T4789  T4795

**Signature**

```typescript theme={null}
(key: string, value: unknown, cwd?: string | undefined, opts?: { global?: boolean | undefined; } | undefined) => Promise<{ key: string; value: unknown; scope: "global" | "project"; }>
```

## validateTitle()

Validate a task title.  T4460

**Signature**

```typescript theme={null}
(title: string) => void
```

## validateStatus()

Validate task status.  T4460

**Signature**

```typescript theme={null}
(status: string) => asserts status is "cancelled" | "pending" | "active" | "blocked" | "done" | "archived"
```

## normalizePriority()

Normalize priority to canonical string format. Accepts both string names ("critical","high","medium","low") and numeric (1-9). Returns the canonical string format per todo.schema.json.  T4572

**Signature**

```typescript theme={null}
(priority: string | number) => TaskPriority
```

## validatePriority()

Validate task priority.  T4460  T4572

**Signature**

```typescript theme={null}
(priority: string) => asserts priority is TaskPriority
```

## validateTaskType()

Validate task type.  T4460

**Signature**

```typescript theme={null}
(type: string) => asserts type is TaskType
```

## validateSize()

Validate task size.  T4460

**Signature**

```typescript theme={null}
(size: string) => asserts size is TaskSize
```

## validateLabels()

Validate label format.  T4460

**Signature**

```typescript theme={null}
(labels: string[]) => void
```

## validatePhaseFormat()

Validate phase slug format.  T4460

**Signature**

```typescript theme={null}
(phase: string) => void
```

## validateDepends()

Validate dependency IDs exist.  T4460

**Signature**

```typescript theme={null}
(depends: string[], tasks: Task[]) => void
```

## validateParent()

Validate parent hierarchy constraints.  T4460

**Signature**

```typescript theme={null}
(parentId: string, tasks: Task[], maxDepth?: number, maxSiblings?: number) => void
```

## getTaskDepth()

Get the depth of a task in the hierarchy.  T4460

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => number
```

## inferTaskType()

Infer task type from parent context.  T4460

**Signature**

```typescript theme={null}
(parentId: string | null | undefined, tasks: Task[]) => TaskType
```

## getNextPosition()

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

**Signature**

```typescript theme={null}
(parentId: string | null | undefined, tasks: Task[]) => number
```

## logOperation()

Log an operation to the audit log.  T4460

**Signature**

```typescript theme={null}
(operation: string, taskId: string, details: Record<string, unknown>, accessor?: DataAccessor | undefined) => Promise<void>
```

## findRecentDuplicate()

Check for recent duplicate task.  T4460

**Signature**

```typescript theme={null}
(title: string, phase: string | undefined, tasks: Task[], windowSeconds?: number) => Task | null
```

## addTask()

Add a new task to the todo file.  T4460

**Signature**

```typescript theme={null}
(options: AddTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<AddTaskResult>
```

## listPhases()

List all phases with status summaries.  T4464

**Signature**

```typescript theme={null}
(_cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ListPhasesResult>
```

## showPhase()

Show the current phase details.  T4464

**Signature**

```typescript theme={null}
(slug?: string | undefined, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ShowPhaseResult>
```

## setPhase()

Set the current project phase.  T4464

**Signature**

```typescript theme={null}
(options: SetPhaseOptions, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<SetPhaseResult>
```

## startPhase()

Start a phase (pending - active).  T4464

**Signature**

```typescript theme={null}
(slug: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ phase: string; startedAt: string; }>
```

## completePhase()

Complete a phase (active - completed).  T4464

**Signature**

```typescript theme={null}
(slug: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ phase: string; completedAt: string; }>
```

## advancePhase()

Advance to the next phase.  T4464

**Signature**

```typescript theme={null}
(force?: boolean, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<AdvancePhaseResult>
```

## renamePhase()

Rename a phase and update all task references.  T4464

**Signature**

```typescript theme={null}
(oldName: string, newName: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<RenamePhaseResult>
```

## deletePhase()

Delete a phase with optional task reassignment.  T4464

**Signature**

```typescript theme={null}
(slug: string, options?: { reassignTo?: string | undefined; force?: boolean | undefined; }, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<DeletePhaseResult>
```

## pruneAuditLog(cleoDir, config)

Prune old audit\_log rows from tasks.db.  1. If auditRetentionDays is 0 or undefined, skip age-based pruning. 2. Compute cutoff timestamp from auditRetentionDays. 3. If archiveBeforePrune, select rows older than cutoff and write to    .cleo/backups/logs/audit-YYYY-MM-DD.jsonl.gz. 4. Delete rows older than cutoff from audit\_log.  Idempotent — safe to call multiple times. Never throws — returns zero counts on any error.

**Signature**

```typescript theme={null}
(cleoDir: string, config: LoggingConfig) => Promise<PruneResult>
```

**Parameters**

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

**Signature**

```typescript theme={null}
(options?: { sessionId?: string | undefined; domain?: string | undefined; operation?: string | undefined; taskId?: string | undefined; since?: string | undefined; limit?: number | undefined; } | undefined) => Promise<...>
```

## generateProjectHash()

Canonical project identity hash. SHA-256 of absolute path, first 12 hex chars. Single source of truth — do not duplicate this function elsewhere.

**Signature**

```typescript theme={null}
(projectPath: string) => string
```

## validateAgainstSchema()

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

**Signature**

```typescript theme={null}
(data: unknown, schema: Record<string, unknown>, schemaId?: string | undefined) => void
```

## validateAgainstSchemaFile()

Load a JSON Schema file and validate data against it.

**Signature**

```typescript theme={null}
(data: unknown, schemaPath: string) => Promise<void>
```

## checkSchema()

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

**Signature**

```typescript theme={null}
(data: unknown, schema: Record<string, unknown>) => string[]
```

## resolveSchemaPath(schemaName)

Resolve the absolute path to a schema file at runtime.  Priority:   1. Global install: \~/.cleo/schemas/schemaName   2. Package bundled: /schemas/schemaName

**Signature**

```typescript theme={null}
(schemaName: string) => string | null
```

**Parameters**

| Name         | Type     | Description                                        |
| ------------ | -------- | -------------------------------------------------- |
| `schemaName` | `string` | Filename of the schema (e.g. "config.schema.json") |

**Returns** — Absolute path to the schema file, or null if not found

## getSchemaVersion(schemaName)

Read the schema version from a resolved schema file.  Checks `schemaVersion` (top-level) and `_meta.schemaVersion` (canonical).

**Signature**

```typescript theme={null}
(schemaName: string) => string | null
```

**Parameters**

| Name         | Type     | Description                                        |
| ------------ | -------- | -------------------------------------------------- |
| `schemaName` | `string` | Filename of the schema (e.g. "config.schema.json") |

**Returns** — The version string, or null if not found or unreadable

## ensureGlobalSchemas(opts)

Copy ALL bundled schemas from package schemas/ to \~/.cleo/schemas/.  - Creates the global schemas directory if it doesn't exist. - Skips files that are already up-to-date (same version). - Overwrites stale files (version mismatch).

**Signature**

```typescript theme={null}
(_opts?: Record<string, unknown> | undefined) => SchemaInstallResult
```

**Parameters**

| Name   | Type | Description                                                       |
| ------ | ---- | ----------------------------------------------------------------- |
| `opts` | —    | Optional settings (currently unused, reserved for future options) |

**Returns** — Summary of installed, updated, and total schemas

## checkGlobalSchemas()

Verify that global schemas are installed and not stale.

**Signature**

```typescript theme={null}
() => CheckResult
```

**Returns** — Check result with counts and lists of issues

## checkSchemaStaleness()

Compare global schema versions against bundled package versions.

**Signature**

```typescript theme={null}
() => StalenessReport
```

**Returns** — Report of stale, current, and missing schemas

## listInstalledSchemas()

List all schemas installed in \~/.cleo/schemas/.

**Signature**

```typescript theme={null}
() => InstalledSchema[]
```

**Returns** — Array of installed schema details

## cleanProjectSchemas(projectRoot)

Backup and remove deprecated .cleo/schemas/ directory from a project.  Schemas should live in \~/.cleo/schemas/ (global) not in project directories. This function creates a backup before removal for safety.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ cleaned: boolean; }>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |

**Returns** — Whether cleanup was performed

## readSchemaVersionFromFile()

Read the top-level `schemaVersion` field from a schema file. Delegates to the centralized schema-management module. Returns null if the file cannot be read or has no such field.

**Signature**

```typescript theme={null}
(schemaName: string) => string | null
```

## checkSchemaIntegrity(cwd)

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<SchemaIntegrityReport>
```

**Parameters**

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

**Signature**

```typescript theme={null}
(projectDir: string) => ProjectContext
```

## BrainDataAccessor

**Signature**

```typescript theme={null}
typeof BrainDataAccessor
```

**Methods**

### addDecision()

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

### getDecision()

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

### findDecisions()

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

### updateDecision()

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

### addPattern()

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

### getPattern()

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

### findPatterns()

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

### updatePattern()

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

### addLearning()

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

### getLearning()

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

### findLearnings()

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

### updateLearning()

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

### addObservation()

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

### getObservation()

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

### findObservations()

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

### updateObservation()

```typescript theme={null}
(id: string, updates: Partial<{ id: string; title: string; type: "discovery" | "change" | "feature" | "bugfix" | "decision" | "refactor"; project?: string | null | undefined; createdAt?: string | undefined; ... 10 more ...; discoveryTokens?: number | ... 1 more ... | undefined; }>) => Promise<...>
```

### addLink()

```typescript theme={null}
(row: { taskId: string; linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts"; memoryType: "decision" | "pattern" | "learning" | "observation"; memoryId: string; createdAt?: string | undefined; }) => Promise<...>
```

### getLinksForMemory()

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

### getLinksForTask()

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

### removeLink()

```typescript theme={null}
(memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string, taskId: string, linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts") => Promise<...>
```

### addStickyNote()

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

### getStickyNote()

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

### findStickyNotes()

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

### updateStickyNote()

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

### deleteStickyNote()

```typescript theme={null}
(id: string) => Promise<void>
```

### addPageNode()

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

### getPageNode()

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

### findPageNodes()

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

### removePageNode()

```typescript theme={null}
(id: string) => Promise<void>
```

### addPageEdge()

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

### getPageEdges()

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

### getNeighbors()

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

### removePageEdge()

```typescript theme={null}
(fromId: string, toId: string, edgeType: "depends_on" | "implements" | "relates_to" | "documents") => Promise<void>
```

## getBrainAccessor()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<BrainDataAccessor>
```

## setEmbeddingProvider()

Register an embedding provider for the brain system. Validates that the provider's dimensions match the vec0 table.

**Signature**

```typescript theme={null}
(provider: EmbeddingProvider) => void
```

**Throws**

* Error if provider dimensions do not match EMBEDDING\_DIMENSIONS

## getEmbeddingProvider()

Get the currently registered embedding provider, or null.

**Signature**

```typescript theme={null}
() => EmbeddingProvider | null
```

## clearEmbeddingProvider()

Clear the current embedding provider (useful for testing).

**Signature**

```typescript theme={null}
() => void
```

## embedText()

Embed text into a float vector using the registered provider. Returns null when no provider is set or not available (FTS5-only fallback).

**Signature**

```typescript theme={null}
(text: string) => Promise<Float32Array<ArrayBufferLike> | null>
```

## isEmbeddingAvailable()

Check whether embedding is currently available.

**Signature**

```typescript theme={null}
() => boolean
```

## searchSimilar(query, projectRoot, limit)

Search for entries similar to a query string using vector similarity.  1. Embeds the query text via the registered embedding provider. 2. Runs KNN query against brain\_embeddings vec0 table. 3. Joins with observation/decision/pattern/learning tables for full entries.  Returns empty array when embedding is unavailable (graceful fallback).

**Signature**

```typescript theme={null}
(query: string, projectRoot: string, limit?: number | undefined) => Promise<SimilarityResult[]>
```

**Parameters**

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

**Returns** — Array of similar entries ranked by distance (ascending)

## ensureFts5Tables()

Create FTS5 virtual tables and content-sync triggers if they don't exist.  Uses content= to sync from main tables, so inserts to main tables auto-populate FTS. UPDATE/DELETE require triggers.   T5130

**Signature**

```typescript theme={null}
(nativeDb: DatabaseSync) => boolean
```

## rebuildFts5Index()

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

**Signature**

```typescript theme={null}
(nativeDb: DatabaseSync) => void
```

## searchBrain()

Unified search across all BRAIN memory tables.  Uses FTS5 MATCH for full-text search with BM25 ranking when available, falls back to LIKE queries otherwise.   T5130

**Signature**

```typescript theme={null}
(projectRoot: string, query: string, options?: BrainSearchOptions | undefined) => Promise<BrainSearchResult>
```

## resetFts5Cache()

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

**Signature**

```typescript theme={null}
() => void
```

## hybridSearch(query, projectRoot, options)

Hybrid search across FTS5, vector similarity, and graph neighbors.  1. Runs FTS5 search via existing searchBrain. 2. Runs vector similarity via searchSimilar (if available). 3. Runs graph neighbor expansion via getNeighbors (if query matches a node). 4. Normalizes scores to 0-1 using min-max normalization. 5. Combines with configurable weights. 6. Deduplicates by ID, keeping highest combined score. 7. Returns top-N sorted by score descending.  Graceful fallback: if vec unavailable, redistributes weight to FTS5.

**Signature**

```typescript theme={null}
(query: string, projectRoot: string, options?: HybridSearchOptions | undefined) => Promise<HybridResult[]>
```

**Parameters**

| Name          | Type                                 | Description                    |
| ------------- | ------------------------------------ | ------------------------------ |
| `query`       | `string`                             | Search query text              |
| `projectRoot` | `string`                             | Project root directory         |
| `options`     | `: HybridSearchOptions \| undefined` | Weight and limit configuration |

**Returns** — Array of hybrid results ranked by combined score

## getInjectionTemplateContent()

Get the CLEO-INJECTION.md template content from the package templates/ directory. Returns null if the template file is not found.

**Signature**

```typescript theme={null}
() => string | null
```

## ensureInjection()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## buildContributorInjectionBlock()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => string | null
```

## checkInjection()

Verify injection health: AGENTS.md exists, has CAAMP markers, markers are balanced, and  references resolve.  Combines logic from doctor/checks.ts checkAgentsMdHub, checkCaampMarkerIntegrity, and checkAtReferenceTargetExists.

**Signature**

```typescript theme={null}
(projectRoot: string) => InjectionCheckResult
```

## fileExists()

Check if a file exists and is readable.

**Signature**

```typescript theme={null}
(path: string) => Promise<boolean>
```

## stripCLEOBlocks()

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

**Signature**

```typescript theme={null}
(filePath: string) => Promise<void>
```

## removeCleoFromRootGitignore()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ removed: boolean; }>
```

## getPackageRoot()

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

**Signature**

```typescript theme={null}
() => string
```

## getGitignoreContent()

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

**Signature**

```typescript theme={null}
() => string
```

## getCleoVersion()

Read CLEO version from package.json.

**Signature**

```typescript theme={null}
() => string
```

## createDefaultConfig()

**Signature**

```typescript theme={null}
() => Record<string, unknown>
```

## ensureCleoStructure()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## ensureGitignore()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## ensureConfig()

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

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { force?: boolean | undefined; } | undefined) => Promise<ScaffoldResult>
```

## ensureProjectInfo()

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

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { force?: boolean | undefined; } | undefined) => Promise<ScaffoldResult>
```

## ensureContributorMcp()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## ensureProjectContext()

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

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { force?: boolean | undefined; staleDays?: number | undefined; } | undefined) => Promise<ScaffoldResult>
```

## ensureCleoGitRepo()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## ensureSqliteDb()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## checkCleoStructure()

Verify all required .cleo/ subdirectories exist.

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## checkGitignore()

Verify .cleo/.gitignore exists and matches template.

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## checkConfig()

Verify config.json exists and is valid JSON.

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## checkProjectInfo()

Verify project-info.json exists with required fields.

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## checkProjectContext()

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

**Signature**

```typescript theme={null}
(projectRoot: string, staleDays?: number) => CheckResult
```

## checkCleoGitRepo()

Verify .cleo/.git checkpoint repository exists.

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## checkSqliteDb()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## ensureBrainDb()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ScaffoldResult>
```

## checkBrainDb()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## checkMemoryBridge()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## ensureGlobalHome()

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

**Signature**

```typescript theme={null}
() => Promise<ScaffoldResult>
```

## ensureGlobalTemplates()

Ensure the global CLEO injection template is installed. Delegates to injection.ts for the template content, but owns the filesystem write to maintain SSoT for scaffolding.  Idempotent: skips if the template already exists with correct content.

**Signature**

```typescript theme={null}
() => Promise<ScaffoldResult>
```

## ensureGlobalScaffold()

Perform a complete global scaffold operation: ensure home, schemas, and templates are all present and current. This is the single entry point for global infrastructure scaffolding.  Used by:   - MCP startup (via startupHealthCheck in health.ts)   - init (for first-time global setup)   - upgrade (for global repair)

**Signature**

```typescript theme={null}
() => Promise<{ home: ScaffoldResult; schemas: { installed: number; updated: number; total: number; }; templates: ScaffoldResult; }>
```

## checkGlobalHome()

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

**Signature**

```typescript theme={null}
() => CheckResult
```

## checkGlobalTemplates()

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

**Signature**

```typescript theme={null}
() => CheckResult
```

## checkLogDir()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => CheckResult
```

## getMcpServerName()

Resolve MCP server name by channel.

**Signature**

```typescript theme={null}
(env: McpEnvMode) => string
```

## detectEnvMode()

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

**Signature**

```typescript theme={null}
() => McpEnvMode
```

## generateMcpServerEntry()

Generate the MCP server entry for the cleo server based on env mode.  Returns a config object compatible with CAAMP's McpServerConfig: - dev-ts:  command: 'node', args: \['/dist/mcp/index.js']  - prod-npm stable:  command: 'npx', args: \['-y', 'cleocode/cleolatest', 'mcp']  - prod-npm beta:  command: 'npx', args: \['-y', 'cleocode/cleobeta', 'mcp']    T4584

**Signature**

```typescript theme={null}
(env: McpEnvMode) => Record<string, unknown>
```

## ensureGitHooks()

Install or update managed git hooks from templates/git-hooks/ into .git/hooks/.  Handles: - No .git directory (skips gracefully) - No source templates directory (skips gracefully) - Hooks already installed (skips unless force) - Sets executable permissions on installed hooks

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: EnsureGitHooksOptions | undefined) => Promise<ScaffoldResult>
```

## checkGitHooks()

Verify managed hooks are installed and current.  Compares installed hooks in .git/hooks/ against source templates in the package's templates/git-hooks/ directory. Returns per-hook status including whether the hook is installed and whether its content matches the source.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<HookCheckResult[]>
```

## toTaskFileExt()

Convert a TaskFile (from contracts) to the looser TaskFileExt shape. Accepts any object with at least the basic TaskFileExt structure. The runtime object is the same reference — this only changes the TS type.

**Signature**

```typescript theme={null}
<T extends { _meta?: object; tasks?: unknown[]; focus?: object; lastUpdated?: string; }>(taskFile: T) => TaskFileExt
```

## recordDecision()

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

**Signature**

```typescript theme={null}
(projectRoot: string, params: RecordDecisionParams) => Promise<DecisionRecord>
```

## getDecisionLog()

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

**Signature**

```typescript theme={null}
(projectRoot: string, params?: DecisionLogParams | undefined) => Promise<DecisionRecord[]>
```

## computeHandoff()

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

**Signature**

```typescript theme={null}
(projectRoot: string, options: ComputeHandoffOptions) => Promise<HandoffData>
```

## persistHandoff()

Persist handoff data to a session.

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string, handoff: HandoffData) => Promise<void>
```

## getHandoff()

Get handoff data for a session.

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<HandoffData | null>
```

## getLastHandoff()

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

**Signature**

```typescript theme={null}
(projectRoot: string, scope?: { type: string; epicId?: string | undefined; rootTaskId?: string | undefined; } | undefined) => Promise<{ sessionId: string; handoff: HandoffData; } | null>
```

## computeDebrief()

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

**Signature**

```typescript theme={null}
(projectRoot: string, options: ComputeDebriefOptions) => Promise<DebriefData>
```

## generateMemoryBridgeContent()

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

**Signature**

```typescript theme={null}
(projectRoot: string, config?: Partial<MemoryBridgeConfig> | undefined) => Promise<string>
```

## writeMemoryBridge()

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

**Signature**

```typescript theme={null}
(projectRoot: string, config?: Partial<MemoryBridgeConfig> | undefined) => Promise<{ path: string; written: boolean; }>
```

## refreshMemoryBridge()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<void>
```

## detectLegacyAgentOutputs(projectRoot, cleoDir)

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

**Signature**

```typescript theme={null}
(projectRoot: string, cleoDir: string) => LegacyDetectionResult
```

**Parameters**

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

```typescript theme={null}
(projectRoot: string, cleoDir: string) => AgentOutputsMigrationResult
```

**Parameters**

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

**Signature**

```typescript theme={null}
() => Promise<number>
```

**Returns** — Number of projects migrated.

## getNexusHome()

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

**Signature**

```typescript theme={null}
() => string
```

## getNexusCacheDir()

Get path to the NEXUS cache directory.

**Signature**

```typescript theme={null}
() => string
```

## getRegistryPath()

> **Deprecated**: Use nexus.db via getNexusDb() instead. Retained for JSON-to-SQLite migration.

Get path to the legacy projects registry JSON file.

**Signature**

```typescript theme={null}
() => string
```

## readRegistry()

Read all projects from nexus.db and return as a NexusRegistryFile. Compatibility wrapper for consumers that expect the legacy JSON shape. Returns null if nexus.db has not been initialized yet.

**Signature**

```typescript theme={null}
() => Promise<NexusRegistryFile | null>
```

## readRegistryRequired()

Read the global registry, throwing if not initialized.

**Signature**

```typescript theme={null}
() => Promise<NexusRegistryFile>
```

## nexusInit()

Initialize the NEXUS directory structure and nexus.db. Idempotent -- safe to call multiple times. Migrates legacy JSON registry on first run if present.

**Signature**

```typescript theme={null}
() => Promise<void>
```

## nexusRegister()

Register a project in the global registry (nexus.db).

**Signature**

```typescript theme={null}
(projectPath: string, name?: string | undefined, permissions?: NexusPermissionLevel) => Promise<string>
```

**Returns** — The project hash.

## nexusUnregister()

Unregister a project from the global registry.

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<void>
```

## nexusList()

List all registered projects.

**Signature**

```typescript theme={null}
() => Promise<NexusProject[]>
```

## nexusGetProject()

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

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<NexusProject | null>
```

## nexusProjectExists()

Check if a project exists in the registry.

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<boolean>
```

## nexusSync()

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

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<void>
```

## nexusSyncAll()

Sync all registered projects.

**Signature**

```typescript theme={null}
() => Promise<{ synced: number; failed: number; }>
```

**Returns** — Counts of synced and failed projects.

## nexusSetPermission()

Update a project's permission level in the registry. Used by permissions.ts to avoid direct JSON file writes.

**Signature**

```typescript theme={null}
(nameOrHash: string, permission: NexusPermissionLevel) => Promise<void>
```

## nexusReconcile()

Reconcile the current project's identity with the global nexus registry.  4-scenario policy:   1. projectId in registry + path matches → update lastSeen, return status:'ok'   2. projectId in registry + path changed → update path+hash, return status:'path\_updated'   3. projectId not in registry → auto-register, return status:'auto\_registered'   4. projectHash matches but different projectId → throw CleoError (identity conflict)  Uses projectId as the stable identifier across project moves, since projectHash is derived from the absolute path and changes when moved.   T5368

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ status: "ok" | "path_updated" | "auto_registered"; oldPath?: string | undefined; newPath?: string | undefined; }>
```

## analyzeStack()

**Signature**

```typescript theme={null}
(projectRoot: string, projectContext: ProjectContext) => StackAnalysis
```

## analyzeArchitecture()

**Signature**

```typescript theme={null}
(projectRoot: string, _projectContext: ProjectContext) => ArchAnalysis
```

## analyzeStructure()

**Signature**

```typescript theme={null}
(projectRoot: string) => StructureAnalysis
```

## analyzeConventions()

**Signature**

```typescript theme={null}
(projectRoot: string, projectContext: ProjectContext) => ConventionAnalysis
```

## analyzeTesting()

**Signature**

```typescript theme={null}
(projectRoot: string, projectContext: ProjectContext) => TestingAnalysis
```

## analyzeIntegrations()

**Signature**

```typescript theme={null}
(projectRoot: string, _projectContext: ProjectContext) => IntegrationAnalysis
```

## analyzeConcerns()

**Signature**

```typescript theme={null}
(projectRoot: string) => ConcernAnalysis
```

## storePattern()

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

**Signature**

```typescript theme={null}
(projectRoot: string, params: StorePatternParams) => Promise<{ examples: any; id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; ... 8 more ...; extractedAt: string; }>
```

## searchPatterns()

Search patterns by criteria.  T4768, T5241

**Signature**

```typescript theme={null}
(projectRoot: string, params?: SearchPatternParams) => Promise<{ examples: any; id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; ... 8 more ...; extractedAt: string; }[]>
```

## patternStats()

Get pattern statistics.  T4768, T5241

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ total: number; byType: Record<string, number>; byImpact: Record<string, number>; highestFrequency: { pattern: string; frequency: number; } | null; }>
```

## storeLearning()

Store a new learning.  T4769, T5241

**Signature**

```typescript theme={null}
(projectRoot: string, params: StoreLearningParams) => Promise<{ applicableTypes: any; id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; }>
```

## searchLearnings()

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

**Signature**

```typescript theme={null}
(projectRoot: string, params?: SearchLearningParams) => Promise<{ applicableTypes: any; id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; }[]>
```

## learningStats()

Get learning statistics.  T4769, T5241

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ total: number; actionable: number; averageConfidence: number; bySource: Record<string, number>; highConfidence: number; lowConfidence: number; }>
```

## searchBrainCompact(projectRoot, params)

Token-efficient compact search across BRAIN tables. Returns index-level hits (\~50 tokens per result).  Delegates to searchBrain() from brain-search.ts for FTS5/LIKE search, then projects results to a compact format with optional date filtering.

**Signature**

```typescript theme={null}
(projectRoot: string, params: SearchBrainCompactParams) => Promise<SearchBrainCompactResult>
```

**Parameters**

| Name          | Type                       | Description            |
| ------------- | -------------------------- | ---------------------- |
| `projectRoot` | `string`                   | Project root directory |
| `params`      | `SearchBrainCompactParams` | Search parameters      |

**Returns** — Compact search results with token estimate

## timelineBrain(projectRoot, params)

Get chronological context around an anchor entry. Fetches the anchor's full data, then queries all 4 BRAIN tables via UNION ALL to find chronological neighbors.

**Signature**

```typescript theme={null}
(projectRoot: string, params: TimelineBrainParams) => Promise<TimelineBrainResult>
```

**Parameters**

| Name          | Type                  | Description                                  |
| ------------- | --------------------- | -------------------------------------------- |
| `projectRoot` | `string`              | Project root directory                       |
| `params`      | `TimelineBrainParams` | Timeline parameters with anchor ID and depth |

**Returns** — Anchor entry data with surrounding chronological entries

## fetchBrainEntries(projectRoot, params)

Batch-fetch full details by IDs. Groups IDs by prefix to query the correct tables via BrainDataAccessor.

**Signature**

```typescript theme={null}
(projectRoot: string, params: FetchBrainEntriesParams) => Promise<FetchBrainEntriesResult>
```

**Parameters**

| Name          | Type                      | Description               |
| ------------- | ------------------------- | ------------------------- |
| `projectRoot` | `string`                  | Project root directory    |
| `params`      | `FetchBrainEntriesParams` | Fetch parameters with IDs |

**Returns** — Full entry data for each found ID, plus not-found list

## observeBrain(projectRoot, params)

Save an observation to the BRAIN observations table. Replaces the external claude-mem save\_observation pattern.  Auto-classifies type from text if not provided. Generates a unique ID with O- prefix + base36 timestamp.

**Signature**

```typescript theme={null}
(projectRoot: string, params: ObserveBrainParams) => Promise<ObserveBrainResult>
```

**Parameters**

| Name          | Type                 | Description            |
| ------------- | -------------------- | ---------------------- |
| `projectRoot` | `string`             | Project root directory |
| `params`      | `ObserveBrainParams` | Observation data       |

**Returns** — Created observation ID, type, and timestamp

## populateEmbeddings(projectRoot, options)

Backfill embeddings for existing observations that lack them.  Iterates through observations not yet in brain\_embeddings and generates vectors using the registered embedding provider. Processes in batches to avoid memory pressure.

**Signature**

```typescript theme={null}
(projectRoot: string, options?: { batchSize?: number | undefined; } | undefined) => Promise<PopulateEmbeddingsResult>
```

**Parameters**

| Name          | Type                                                    | Description                       |
| ------------- | ------------------------------------------------------- | --------------------------------- |
| `projectRoot` | `string`                                                | Project root directory            |
| `options`     | `: \{ batchSize?: number \| undefined; \} \| undefined` | Optional batch size configuration |

**Returns** — Count of processed and skipped observations

## storeMapToBrain()

**Signature**

```typescript theme={null}
(projectRoot: string, result: CodebaseMapResult) => Promise<{ patternsStored: number; learningsStored: number; observationsStored: number; }>
```

## mapCodebase()

**Signature**

```typescript theme={null}
(projectRoot: string, options?: MapCodebaseOptions | undefined) => Promise<CodebaseMapResult>
```

## isValidAdapter()

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

**Signature**

```typescript theme={null}
(adapter: unknown) => adapter is CLEOProviderAdapter
```

## loadAdapterFromManifest(manifest)

Dynamically load and instantiate an adapter from its manifest.  Uses the manifest's packagePath to resolve the adapter module, then looks for a `createAdapter()` factory or a default export class.

**Signature**

```typescript theme={null}
(manifest: AdapterManifest) => Promise<CLEOProviderAdapter>
```

**Parameters**

| Name       | Type              | Description                                      |
| ---------- | ----------------- | ------------------------------------------------ |
| `manifest` | `AdapterManifest` | The adapter manifest with a resolved packagePath |

**Returns** — A CLEOProviderAdapter instance

**Throws**

* If the module cannot be loaded or does not export a valid adapter

## discoverAdapterManifests()

Scan the packages/adapters/ directory for adapter packages. Each adapter must have a manifest.json at its root.

**Signature**

```typescript theme={null}
(projectRoot: string) => AdapterManifest[]
```

## detectProvider()

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

**Signature**

```typescript theme={null}
(patterns: DetectionPattern[]) => boolean
```

## AdapterManager

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

**Signature**

```typescript theme={null}
typeof AdapterManager
```

**Methods**

### getInstance()

```typescript theme={null}
(projectRoot: string) => AdapterManager
```

### resetInstance()

Reset singleton (for testing).

```typescript theme={null}
() => void
```

### discover()

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

```typescript theme={null}
() => AdapterManifest[]
```

### detectActive()

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

```typescript theme={null}
() => string[]
```

### activate()

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

```typescript theme={null}
(adapterId: string) => Promise<CLEOProviderAdapter>
```

### getActive()

Get the currently active adapter, or null if none.

```typescript theme={null}
() => CLEOProviderAdapter | null
```

### getActiveId()

Get the active adapter's ID, or null.

```typescript theme={null}
() => string | null
```

### get()

Get a specific adapter by ID.

```typescript theme={null}
(adapterId: string) => CLEOProviderAdapter | null
```

### getManifest()

Get the manifest for a specific adapter.

```typescript theme={null}
(adapterId: string) => AdapterManifest | null
```

### listAdapters()

List all known adapters with summary info.

```typescript theme={null}
() => AdapterInfo[]
```

### healthCheckAll()

Run health check on all initialized adapters.

```typescript theme={null}
() => Promise<Map<string, AdapterHealthStatus>>
```

### healthCheck()

Health check a single adapter.

```typescript theme={null}
(adapterId: string) => Promise<AdapterHealthStatus>
```

### dispose()

Dispose all initialized adapters.

```typescript theme={null}
() => Promise<void>
```

### disposeAdapter()

Dispose a single adapter.

```typescript theme={null}
(adapterId: string) => Promise<void>
```

### wireAdapterHooks()

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

```typescript theme={null}
(adapterId: string, adapter: CLEOProviderAdapter) => Promise<void>
```

### cleanupAdapterHooks()

Clean up hook registrations for an adapter.

```typescript theme={null}
(adapterId: string, adapter: CLEOProviderAdapter) => Promise<void>
```

## initAgentDefinition()

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

**Signature**

```typescript theme={null}
(created: string[], warnings: string[]) => Promise<void>
```

## initMcpServer()

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

**Signature**

```typescript theme={null}
(projectRoot: string, created: string[], warnings: string[]) => Promise<void>
```

## initCoreSkills()

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

**Signature**

```typescript theme={null}
(created: string[], warnings: string[]) => Promise<void>
```

## initNexusRegistration()

Register/reconcile project with NEXUS. Uses nexusReconcile for idempotent handshake — auto-registers if new, updates path if moved, confirms identity if unchanged.  T4684  T5368

**Signature**

```typescript theme={null}
(projectRoot: string, created: string[], warnings: string[]) => Promise<void>
```

## installGitHubTemplates(projectRoot, created, skipped)

Install GitHub issue and PR templates to .github/ if a git repo exists but .github/ISSUE\_TEMPLATE/ is not yet present.  Idempotent: skips files that already exist. Never overwrites existing templates — the project owner's customisations take precedence.

**Signature**

```typescript theme={null}
(projectRoot: string, created: string[], skipped: string[]) => Promise<void>
```

**Parameters**

| 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

**Signature**

```typescript theme={null}
() => Promise<InitResult>
```

## initProject()

Run full project initialization.  Creates the .cleo/ directory structure, installs schemas, templates, agent definitions, MCP server configs, skills, and registers with NEXUS.   T4681  T4682  T4684  T4685  T4686  T4687  T4689  T4706  T4707

**Signature**

```typescript theme={null}
(opts?: InitOptions) => Promise<InitResult>
```

## isAutoInitEnabled()

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

**Signature**

```typescript theme={null}
() => boolean
```

## ensureInitialized()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<{ initialized: boolean; }>
```

## getVersion()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<{ version: string; }>
```

## bootstrapGlobalCleo()

Bootstrap the global CLEO directory structure and install templates.  Creates:   - \~/.cleo/templates/CLEO-INJECTION.md (from bundled template or injection content)   - \~/.agents/AGENTS.md with CAAMP injection block  This is idempotent — safe to call multiple times.

**Signature**

```typescript theme={null}
(options?: BootstrapOptions | undefined) => Promise<BootstrapContext>
```

## installMcpToProviders()

Install the CLEO MCP server config to all detected providers.

**Signature**

```typescript theme={null}
(ctx: BootstrapContext) => Promise<void>
```

## installSkillsGlobally()

Install CLEO core skills globally via CAAMP.

**Signature**

```typescript theme={null}
(ctx: BootstrapContext) => Promise<void>
```

## bootstrapCaamp()

**Signature**

```typescript theme={null}
() => void
```

## exportTasks()

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

**Signature**

```typescript theme={null}
(params: ExportParams) => Promise<ExportResult>
```

## importTasks()

Import tasks from an export file.

**Signature**

```typescript theme={null}
(params: ImportParams) => Promise<ImportResult>
```

## validateSyntax()

Validate a query string matches expected syntax.

**Signature**

```typescript theme={null}
(query: string) => boolean
```

## parseQuery()

Parse a query string into its components.

**Signature**

```typescript theme={null}
(query: string, currentProject?: string | undefined) => NexusParsedQuery
```

**Throws**

* CleoError with NEXUS\_INVALID\_SYNTAX for bad format.

## getCurrentProject()

Get the current project name from context. Reads .cleo/project-info.json or falls back to directory name.

**Signature**

```typescript theme={null}
() => string
```

## resolveProjectPath()

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

**Signature**

```typescript theme={null}
(projectName: string) => Promise<string>
```

## resolveTask()

Resolve a query to task data. For wildcard queries, returns an array of matches from all projects. For named projects, returns a single task with project context.

**Signature**

```typescript theme={null}
(query: string, currentProject?: string | undefined) => Promise<NexusResolvedTask | NexusResolvedTask[]>
```

## getProjectFromQuery()

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

**Signature**

```typescript theme={null}
(query: string, currentProject?: string | undefined) => string
```

## extractKeywords()

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

**Signature**

```typescript theme={null}
(text: string) => string[]
```

## discoverRelated()

Discover tasks related to a given task query across projects.  Returns a structured result or throws on unrecoverable errors. Validation errors (bad syntax, wildcard) are returned as  error  objects so callers can wrap them in an appropriate engine error response.

**Signature**

```typescript theme={null}
(taskQuery: string, method?: string, limit?: number) => Promise<NexusDiscoverResult | { error: { code: string; message: string; }; }>
```

## searchAcrossProjects()

Search for tasks across all registered projects.  Returns a structured result or throws on unrecoverable errors. Validation errors (bad pattern) are returned as  error  objects.

**Signature**

```typescript theme={null}
(pattern: string, projectFilter?: string | undefined, limit?: number) => Promise<NexusSearchResult | { error: { code: string; message: string; }; }>
```

## permissionLevel()

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

**Signature**

```typescript theme={null}
(permission: string) => number
```

## getPermission()

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

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<NexusPermissionLevel>
```

## checkPermission()

Check if a project has sufficient permissions (non-throwing). Uses hierarchical comparison: execute = write = read.

**Signature**

```typescript theme={null}
(nameOrHash: string, required: NexusPermissionLevel) => Promise<boolean>
```

**Returns** — true if the granted permission meets or exceeds the required level.

## requirePermission()

Require a permission level or throw CleoError. Used as a guard at the start of cross-project operations.

**Signature**

```typescript theme={null}
(nameOrHash: string, required: NexusPermissionLevel, operationName?: string) => Promise<void>
```

## checkPermissionDetail()

Full permission check returning a structured result.

**Signature**

```typescript theme={null}
(nameOrHash: string, required: NexusPermissionLevel) => Promise<PermissionCheckResult>
```

## setPermission()

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

**Signature**

```typescript theme={null}
(nameOrHash: string, permission: NexusPermissionLevel) => Promise<void>
```

## canRead()

Convenience: check read access.

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<boolean>
```

## canWrite()

Convenience: check write access.

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<boolean>
```

## canExecute()

Convenience: check execute access.

**Signature**

```typescript theme={null}
(nameOrHash: string) => Promise<boolean>
```

## matchesPattern()

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

**Signature**

```typescript theme={null}
(filePath: string, pattern: string) => boolean
```

## getSharingStatus()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<SharingStatus>
```

## syncGitignore()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ updated: boolean; entriesCount: number; }>
```

## invalidateDepsCache()

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

**Signature**

```typescript theme={null}
() => void
```

## buildGraph()

Build an adjacency graph from task dependencies.  T4464

**Signature**

```typescript theme={null}
(tasks: Task[]) => Map<string, DepNode>
```

## getDepsOverview()

Get dependency overview for all tasks.  T4464

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<DepsOverviewResult>
```

## getTaskDeps()

Get dependencies for a specific task.  T4464

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskDepsResult>
```

## topologicalSort()

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

**Signature**

```typescript theme={null}
(tasks: Task[]) => Task[]
```

## getExecutionWaves()

Group tasks into parallelizable execution waves.  T4464

**Signature**

```typescript theme={null}
(epicId?: string | undefined, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ExecutionWave[]>
```

## getCriticalPath()

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

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CriticalPathResult>
```

## getImpact()

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

**Signature**

```typescript theme={null}
(taskId: string, maxDepth?: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<string[]>
```

## detectCycles()

Detect circular dependencies in the task graph.  T4464

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CycleResult>
```

## getTaskTree()

Build task hierarchy tree.  T4464

**Signature**

```typescript theme={null}
(rootId?: string | undefined, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TreeNode[]>
```

## addRelation()

Manage task relationships (relates/blocks).  T4464

**Signature**

```typescript theme={null}
(taskId: string, relatedId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ taskId: string; relatedId: string; }>
```

## buildDependencyGraph()

Build a dependency graph for a set of tasks.  Returns a Map from task ID to the set of task IDs it depends on.

**Signature**

```typescript theme={null}
(tasks: Task[]) => Map<string, Set<string>>
```

## detectCircularDependencies(tasks, graph)

Detect circular dependencies using DFS traversal.

**Signature**

```typescript theme={null}
(tasks: Task[], graph?: Map<string, Set<string>> | undefined) => CircularDependency[]
```

**Parameters**

| Name    | Type              | Description                                                             |
| ------- | ----------------- | ----------------------------------------------------------------------- |
| `tasks` | `Task[]`          | The set of tasks to analyze                                             |
| `graph` | `: Map&lt;string` | Pre-built dependency graph (optional; built from tasks if not provided) |

**Returns** — Array of circular dependency cycles (each cycle is an array of task IDs)

## findMissingDependencies(children, allTasks)

Find missing dependencies — deps that reference tasks outside the epic that are not yet completed.

**Signature**

```typescript theme={null}
(children: Task[], allTasks: Task[]) => MissingDependency[]
```

**Parameters**

| Name       | Type     | Description                                                         |
| ---------- | -------- | ------------------------------------------------------------------- |
| `children` | `Task[]` | Child tasks of the epic                                             |
| `allTasks` | `Task[]` | All tasks in the project (to check if deps are completed elsewhere) |

**Returns** — Array of missing dependency references

## analyzeDependencies(children, allTasks)

Perform full dependency analysis for an epic's children.  Combines dependency graph building, circular detection, and missing dep identification into a single analysis result.

**Signature**

```typescript theme={null}
(children: Task[], allTasks: Task[]) => DependencyAnalysis
```

**Parameters**

| Name       | Type     | Description              |
| ---------- | -------- | ------------------------ |
| `children` | `Task[]` | Child tasks of the epic  |
| `allTasks` | `Task[]` | All tasks in the project |

**Returns** — Complete dependency analysis

## countManifestEntries(projectRoot)

Count manifest entries from MANIFEST.jsonl.

**Signature**

```typescript theme={null}
(projectRoot: string) => number
```

**Parameters**

| Name          | Type     | Description                |
| ------------- | -------- | -------------------------- |
| `projectRoot` | `string` | The project root directory |

**Returns** — Number of manifest entries

## estimateContext(taskCount, projectRoot, epicId)

Estimate context usage for orchestration.

**Signature**

```typescript theme={null}
(taskCount: number, projectRoot: string, epicId?: string | undefined) => ContextEstimation
```

**Parameters**

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

**Returns** — Context estimation with recommendations

## computeWaves()

Compute execution waves using topological sort.

**Signature**

```typescript theme={null}
(tasks: Task[]) => Wave[]
```

## getEnrichedWaves()

Get enriched wave data for an epic.

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; waves: EnrichedWave[]; totalWaves: number; totalTasks: number; }>
```

## countByStatus()

Count tasks by status.

**Signature**

```typescript theme={null}
(tasks: Task[]) => StatusCounts
```

## computeEpicStatus(epicId, epicTitle, children)

Compute epic-specific status.

**Signature**

```typescript theme={null}
(epicId: string, epicTitle: string, children: Task[]) => EpicStatus
```

**Parameters**

| Name        | Type     | Description             |
| ----------- | -------- | ----------------------- |
| `epicId`    | `string` | The epic task ID        |
| `epicTitle` | `string` | The epic title          |
| `children`  | `Task[]` | Child tasks of the epic |

**Returns** — Epic status with wave information

## computeOverallStatus(tasks)

Compute overall orchestration status across all tasks.

**Signature**

```typescript theme={null}
(tasks: Task[]) => OverallStatus
```

**Parameters**

| Name    | Type     | Description              |
| ------- | -------- | ------------------------ |
| `tasks` | `Task[]` | All tasks in the project |

**Returns** — Overall status with epic count

## computeProgress(tasks)

Compute progress metrics for all tasks.

**Signature**

```typescript theme={null}
(tasks: Task[]) => ProgressMetrics
```

**Parameters**

| Name    | Type     | Description          |
| ------- | -------- | -------------------- |
| `tasks` | `Task[]` | All tasks to measure |

**Returns** — Progress metrics with completion percentage

## computeStartupSummary(epicId, epicTitle, children, readyCount)

Compute startup summary for an epic.

**Signature**

```typescript theme={null}
(epicId: string, epicTitle: string, children: Task[], readyCount: number) => StartupSummary
```

**Parameters**

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

**Returns** — Startup summary with wave information

## startOrchestration()

Start an orchestrator session for an epic.  T4466

**Signature**

```typescript theme={null}
(epicId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<OrchestratorSession>
```

## analyzeEpic()

Analyze an epic's dependency structure.  T4466

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<AnalysisResult>
```

## getReadyTasks()

Get parallel-safe ready tasks for an epic.  T4466

**Signature**

```typescript theme={null}
(epicId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskReadiness[]>
```

## getNextTask()

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

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskReadiness | null>
```

## prepareSpawn()

Prepare a spawn context for a subagent.  T4466

**Signature**

```typescript theme={null}
(taskId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<SpawnContext>
```

## validateSpawnOutput()

Validate a subagent's output.  T4466

**Signature**

```typescript theme={null}
(_taskId: string, output: { file?: string | undefined; manifestEntry?: boolean | undefined; }) => Promise<{ valid: boolean; errors: string[]; }>
```

## getOrchestratorContext()

Get orchestrator context summary.  T4466

**Signature**

```typescript theme={null}
(epicId: string, _cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; epicTitle: string; totalTasks: number; completed: number; inProgress: number; blocked: number; pending: number; completionPercent: number; }>
```

## autoDispatch()

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

**Signature**

```typescript theme={null}
(task: Task) => string
```

## resolveTokens()

Resolve tokens in a prompt string.  T4466

**Signature**

```typescript theme={null}
(prompt: string, context: Record<string, string>) => { resolved: string; unresolved: string[]; }
```

## bridgeSessionToMemory(projectRoot, sessionData)

Bridge session end data to brain.db as an observation.  Builds a summary text from the session metadata and saves it as a 'change' observation with source\_type 'agent'.

**Signature**

```typescript theme={null}
(projectRoot: string, sessionData: SessionBridgeData) => Promise<void>
```

**Parameters**

| 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

**Signature**

```typescript theme={null}
(projectRoot: string, params: StoreDecisionParams) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }>
```

## recallDecision()

Recall a specific decision by ID.   T5155

**Signature**

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

## searchDecisions()

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

**Signature**

```typescript theme={null}
(projectRoot: string, params?: SearchDecisionParams) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }[]>
```

## listDecisions()

List decisions with pagination.   T5155

**Signature**

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

## updateDecisionOutcome()

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

**Signature**

```typescript theme={null}
(projectRoot: string, id: string, outcome: "pending" | "success" | "failure" | "mixed" | null) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; ... 7 more ...; contextPhase: string | null; }>
```

## extractTaskCompletionMemory()

Extract and store memory entries when a task is completed.  - Always stores a learning for the completed task. - Stores a second learning if the task had dependencies. - Detects recurring label patterns across recent completed tasks   and stores a success pattern when any label appears 3+ times.

**Signature**

```typescript theme={null}
(projectRoot: string, task: Task, _parentTask?: Task | undefined) => Promise<void>
```

## extractSessionEndMemory()

Extract and store memory entries when a session ends.  - Stores a process decision summarising the session. - Stores a per-task learning for each completed task. - Stores a workflow pattern when 2+ completed tasks share a label.

**Signature**

```typescript theme={null}
(projectRoot: string, sessionData: SessionBridgeData, taskDetails: Task[]) => Promise<void>
```

## resolveTaskDetails()

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

**Signature**

```typescript theme={null}
(projectRoot: string, taskIds: string[]) => Promise<Task[]>
```

## completeTask()

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

**Signature**

```typescript theme={null}
(options: CompleteTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CompleteTaskResult>
```

## updateTask()

Update a task's fields.  T4461

**Signature**

```typescript theme={null}
(options: UpdateTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<UpdateTaskResult>
```

## getLinksByProvider()

Find all links for a given provider.

**Signature**

```typescript theme={null}
(providerId: string, cwd?: string | undefined) => Promise<ExternalTaskLink[]>
```

## getLinkByExternalId()

Find a link by provider + external ID.

**Signature**

```typescript theme={null}
(providerId: string, externalId: string, cwd?: string | undefined) => Promise<ExternalTaskLink | null>
```

## getLinksByTaskId()

Find all links for a given CLEO task.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<ExternalTaskLink[]>
```

## createLink()

Create a new external task link.

**Signature**

```typescript theme={null}
(params: { taskId: string; providerId: string; externalId: string; externalUrl?: string | undefined; externalTitle?: string | undefined; linkType: ExternalLinkType; syncDirection?: SyncDirection | undefined; metadata?: Record<...> | undefined; }, cwd?: string | undefined) => Promise<...>
```

## touchLink()

Update the lastSyncAt and optionally the title/metadata for an existing link.

**Signature**

```typescript theme={null}
(linkId: string, updates?: { externalTitle?: string | undefined; metadata?: Record<string, unknown> | undefined; } | undefined, cwd?: string | undefined) => Promise<void>
```

## removeLinksByProvider()

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

**Signature**

```typescript theme={null}
(providerId: string, cwd?: string | undefined) => Promise<number>
```

## reconcile(externalTasks, options, accessor)

Reconcile external task state with CLEO's authoritative task store.

**Signature**

```typescript theme={null}
(externalTasks: ExternalTask[], options: ReconcileOptions, accessor?: DataAccessor | undefined) => Promise<ReconcileResult>
```

**Parameters**

| Name            | Type                          | Description                                   |
| --------------- | ----------------------------- | --------------------------------------------- |
| `externalTasks` | `ExternalTask[]`              | Normalized tasks from a provider adapter.     |
| `options`       | `ReconcileOptions`            | Reconciliation options.                       |
| `accessor`      | `: DataAccessor \| undefined` | Optional DataAccessor override (for testing). |

**Returns** — Reconciliation result with actions taken.

## getArtifactHandler()

Get handler for an artifact type.  T4552

**Signature**

```typescript theme={null}
(artifactType: ArtifactType) => ArtifactHandler | null
```

## hasArtifactHandler()

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

**Signature**

```typescript theme={null}
(artifactType: string) => artifactType is ArtifactType
```

## buildArtifact()

Build an artifact using the appropriate handler.  T4552

**Signature**

```typescript theme={null}
(config: ArtifactConfig, dryRun?: boolean) => Promise<ArtifactResult>
```

## validateArtifact()

Validate an artifact using the appropriate handler.  T4552

**Signature**

```typescript theme={null}
(config: ArtifactConfig) => Promise<ArtifactResult>
```

## publishArtifact()

Publish an artifact using the appropriate handler.  T4552

**Signature**

```typescript theme={null}
(config: ArtifactConfig, dryRun?: boolean) => Promise<ArtifactResult>
```

## getSupportedArtifactTypes()

Get all supported artifact types.  T4552

**Signature**

```typescript theme={null}
() => ArtifactType[]
```

## parseChangelogBlocks()

Parse \[custom-log]...\[/custom-log] blocks from a CHANGELOG section. Returns the extracted block content (tags stripped) and the content with tags+content removed.

**Signature**

```typescript theme={null}
(content: string) => { customBlocks: string[]; strippedContent: string; }
```

## writeChangelogSection()

Write or update a CHANGELOG.md section for a specific version.  - If ## \[VERSION] section exists: replaces it in-place. - If not: prepends as new section after any top-level # heading. - Custom block content (from \[custom-log] blocks) is appended after   generated content. - Section header format: '## \[VERSION] (YYYY-MM-DD)'

**Signature**

```typescript theme={null}
(version: string, generatedContent: string, customBlocks: string[], changelogPath: string) => Promise<void>
```

## loadReleaseConfig()

Load release configuration with defaults.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => ReleaseConfig
```

## validateReleaseConfig()

Validate release configuration.

**Signature**

```typescript theme={null}
(config: ReleaseConfig) => { valid: boolean; errors: string[]; warnings: string[]; }
```

## getArtifactType()

Get artifact type from config.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getReleaseGates()

Get release gates from config.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => ReleaseGate[]
```

## getChangelogConfig()

Get changelog configuration.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { format: string; file: string; }
```

## getDefaultGitFlowConfig()

Return the default GitFlow branch configuration.

**Signature**

```typescript theme={null}
() => GitFlowConfig
```

## getGitFlowConfig()

Merge caller-supplied GitFlow config with defaults.

**Signature**

```typescript theme={null}
(config: ReleaseConfig) => GitFlowConfig
```

## getDefaultChannelConfig()

Return the default channel configuration.

**Signature**

```typescript theme={null}
() => ChannelConfig
```

## getChannelConfig()

Merge caller-supplied channel config with defaults.

**Signature**

```typescript theme={null}
(config: ReleaseConfig) => ChannelConfig
```

## getPushMode()

Return the configured push mode, defaulting to 'auto'.

**Signature**

```typescript theme={null}
(config: ReleaseConfig) => PushMode
```

## getDefaultChannelConfig()

Return the default branch-to-channel mapping.

**Signature**

```typescript theme={null}
() => ChannelConfig
```

## resolveChannelFromBranch()

Resolve the release channel for a given Git branch name.  Resolution order: 1. Exact match in `config.custom` 2. Prefix match in `config.custom` 3. Exact match against `config.main` → 'latest' 4. Exact match against `config.develop` → 'beta' 5. Starts with 'feature/', 'hotfix/', 'release/', or `config.feature` → 'alpha' 6. Fallback → 'alpha'

**Signature**

```typescript theme={null}
(branch: string, config?: ChannelConfig | undefined) => ReleaseChannel
```

## channelToDistTag()

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

**Signature**

```typescript theme={null}
(channel: ReleaseChannel) => string
```

## validateVersionChannel()

Validate that a version string satisfies the pre-release conventions for the given channel.  Rules: - 'latest': version must NOT contain '-' (no pre-release suffix) - 'beta':   version must contain '-beta' or '-rc' - 'alpha':  version must contain '-alpha', '-dev', '-rc', or '-beta'

**Signature**

```typescript theme={null}
(version: string, channel: ReleaseChannel) => ChannelValidationResult
```

## describeChannel()

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

**Signature**

```typescript theme={null}
(channel: ReleaseChannel) => string
```

## getPlatformPath()

Get the output path for a CI platform.

**Signature**

```typescript theme={null}
(platform: CIPlatform) => string
```

## detectCIPlatform()

Detect the CI platform from the project.

**Signature**

```typescript theme={null}
(projectDir?: string | undefined) => CIPlatform | null
```

## generateCIConfig()

Generate CI config for a platform.

**Signature**

```typescript theme={null}
(platform: CIPlatform, cwd?: string | undefined) => string
```

## writeCIConfig()

Write CI config to the appropriate path.

**Signature**

```typescript theme={null}
(platform: CIPlatform, options?: { projectDir?: string | undefined; dryRun?: boolean | undefined; }) => { action: string; path: string; content: string; }
```

## validateCIConfig()

Validate an existing CI config.

**Signature**

```typescript theme={null}
(platform: CIPlatform, projectDir?: string | undefined) => { valid: boolean; exists: boolean; errors: string[]; }
```

## isGhCliAvailable()

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

**Signature**

```typescript theme={null}
() => boolean
```

## extractRepoOwnerAndName()

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

**Signature**

```typescript theme={null}
(remote: string) => RepoIdentity | null
```

## detectBranchProtection()

Detect whether a branch has protection rules enabled.  Strategy 1 (preferred): use `gh api` to query GitHub branch protection. Strategy 2 (fallback): use `git push --dry-run` and inspect stderr.

**Signature**

```typescript theme={null}
(branch: string, remote: string, projectRoot?: string | undefined) => Promise<BranchProtectionResult>
```

## buildPRBody()

Build the markdown body for a GitHub pull request.

**Signature**

```typescript theme={null}
(opts: PRCreateOptions) => string
```

## formatManualPRInstructions()

Format human-readable instructions for creating a PR manually.

**Signature**

```typescript theme={null}
(opts: PRCreateOptions) => string
```

## createPullRequest()

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

**Signature**

```typescript theme={null}
(opts: PRCreateOptions) => Promise<PRResult>
```

## checkEpicCompleteness()

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

**Signature**

```typescript theme={null}
(releaseTaskIds: string[], cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<EpicCompletenessResult>
```

## checkDoubleListing()

Check if any tasks are listed in multiple releases.

**Signature**

```typescript theme={null}
(releaseTaskIds: string[], existingReleases: { version: string; tasks: string[]; }[]) => DoubleListingResult
```

## validateVersionFormat()

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

**Signature**

```typescript theme={null}
(version: string) => boolean
```

## isCalVer()

Check if a version string is CalVer format.

**Signature**

```typescript theme={null}
(version: string) => boolean
```

## calculateNewVersion()

Calculate new version from current + bump type.

**Signature**

```typescript theme={null}
(current: string, bump: string) => string
```

## getVersionBumpConfig()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => VersionBumpTarget[]
```

## isVersionBumpConfigured()

Check if version bump is configured.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => boolean
```

## bumpVersionFromConfig()

Bump version in all configured files.

**Signature**

```typescript theme={null}
(newVersion: string, options?: { dryRun?: boolean | undefined; }, cwd?: string | undefined) => { results: BumpResult[]; allSuccess: boolean; }
```

## prepareRelease()

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

**Signature**

```typescript theme={null}
(version: string, tasks: string[] | undefined, notes: string | undefined, loadTasksFn: () => Promise<ReleaseTaskRecord[]>, cwd?: string | undefined) => Promise<...>
```

## generateReleaseChangelog()

Generate changelog for a release.  T4788

**Signature**

```typescript theme={null}
(version: string, loadTasksFn: () => Promise<ReleaseTaskRecord[]>, cwd?: string | undefined) => Promise<{ version: string; changelog: string; taskCount: number; sections: Record<...>; }>
```

## listManifestReleases()

List all releases.  T4788

**Signature**

```typescript theme={null}
(optionsOrCwd?: string | ReleaseListOptions | undefined, cwd?: string | undefined) => Promise<{ releases: { version: string; status: string; createdAt: string; taskCount: number; }[]; total: number; filtered: number; latest?: string | undefined; page: LAFSPage; }>
```

## showManifestRelease()

Show release details.  T4788

**Signature**

```typescript theme={null}
(version: string, cwd?: string | undefined) => Promise<ReleaseManifest>
```

## commitRelease()

Mark release as committed (metadata only).  T4788

**Signature**

```typescript theme={null}
(version: string, cwd?: string | undefined) => Promise<{ version: string; status: string; committedAt: string; }>
```

## tagRelease()

Mark release as tagged (metadata only).  T4788

**Signature**

```typescript theme={null}
(version: string, cwd?: string | undefined) => Promise<{ version: string; status: string; taggedAt: string; }>
```

## runReleaseGates()

Run release validation gates.  T4788  T5586

**Signature**

```typescript theme={null}
(version: string, loadTasksFn: () => Promise<ReleaseTaskRecord[]>, cwd?: string | undefined, opts?: { dryRun?: boolean | undefined; } | undefined) => Promise<...>
```

## cancelRelease()

Cancel and remove a release in draft or prepared state. Only releases that have not yet been committed to git can be cancelled. For committed/tagged/pushed releases, use rollbackRelease() instead.   T5602

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string | undefined) => Promise<{ success: boolean; message: string; version: string; }>
```

## rollbackRelease()

Rollback a release.  T4788

**Signature**

```typescript theme={null}
(version: string, reason?: string | undefined, cwd?: string | undefined) => Promise<{ version: string; previousStatus: string; status: string; reason: string; }>
```

## pushRelease()

Push release to remote via git.  Respects config.release.push policy: - remote: override default remote (fallback to 'origin') - requireCleanTree: verify git working tree is clean before push - allowedBranches: verify current branch is in the allowed list - enabled: if false and no explicit push flag, caller should skip   T4788  T4276

**Signature**

```typescript theme={null}
(version: string, remote?: string | undefined, cwd?: string | undefined, opts?: { explicitPush?: boolean | undefined; mode?: PushMode | undefined; prBase?: string | undefined; epicId?: string | undefined; guided?: boolean | undefined; } | undefined) => Promise<...>
```

## markReleasePushed()

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

**Signature**

```typescript theme={null}
(version: string, pushedAt: string, cwd?: string | undefined, provenance?: { commitSha?: string | undefined; gitTag?: string | undefined; } | undefined) => Promise<void>
```

## migrateReleasesJsonToSqlite()

One-time migration: read .cleo/releases.json and insert each release into the release\_manifests table. Renames the file to releases.json.migrated on success.   T5580

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<{ migrated: number; }>
```

## gradeSession()

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

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<GradeResult>
```

## readGrades()

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

**Signature**

```typescript theme={null}
(sessionId?: string | undefined, cwd?: string | undefined) => Promise<GradeResult[]>
```

## handleSessionStart()

Handle onSessionStart - capture initial session context

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnSessionStartPayload) => Promise<void>
```

## handleSessionEnd()

Handle onSessionEnd - capture session summary

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnSessionEndPayload) => Promise<void>
```

## handleToolStart()

Handle onToolStart (maps to task.start in CLEO)

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnToolStartPayload) => Promise<void>
```

## handleToolComplete()

Handle onToolComplete (maps to task.complete in CLEO)

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnToolCompletePayload) => Promise<void>
```

## handleError()

Handle onError - capture operation errors to BRAIN  Includes infinite-loop guard: if the payload has \_fromHook marker, the handler skips to prevent onError - observeBrain - onError loops. Additionally, ALL observeBrain errors are silently suppressed to prevent re-entrant hook firing.

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnErrorPayload) => Promise<void>
```

## handleFileChange()

Handle onFileChange - capture file changes to BRAIN  Gated behind CLEO\_BRAIN\_CAPTURE\_FILES=true env var. Deduplicates rapid writes to the same file within a 5-second window. Filters out .cleo/ internal files and test temp directories. Converts absolute paths to project-relative paths.

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnFileChangePayload) => Promise<void>
```

## handlePromptSubmit()

Handle onPromptSubmit - optionally capture prompt events to BRAIN  No-op by default. Set CLEO\_BRAIN\_CAPTURE\_MCP=true to enable.

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnPromptSubmitPayload) => Promise<void>
```

## handleResponseComplete()

Handle onResponseComplete - optionally capture response events to BRAIN  No-op by default. Set CLEO\_BRAIN\_CAPTURE\_MCP=true to enable.

**Signature**

```typescript theme={null}
(projectRoot: string, payload: OnResponseCompletePayload) => Promise<void>
```

## recordAssumption()

Record an assumption made during a session. Appends to .cleo/audit/assumptions.jsonl (creates dir if needed). Throws if required params are missing or invalid.

**Signature**

```typescript theme={null}
(projectRoot: string, params: RecordAssumptionParams) => Promise<Omit<AssumptionRecord, "validatedAt"> & { timestamp: string; }>
```

## linkMemoryToTask()

Link a memory entry to a task.   T5156

**Signature**

```typescript theme={null}
(projectRoot: string, memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string, taskId: string, linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts") => Promise<...>
```

## unlinkMemoryFromTask()

Remove a link between a memory entry and a task.   T5156

**Signature**

```typescript theme={null}
(projectRoot: string, memoryType: "decision" | "pattern" | "learning" | "observation", memoryId: string, taskId: string, linkType: "produced_by" | "applies_to" | "informed_by" | "contradicts") => Promise<...>
```

## getTaskLinks()

Get all memory entries linked to a specific task.   T5156

**Signature**

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

## getMemoryLinks()

Get all tasks linked to a specific memory entry.   T5156

**Signature**

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

## bulkLink()

Batch create multiple links at once.   T5156

**Signature**

```typescript theme={null}
(projectRoot: string, links: BulkLinkEntry[]) => Promise<{ created: number; skipped: number; }>
```

## getLinkedDecisions()

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

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; type: "architecture" | "technical" | "process" | "strategic" | "tactical"; confidence: "high" | ... 1 more ... | "low"; ... 6 more ...; contextPhase: string | null; }[]>
```

## getLinkedPatterns()

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

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<{ id: string; updatedAt: string | null; type: "success" | "workflow" | "failure" | "blocker" | "optimization"; pattern: string; context: string; ... 6 more ...; extractedAt: string; }[]>
```

## getLinkedLearnings()

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

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<{ id: string; createdAt: string; updatedAt: string | null; source: string; confidence: number; insight: string; actionable: boolean; application: string | null; applicableTypesJson: string | null; }[]>
```

## extractMemoryItems()

Extract memory-worthy items from debrief data. Pure function -- no side effects.  Items extracted: - Decisions (from debrief.decisions\[]) - observations with type='decision' - Tasks completed summary - observation with type='change' - Session-level note (if present) - observation with type='discovery'

**Signature**

```typescript theme={null}
(sessionId: string, debrief: DebriefData | null | undefined) => MemoryItem[]
```

## persistSessionMemory(projectRoot, sessionId, debrief)

Main entry point -- called from session.end handler. Extracts memory-worthy content from debrief data and persists to brain.db.  ALL errors are caught and accumulated in result.errors -- never throws.

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string, debrief: DebriefData | null | undefined) => Promise<SessionMemoryResult>
```

**Parameters**

| Name          | Type                               | Description                                    |
| ------------- | ---------------------------------- | ---------------------------------------------- |
| `projectRoot` | `string`                           | Project root directory                         |
| `sessionId`   | `string`                           | The session that just ended                    |
| `debrief`     | `DebriefData \| null \| undefined` | Rich debrief data from sessionComputeDebrief() |

**Returns** — Summary of what was persisted

## getSessionMemoryContext(projectRoot, scope, options)

Retrieve session memory for a given scope. Used by briefing/handoff to enrich response with brain context.

**Signature**

```typescript theme={null}
(projectRoot: string, scope?: { type: string; epicId?: string | undefined; rootTaskId?: string | undefined; } | undefined, options?: { limit?: number | undefined; includeDecisions?: boolean | undefined; includePatterns?: boolean | undefined; } | undefined) => Promise<...>
```

**Parameters**

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

**Returns** — Relevant brain memory entries

## depsReady(depends, taskLookup)

Check if all dependencies of a task are satisfied.

**Signature**

```typescript theme={null}
(depends: string[] | undefined, taskLookup: ReadonlyMap<string, unknown>) => boolean
```

**Parameters**

| Name         | Type                    | Description                                                          |
| ------------ | ----------------------- | -------------------------------------------------------------------- |
| `depends`    | `string[] \| undefined` | Array of dependency task IDs (may be undefined/empty)                |
| `taskLookup` | `ReadonlyMap&lt;string` | Map from task ID to a task-like object with at least  status: string |

**Returns** — true if all dependencies are done/cancelled, or if no dependencies exist

## computeBriefing()

Compute the complete session briefing. Aggregates data from all 6+ sources.

**Signature**

```typescript theme={null}
(projectRoot: string, options?: BriefingOptions) => Promise<SessionBriefing>
```

## findSessions(accessor, params)

Find sessions with minimal field projection.  Loads all sessions, applies filters, then projects to minimal fields. This is cheaper for agents that only need discovery-level data.

**Signature**

```typescript theme={null}
(accessor: DataAccessor, params?: FindSessionsParams | undefined) => Promise<MinimalSessionRecord[]>
```

**Parameters**

| Name       | Type                                | Description                                    |
| ---------- | ----------------------------------- | ---------------------------------------------- |
| `accessor` | `DataAccessor`                      | DataAccessor for loading sessions              |
| `params`   | `: FindSessionsParams \| undefined` | Optional filters (status, scope, query, limit) |

**Returns** — Array of minimal session records

## archiveSessions()

Archive old/ended sessions. Identifies ended and suspended sessions older than the threshold. With SQLite, all sessions live in a single table — "archiving" marks them as identified for potential cleanup rather than moving between arrays.

**Signature**

```typescript theme={null}
(projectRoot: string, olderThan?: string | undefined) => Promise<{ archived: string[]; count: number; }>
```

## cleanupSessions()

Remove orphaned sessions, auto-end stale active sessions, and clean up stale data.  Stale active sessions (no activity beyond the configured threshold) are transitioned to 'ended' with an auto-end note. The threshold is read from `retention.autoEndActiveAfterDays` in the project config (default: 7 days).   T2304

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ removed: string[]; autoEnded: string[]; cleaned: boolean; }>
```

## getContextDrift()

Compute context drift score for the current session. Compares session progress against original scope by counting completed vs total tasks in scope, and detecting out-of-scope work.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { sessionId?: string | undefined; } | undefined) => Promise<ContextDriftResult>
```

## getSessionHistory()

List session history with focus changes and completed tasks. If sessionId is provided, returns history for that specific session. Otherwise, returns history across all sessions.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: SessionHistoryParams | undefined) => Promise<{ sessions: SessionHistoryEntry[]; }>
```

## showSession()

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

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<Session>
```

## getSessionStats()

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

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId?: string | undefined) => Promise<SessionStatsResult>
```

## suspendSession()

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

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string, reason?: string | undefined) => Promise<Session>
```

## switchSession()

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

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<Session>
```

## SessionView

**Signature**

```typescript theme={null}
typeof SessionView
```

**Methods**

### from()

Create a SessionView from a Session array.

```typescript theme={null}
(sessions: Session[]) => SessionView
```

### findActive()

Find the currently active session (if any).

```typescript theme={null}
() => Session | undefined
```

### findById()

Find a session by ID.

```typescript theme={null}
(id: string) => Session | undefined
```

### filterByStatus()

Filter sessions by one or more statuses.

```typescript theme={null}
(...statuses: ("active" | "ended" | "orphaned" | "suspended")[]) => Session[]
```

### findByScope()

Find sessions matching a scope type and optional rootTaskId.

```typescript theme={null}
(type: string, rootTaskId?: string | undefined) => Session[]
```

### sortByDate()

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

```typescript theme={null}
(field: "startedAt" | "endedAt", descending?: boolean) => Session[]
```

### mostRecent()

Get the most recently started session.

```typescript theme={null}
() => Session | undefined
```

### toArray()

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

```typescript theme={null}
() => Session[]
```

### [Symbol.iterator]()

Support for-of iteration.

```typescript theme={null}
() => Iterator<Session, any, any>
```

## selectRuntimeProviderContext()

**Signature**

```typescript theme={null}
(detections: DetectionResult[], snapshot?: RuntimeProviderSnapshot) => RuntimeProviderContext
```

## detectRuntimeProviderContext()

**Signature**

```typescript theme={null}
(snapshot?: RuntimeProviderSnapshot) => RuntimeProviderContext
```

## resetRuntimeProviderContextCache()

**Signature**

```typescript theme={null}
() => void
```

## parseScope()

Parse a scope string into a SessionScope.  T4463

**Signature**

```typescript theme={null}
(scopeStr: string) => SessionScope
```

## readSessions()

Read sessions from accessor or JSON file.  T4463

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session[]>
```

## saveSessions()

Save sessions via accessor or JSON file.  T4463

**Signature**

```typescript theme={null}
(sessions: Session[], cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<void>
```

## startSession()

Start a new session.  T4463

**Signature**

```typescript theme={null}
(options: StartSessionOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session>
```

## endSession()

End a session.  T4463

**Signature**

```typescript theme={null}
(options?: EndSessionOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session>
```

## sessionStatus()

Get current session status.  T4463

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session | null>
```

## resumeSession()

Resume an existing session.  T4463

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session>
```

## listSessions()

List sessions with optional filtering.  T4463

**Signature**

```typescript theme={null}
(options?: ListSessionsOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Session[]>
```

## gcSessions()

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

**Signature**

```typescript theme={null}
(maxAgeHours?: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ orphaned: string[]; removed: string[]; }>
```

## archiveSticky(id, projectRoot)

Archive a sticky note.

**Signature**

```typescript theme={null}
(id: string, projectRoot: string) => Promise<StickyNote | null>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `id`          | `string` | Sticky note ID    |
| `projectRoot` | `string` | Project root path |

**Returns** — The archived sticky note or null if not found

## convertStickyToTask(stickyId, taskTitle, projectRoot)

Convert a sticky note to a task.

**Signature**

```typescript theme={null}
(stickyId: string, taskTitle: string | undefined, projectRoot: string) => Promise<{ success: boolean; taskId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
```

**Parameters**

| Name          | Type                  | Description                                      |
| ------------- | --------------------- | ------------------------------------------------ |
| `stickyId`    | `string`              | Sticky note ID                                   |
| `taskTitle`   | `string \| undefined` | Optional task title (defaults to sticky content) |
| `projectRoot` | `string`              | Project root path                                |

**Returns** — Result with new task ID

## convertStickyToMemory(stickyId, memoryType, projectRoot)

Convert a sticky note to a memory observation.

**Signature**

```typescript theme={null}
(stickyId: string, memoryType: string | undefined, projectRoot: string) => Promise<{ success: boolean; memoryId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
```

**Parameters**

| Name          | Type                  | Description          |
| ------------- | --------------------- | -------------------- |
| `stickyId`    | `string`              | Sticky note ID       |
| `memoryType`  | `string \| undefined` | Optional memory type |
| `projectRoot` | `string`              | Project root path    |

**Returns** — Result with new memory entry ID

## convertStickyToTaskNote(stickyId, taskId, projectRoot)

Convert a sticky note to a task note.

**Signature**

```typescript theme={null}
(stickyId: string, taskId: string, projectRoot: string) => Promise<{ success: boolean; taskId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `stickyId`    | `string` | Sticky note ID    |
| `taskId`      | `string` | Target task ID    |
| `projectRoot` | `string` | Project root path |

**Returns** — Result with updated task ID

## convertStickyToSessionNote(stickyId, sessionId, projectRoot)

Convert a sticky note to a session note.

**Signature**

```typescript theme={null}
(stickyId: string, sessionId: string | undefined, projectRoot: string) => Promise<{ success: boolean; sessionId?: string | undefined; error?: { code: string; message: string; } | undefined; }>
```

**Parameters**

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

**Returns** — Result with session ID

## generateStickyId(projectRoot)

Generate the next sticky note ID.  Finds the highest existing SN-XXX ID and increments.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<string>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `projectRoot` | `string` | Project root path |

**Returns** — Next sticky note ID (e.g., "SN-042")

## addSticky(params, projectRoot)

Create a new sticky note.

**Signature**

```typescript theme={null}
(params: CreateStickyParams, projectRoot: string) => Promise<StickyNote>
```

**Parameters**

| Name          | Type                 | Description         |
| ------------- | -------------------- | ------------------- |
| `params`      | `CreateStickyParams` | Creation parameters |
| `projectRoot` | `string`             | Project root path   |

**Returns** — The created sticky note

## listStickies(params, projectRoot)

List sticky notes with optional filters.

**Signature**

```typescript theme={null}
(params: ListStickiesParams, projectRoot: string) => Promise<StickyNote[]>
```

**Parameters**

| Name          | Type                 | Description       |
| ------------- | -------------------- | ----------------- |
| `params`      | `ListStickiesParams` | Filter parameters |
| `projectRoot` | `string`             | Project root path |

**Returns** — Array of sticky notes

## purgeSticky(id, projectRoot)

Purge (permanently delete) a sticky note.

**Signature**

```typescript theme={null}
(id: string, projectRoot: string) => Promise<StickyNote | null>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `id`          | `string` | Sticky note ID    |
| `projectRoot` | `string` | Project root path |

**Returns** — The deleted sticky note or null if not found

## getSticky(id, projectRoot)

Get a sticky note by ID.

**Signature**

```typescript theme={null}
(id: string, projectRoot: string) => Promise<StickyNote | null>
```

**Parameters**

| Name          | Type     | Description                     |
| ------------- | -------- | ------------------------------- |
| `id`          | `string` | Sticky note ID (e.g., "SN-042") |
| `projectRoot` | `string` | Project root path               |

**Returns** — The sticky note or null if not found

## archiveTasks()

Archive completed (and optionally cancelled) tasks. Moves them from active task data to archive.  T4461

**Signature**

```typescript theme={null}
(options?: ArchiveTasksOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ArchiveTasksResult>
```

## deleteTask()

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

**Signature**

```typescript theme={null}
(options: DeleteTaskOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<DeleteTaskResult>
```

## Cleo

**Signature**

```typescript theme={null}
typeof Cleo
```

**Methods**

### init()

```typescript theme={null}
(projectRoot: string, options?: CleoInitOptions | undefined) => Promise<Cleo>
```

### forProject()

```typescript theme={null}
(projectRoot: string) => Cleo
```

## calculateExportChecksum()

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

**Signature**

```typescript theme={null}
(tasksJson: string) => string
```

## verifyExportChecksum()

Verify export package checksum.

**Signature**

```typescript theme={null}
(pkg: ExportPackage) => boolean
```

## buildIdMap()

Build ID map from tasks.

**Signature**

```typescript theme={null}
(tasks: Task[]) => Record<string, IdMapEntry>
```

## buildRelationshipGraph()

Build relationship graph from tasks.

**Signature**

```typescript theme={null}
(tasks: Task[]) => RelationshipGraph
```

## buildExportPackage()

Build a complete export package.

**Signature**

```typescript theme={null}
(tasks: Task[], taskData: TaskFile, options: { mode: string; rootTaskIds: string[]; includeChildren: boolean; cleoVersion?: string | undefined; filters?: unknown; }) => ExportPackage
```

## exportSingle()

Export a single task.

**Signature**

```typescript theme={null}
(taskId: string, taskData: TaskFile) => ExportPackage | null
```

## exportSubtree()

Export a subtree (task + all descendants).

**Signature**

```typescript theme={null}
(rootId: string, taskData: TaskFile) => ExportPackage | null
```

## exportTasksPackage()

Export tasks to a portable cross-project package.

**Signature**

```typescript theme={null}
(params: ExportTasksParams) => Promise<ExportTasksResult>
```

## getCostHint()

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

**Signature**

```typescript theme={null}
(domain: string, operation: string) => CostHint
```

## groupOperationsByDomain(ops)

Group operations by domain into a compact format.

**Signature**

```typescript theme={null}
(ops: HelpOperationDef[]) => GroupedOperations
```

**Parameters**

| Name  | Type                 | Description                               |
| ----- | -------------------- | ----------------------------------------- |
| `ops` | `HelpOperationDef[]` | Operations filtered to the requested tier |

**Returns** — Domain-grouped operations with query and mutate arrays

## buildVerboseOperations(ops)

Build verbose operation entries with cost hints.

**Signature**

```typescript theme={null}
(ops: HelpOperationDef[]) => VerboseOperation[]
```

**Parameters**

| Name  | Type                 | Description                               |
| ----- | -------------------- | ----------------------------------------- |
| `ops` | `HelpOperationDef[]` | Operations filtered to the requested tier |

**Returns** — Array of verbose operation objects

## computeHelp(allOperations, tier, verbose)

Compute the help result for the admin.help operation.  Accepts the full OPERATIONS registry and filters/formats based on tier and verbosity. This is pure business logic with no dispatch or engine dependencies.

**Signature**

```typescript theme={null}
(allOperations: HelpOperationDef[], tier: number, verbose: boolean) => HelpResult
```

**Parameters**

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

**Returns** — The computed help result

## getNextAvailableId()

Get the next available task ID number from existing tasks.

**Signature**

```typescript theme={null}
(tasks: Task[]) => number
```

## generateRemapTable()

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

**Signature**

```typescript theme={null}
(sourceTaskIds: string[], existingTasks: Task[]) => RemapTable
```

## validateRemapTable()

Validate that a remap table is complete and consistent.

**Signature**

```typescript theme={null}
(table: RemapTable, expectedSourceIds: string[]) => { valid: boolean; errors: string[]; }
```

## remapTaskId()

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

**Signature**

```typescript theme={null}
(taskId: string | null, table: RemapTable) => string | null
```

## remapTaskReferences()

Remap all ID references in a task.

**Signature**

```typescript theme={null}
(task: Task, table: RemapTable, existingTaskIds: Set<string>, missingDepStrategy?: "fail" | "strip") => Task
```

## detectDuplicateTitles()

Detect duplicate titles between import and target.

**Signature**

```typescript theme={null}
(importTasks: Task[], existingTasks: Task[]) => { sourceId: string; title: string; existingId: string; }[]
```

## resolveDuplicateTitle()

Resolve duplicate title by appending suffix.

**Signature**

```typescript theme={null}
(title: string, existingTitles: Set<string>) => string
```

## importTasksPackage()

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

**Signature**

```typescript theme={null}
(params: ImportTasksParams) => Promise<ImportTasksResult>
```

## findAdrs()

**Signature**

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

## listAdrs()

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

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { status?: string | undefined; since?: string | undefined; limit?: number | undefined; offset?: number | undefined; } | undefined) => Promise<AdrListResult>
```

## showAdr()

Retrieve a single ADR by ID (e.g., 'ADR-007')

**Signature**

```typescript theme={null}
(projectRoot: string, adrId: string) => Promise<AdrRecord | null>
```

## validateAllAdrs()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ValidationResult>
```

## providerList()

List all registered providers.  T4332

**Signature**

```typescript theme={null}
() => EngineResult<Provider[]>
```

## providerGet()

Get a single provider by ID or alias.  T4332

**Signature**

```typescript theme={null}
(idOrAlias: string) => EngineResult<Provider>
```

## providerDetect()

Detect all providers installed on the system.  T4332

**Signature**

```typescript theme={null}
() => EngineResult<DetectionResult[]>
```

## providerInstalled()

Get providers that are installed on the system.  T4332

**Signature**

```typescript theme={null}
() => EngineResult<Provider[]>
```

## providerCount()

Get count of registered providers.  T4332

**Signature**

```typescript theme={null}
() => EngineResult<{ count: number; }>
```

## registryVersion()

Get CAAMP registry version.  T4332

**Signature**

```typescript theme={null}
() => EngineResult<{ version: string; }>
```

## mcpList()

List MCP servers for a specific provider.  T4332

**Signature**

```typescript theme={null}
(providerId: string, scope: "global" | "project", projectDir?: string | undefined) => Promise<EngineResult<{ servers: unknown[]; }>>
```

## mcpListAll()

List MCP servers across all installed providers.  T4332

**Signature**

```typescript theme={null}
(scope: "global" | "project", projectDir?: string | undefined) => Promise<EngineResult<{ servers: unknown[]; }>>
```

## mcpInstall()

Install an MCP server to a provider's config.  T4332

**Signature**

```typescript theme={null}
(providerId: string, serverName: string, config: McpServerConfig, scope?: "global" | "project" | undefined, projectDir?: string | undefined) => Promise<EngineResult<InstallResult>>
```

## mcpRemove()

Remove an MCP server from a provider's config.  T4332

**Signature**

```typescript theme={null}
(providerId: string, serverName: string, scope: "global" | "project", projectDir?: string | undefined) => Promise<EngineResult<{ removed: boolean; }>>
```

## mcpConfigPath()

Resolve the config file path for a provider.  T4332

**Signature**

```typescript theme={null}
(providerId: string, scope: "global" | "project", projectDir?: string | undefined) => EngineResult<{ path: string | null; }>
```

## injectionCheck()

Check injection status for a single file.  T4332

**Signature**

```typescript theme={null}
(filePath: string, expectedContent?: string | undefined) => Promise<EngineResult<InjectionStatus>>
```

## injectionCheckAll()

Check injection status across all providers.  T4332

**Signature**

```typescript theme={null}
(projectDir: string, scope: "global" | "project", expectedContent?: string | undefined) => Promise<EngineResult<{ results: unknown[]; }>>
```

## injectionUpdate()

Inject or update content in a single file.  T4332

**Signature**

```typescript theme={null}
(filePath: string, content: string) => Promise<EngineResult<{ action: string; }>>
```

## injectionUpdateAll()

Inject content to all providers' instruction files.  T4332

**Signature**

```typescript theme={null}
(projectDir: string, scope: "global" | "project", content: string) => Promise<EngineResult<{ results: Record<string, string>; }>>
```

## batchInstallWithRollback()

Install multiple MCP servers atomically with rollback on failure. Supports Wave 4 init rewrite which needs to install multiple skills/configs as a single atomic operation.   T4705  T4663

**Signature**

```typescript theme={null}
(options: BatchInstallOptions) => Promise<EngineResult<BatchInstallResult>>
```

## dualScopeConfigure()

Configure a provider at both global and project scope simultaneously. Used during init to set up MCP configs in both scopes atomically.   T4705  T4663

**Signature**

```typescript theme={null}
(providerId: string, options: DualScopeConfigureOptions) => Promise<EngineResult<DualScopeConfigureResult>>
```

## checkProviderCapability(provider, capabilityPath)

Check if provider supports a specific capability

**Signature**

```typescript theme={null}
(provider: string | Provider, capabilityPath: string) => boolean
```

**Parameters**

| Name             | Type                 | Description                                         |
| ---------------- | -------------------- | --------------------------------------------------- |
| `provider`       | `string \| Provider` | Provider object or ID                               |
| `capabilityPath` | `string`             | Dot notation path (e.g., 'spawn.supportsSubagents') |

**Returns** — boolean  Examples: - providerSupports(provider, 'spawn.supportsSubagents') - providerSupports(provider, 'hooks.supported') - providerSupportsById('claude-code', 'spawn.supportsParallelSpawn') - providerSupportsById('gemini-cli', 'skills.precedence')

## checkProviderCapabilities()

Check multiple capabilities at once

**Signature**

```typescript theme={null}
(providerId: string, capabilities: string[]) => Record<string, boolean>
```

## getComplianceJsonlPath()

Resolve COMPLIANCE.jsonl path for a project root.

**Signature**

```typescript theme={null}
(projectRoot: string) => string
```

## readComplianceJsonl()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => ComplianceJsonlEntry[]
```

## appendComplianceJsonl()

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

**Signature**

```typescript theme={null}
(projectRoot: string, entry: ComplianceJsonlEntry) => void
```

## getComplianceSummary()

Get compliance summary.

**Signature**

```typescript theme={null}
(opts: { since?: string | undefined; agent?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## listComplianceViolations()

List compliance violations.

**Signature**

```typescript theme={null}
(opts: { severity?: string | undefined; since?: string | undefined; agent?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## getComplianceTrend()

Get compliance trend.

**Signature**

```typescript theme={null}
(days?: number, cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## auditEpicCompliance()

Audit epic compliance.

**Signature**

```typescript theme={null}
(epicId: string, opts: { since?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## syncComplianceMetrics()

Sync compliance metrics to a summary file.

**Signature**

```typescript theme={null}
(opts: { force?: boolean | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## getSkillReliability()

Get skill reliability stats.

**Signature**

```typescript theme={null}
(opts: { global?: boolean | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## getValueMetrics()

Get value metrics (T2833).

**Signature**

```typescript theme={null}
(days?: number, cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## getContextStatus()

Get context status.

**Signature**

```typescript theme={null}
(opts: { session?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## checkContextThreshold()

Check context threshold (returns exit code info).

**Signature**

```typescript theme={null}
(opts: { session?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown> & { exitCode?: number | undefined; }>
```

## listContextSessions()

List all context state files.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## injectTasks()

Inject tasks for external consumption.

**Signature**

```typescript theme={null}
(opts: { maxTasks?: number | undefined; focusedOnly?: boolean | undefined; phase?: string | undefined; output?: string | undefined; saveState?: boolean | undefined; dryRun?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<...>
```

## collectDiagnostics()

Collect system diagnostics for bug reports.

**Signature**

```typescript theme={null}
() => Record<string, string>
```

## formatDiagnosticsTable()

Format diagnostics as markdown table.

**Signature**

```typescript theme={null}
(diag: Record<string, string>) => string
```

## parseIssueTemplates()

Parse all issue templates from available sources. Priority:   1. Packaged templates in the CLEO installation (for npm-installed users)   2. Project's .github/ISSUE\_TEMPLATE/ (for contributors working on CLEO)

**Signature**

```typescript theme={null}
(projectDir?: string | undefined) => IssueTemplate[]
```

## getTemplateConfig()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => IssueTemplate[]
```

## getTemplateForSubcommand()

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

**Signature**

```typescript theme={null}
(subcommand: string, cwd?: string | undefined) => IssueTemplate | null
```

## cacheTemplates()

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

**Signature**

```typescript theme={null}
(templates: IssueTemplate[], cwd?: string | undefined) => void
```

## validateLabelsExist()

Validate that required labels exist (informational).

**Signature**

```typescript theme={null}
(_templates: IssueTemplate[]) => { valid: boolean; missingLabels: string[]; }
```

## buildIssueBody()

Build structured issue body with template sections.

**Signature**

```typescript theme={null}
(subcommand: string, rawBody: string, severity?: string | undefined, area?: string | undefined) => string
```

## checkGhCli()

Check that gh CLI is installed and authenticated.

**Signature**

```typescript theme={null}
() => void
```

## addIssue()

Add a GitHub issue for a given type (bug, feature, help). Returns structured result. Does not handle CLI output or process.exit.  Note: Named 'add' per VERB-STANDARDS.md (canonical verb for "Create new entity")

**Signature**

```typescript theme={null}
(params: AddIssueParams) => AddIssueResult
```

## applyTemporalDecay(projectRoot, options)

Apply temporal decay to brain\_learnings confidence values.  Entries older than `olderThanDays` have their confidence reduced by an exponential decay factor based on the number of days since their last update (or creation if never updated).  Formula: new\_confidence = confidence \* (decayRate ^ daysSinceUpdate)

**Signature**

```typescript theme={null}
(projectRoot: string, options?: { decayRate?: number | undefined; olderThanDays?: number | undefined; } | undefined) => Promise<DecayResult>
```

**Parameters**

| Name          | Type                                                                                         | Description                                    |
| ------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `projectRoot` | `string`                                                                                     | Project root directory for brain.db resolution |
| `options`     | `: \{ decayRate?: number \| undefined; olderThanDays?: number \| undefined; \} \| undefined` | Decay configuration                            |

**Returns** — Count of updated rows and tables processed

## consolidateMemories(projectRoot, options)

Consolidate old observations by keyword similarity.  Groups observations older than `olderThanDays` by FTS5 keyword overlap. For groups with at least `minClusterSize` entries, creates one summary observation and marks originals as archived (updated\_at set, narrative prefixed with \[ARCHIVED]).

**Signature**

```typescript theme={null}
(projectRoot: string, options?: { olderThanDays?: number | undefined; minClusterSize?: number | undefined; } | undefined) => Promise<ConsolidationResult>
```

**Parameters**

| Name          | Type                                                                                              | Description                                    |
| ------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `projectRoot` | `string`                                                                                          | Project root directory for brain.db resolution |
| `options`     | `: \{ olderThanDays?: number \| undefined; minClusterSize?: number \| undefined; \} \| undefined` | Consolidation configuration                    |

**Returns** — Counts of grouped, merged, and archived observations

## migrateBrainData()

Migrate BRAIN memory data from JSONL files to brain.db.  Reads: - .cleo/memory/patterns.jsonl - brain\_patterns table - .cleo/memory/learnings.jsonl - brain\_learnings table  Skips entries where the ID already exists in the database (idempotent).   T5129

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<BrainMigrationResult>
```

## addResearch()

Add a research entry.  T4465

**Signature**

```typescript theme={null}
(options: AddResearchOptions, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ResearchEntry>
```

## showResearch()

Show a specific research entry.  T4465

**Signature**

```typescript theme={null}
(researchId: string, cwd?: string | undefined) => Promise<ResearchEntry>
```

## listResearch()

List research entries with optional filtering.  T4465

**Signature**

```typescript theme={null}
(options?: ListResearchOptions, cwd?: string | undefined) => Promise<ResearchEntry[]>
```

## pendingResearch()

List pending research entries.  T4465

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<ResearchEntry[]>
```

## linkResearch()

Link a research entry to a task.  T4465

**Signature**

```typescript theme={null}
(researchId: string, taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ researchId: string; taskId: string; }>
```

## updateResearch()

Update research findings.  T4465

**Signature**

```typescript theme={null}
(researchId: string, updates: { findings?: string[] | undefined; sources?: string[] | undefined; status?: "complete" | "pending" | "partial" | undefined; }, cwd?: string | undefined) => Promise<...>
```

## statsResearch()

Get research statistics.  T4474

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ total: number; byStatus: Record<string, number>; byTopic: Record<string, number>; }>
```

## linksResearch()

Get research entries linked to a specific task.  T4474

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<ResearchEntry[]>
```

## archiveResearch()

Archive old research entries by status. Moves 'complete' entries older than a threshold to an archive, or returns summary of archivable entries.  T4474

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ action: string; entriesArchived: number; entriesRemaining: number; }>
```

## readManifest()

Read manifest entries from MANIFEST.jsonl.  T4465

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<ManifestEntry[]>
```

## appendManifest()

Append a manifest entry.  T4465

**Signature**

```typescript theme={null}
(entry: ManifestEntry, cwd?: string | undefined) => Promise<void>
```

## queryManifest()

Query manifest entries.  T4465

**Signature**

```typescript theme={null}
(options?: ManifestQueryOptions, cwd?: string | undefined) => Promise<ManifestEntry[]>
```

## readExtendedManifest()

Read all manifest entries as extended entries.  T4787

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<ExtendedManifestEntry[]>
```

## filterManifestEntries()

Filter manifest entries by criteria.  T4787

**Signature**

```typescript theme={null}
(entries: ExtendedManifestEntry[], filter: ResearchFilter) => ExtendedManifestEntry[]
```

## showManifestEntry()

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

**Signature**

```typescript theme={null}
(researchId: string, cwd?: string | undefined) => Promise<ExtendedManifestEntry & { fileContent: string | null; fileExists: boolean; }>
```

## searchManifest()

Search manifest entries by text with relevance scoring.  T4787

**Signature**

```typescript theme={null}
(query: string, options?: { confidence?: number | undefined; limit?: number | undefined; } | undefined, cwd?: string | undefined) => Promise<(ExtendedManifestEntry & { ...; })[]>
```

## pendingManifestEntries()

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

**Signature**

```typescript theme={null}
(epicId?: string | undefined, cwd?: string | undefined) => Promise<{ entries: ExtendedManifestEntry[]; total: number; byStatus: { partial: number; blocked: number; needsFollowup: number; }; }>
```

## manifestStats()

Get manifest-based research statistics.  T4787

**Signature**

```typescript theme={null}
(epicId?: string | undefined, cwd?: string | undefined) => Promise<{ total: number; byStatus: Record<string, number>; byType: Record<string, number>; actionable: number; needsFollowup: number; averageFindings: number; }>
```

## linkManifestEntry()

Link a manifest entry to a task (adds taskId to linked\_tasks array).  T4787

**Signature**

```typescript theme={null}
(taskId: string, researchId: string, cwd?: string | undefined) => Promise<{ taskId: string; researchId: string; alreadyLinked: boolean; }>
```

## appendExtendedManifest()

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

**Signature**

```typescript theme={null}
(entry: ExtendedManifestEntry, cwd?: string | undefined) => Promise<{ entryId: string; file: string; }>
```

## archiveManifestEntries()

Archive manifest entries older than a date.  T4787

**Signature**

```typescript theme={null}
(beforeDate: string, cwd?: string | undefined) => Promise<{ archived: number; remaining: number; archiveFile: string; }>
```

## findContradictions()

Find manifest entries with overlapping topics but conflicting key\_findings.  T4787

**Signature**

```typescript theme={null}
(cwd?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<ContradictionDetail[]>
```

## findSuperseded()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<SupersededDetail[]>
```

## readProtocolInjection()

Read protocol injection content for a given protocol type.  T4787

**Signature**

```typescript theme={null}
(protocolType: string, params?: { taskId?: string | undefined; variant?: string | undefined; } | undefined, cwd?: string | undefined) => Promise<{ protocolType: string; content: string; ... 4 more ...; variant: string | null; }>
```

## compactManifest()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ compacted: boolean; originalLines: number; malformedRemoved: number; duplicatesRemoved: number; remainingEntries: number; }>
```

## validateManifestEntries()

Validate research entries for a task.  T4787

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<{ taskId: string; valid: boolean; entriesFound: number; issues: { entryId: string; issue: string; severity: "error" | "warning"; }[]; errorCount: number; warningCount: number; }>
```

## ensureMetricsDir()

Ensure metrics directory exists, returning its path.

**Signature**

```typescript theme={null}
(metricsDir?: string | undefined) => Promise<string>
```

## getCompliancePath()

Get compliance log path.

**Signature**

```typescript theme={null}
(metricsDir?: string | undefined) => string
```

## getViolationsPath()

Get violations log path.

**Signature**

```typescript theme={null}
(metricsDir?: string | undefined) => string
```

## getSessionsMetricsPath()

Get sessions metrics log path.

**Signature**

```typescript theme={null}
(metricsDir?: string | undefined) => string
```

## isoTimestamp()

Generate ISO 8601 UTC timestamp.

**Signature**

```typescript theme={null}
() => string
```

## isoDate()

Generate ISO 8601 date only.

**Signature**

```typescript theme={null}
() => string
```

## readJsonlFile()

Read a JSONL file into an array of parsed objects.

**Signature**

```typescript theme={null}
(filePath: string) => Record<string, unknown>[]
```

## getComplianceSummaryBase()

Get compliance summary from log file.

**Signature**

```typescript theme={null}
(compliancePath?: string | undefined) => ComplianceSummary
```

## isOtelEnabled()

Check if OTel telemetry is enabled.

**Signature**

```typescript theme={null}
() => boolean
```

## getOtelSetupCommands()

Get environment variable commands for OTel capture setup.

**Signature**

```typescript theme={null}
(mode?: OtelCaptureMode, cwd?: string | undefined) => string
```

## parseTokenMetrics()

Parse OTel token metrics from collected data.

**Signature**

```typescript theme={null}
(inputFile?: string | undefined, cwd?: string | undefined) => OtelTokenDataPoint[]
```

## getSessionTokens()

Get aggregated token counts from OTel data.

**Signature**

```typescript theme={null}
(sessionId?: string | undefined, cwd?: string | undefined) => AggregatedTokens
```

## recordSessionStart()

Record token counts at session start.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## recordSessionEnd()

Record token counts at session end.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## compareSessions()

Compare token usage between two sessions.

**Signature**

```typescript theme={null}
(sessionA: string, sessionB: string, cwd?: string | undefined) => Record<string, unknown>
```

## getTokenStats()

Get statistics about token usage across sessions.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Record<string, unknown>
```

## logABEvent()

Log an A/B test event.

**Signature**

```typescript theme={null}
(eventType: ABEventType, testName: string, variant: ABVariant, context?: string | Record<string, unknown> | undefined, cwd?: string | undefined) => Promise<...>
```

## startABTest()

Start an A/B test session.

**Signature**

```typescript theme={null}
(testName: string, variant: ABVariant, description?: string | undefined, cwd?: string | undefined) => Promise<void>
```

## endABTest()

End an A/B test session with summary.

**Signature**

```typescript theme={null}
(options?: { tasksCompleted?: number | undefined; validationPasses?: number | undefined; validationFailures?: number | undefined; notes?: string | undefined; }, cwd?: string | undefined) => Promise<...>
```

## getABTestResults()

Get results for a specific test variant.

**Signature**

```typescript theme={null}
(testName: string, variant: ABVariant, cwd?: string | undefined) => Record<string, unknown> | null
```

## listABTests()

List all A/B tests.

**Signature**

```typescript theme={null}
(filter?: string | undefined, cwd?: string | undefined) => Record<string, unknown>[]
```

## compareABTest()

Compare two variants of the same test.

**Signature**

```typescript theme={null}
(testName: string, cwd?: string | undefined) => Record<string, unknown>
```

## getABTestStats()

Get aggregate statistics of all A/B tests.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Record<string, unknown>
```

## syncMetricsToGlobal()

Sync project metrics to global aggregation file.

**Signature**

```typescript theme={null}
(options?: { force?: boolean | undefined; }, cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## getProjectComplianceSummary()

Get compliance summary for the current project.

**Signature**

```typescript theme={null}
(options?: { since?: string | undefined; agent?: string | undefined; category?: string | undefined; }, cwd?: string | undefined) => Record<string, unknown>
```

## getGlobalComplianceSummary()

Get compliance summary across all projects.

**Signature**

```typescript theme={null}
(options?: { since?: string | undefined; project?: string | undefined; }) => Record<string, unknown>
```

## getComplianceTrend()

Get compliance trend over time.

**Signature**

```typescript theme={null}
(days?: number, options?: { project?: string | undefined; global?: boolean | undefined; }, cwd?: string | undefined) => Record<string, unknown>
```

## getSkillReliability()

Get reliability stats per skill/agent.

**Signature**

```typescript theme={null}
(options?: { since?: string | undefined; global?: boolean | undefined; }, cwd?: string | undefined) => Record<string, unknown>
```

## logSessionMetrics()

Log session metrics to SESSIONS.jsonl.

**Signature**

```typescript theme={null}
(metricsJson: Record<string, unknown>, cwd?: string | undefined) => Promise<Record<string, unknown>>
```

## getSessionMetricsSummary()

Get summary of session metrics.

**Signature**

```typescript theme={null}
(options?: { since?: string | undefined; }, cwd?: string | undefined) => Record<string, unknown>
```

## isValidEnumValue()

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

**Signature**

```typescript theme={null}
<T extends Record<string, string>>(enumObj: T, value: string) => value is T[keyof T]
```

## estimateTokens()

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

**Signature**

```typescript theme={null}
(text: string) => number
```

## estimateTokensFromFile()

Estimate token count from a file.

**Signature**

```typescript theme={null}
(filePath: string) => number
```

## logTokenEvent()

Log a token usage event to the JSONL file.

**Signature**

```typescript theme={null}
(eventType: TokenEventType, tokens: number, source: string, taskId?: string | undefined, context?: Record<string, unknown> | undefined, cwd?: string | undefined) => Promise<...>
```

## trackFileRead()

Track a file read with token estimate.

**Signature**

```typescript theme={null}
(filePath: string, purpose: string, taskId?: string | undefined, cwd?: string | undefined) => Promise<number>
```

## trackManifestQuery()

Track a manifest query (partial read).

**Signature**

```typescript theme={null}
(queryType: string, resultCount: number, taskId?: string | undefined, cwd?: string | undefined) => Promise<number>
```

## trackSkillInjection()

Track skill injection with tokens.

**Signature**

```typescript theme={null}
(skillName: string, tier: number, tokens: number, taskId?: string | undefined, cwd?: string | undefined) => Promise<void>
```

## trackPromptBuild()

Track final prompt size.

**Signature**

```typescript theme={null}
(prompt: string, taskId: string, skillsUsed: string, cwd?: string | undefined) => Promise<number>
```

## trackSpawnOutput()

Track subagent output tokens.

**Signature**

```typescript theme={null}
(taskId: string, outputText: string, sessionId?: string | undefined, cwd?: string | undefined) => Promise<number>
```

## trackSpawnComplete()

Track complete spawn cycle (prompt + output).

**Signature**

```typescript theme={null}
(taskId: string, promptTokens: number, outputTokens: number, sessionId?: string | undefined, cwd?: string | undefined) => Promise<number>
```

## startTokenSession()

Start tracking tokens for a session.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<void>
```

## endTokenSession()

End token tracking session with summary.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<TokenSessionSummary | null>
```

## getTokenSummary()

Get token usage summary for a time period.

**Signature**

```typescript theme={null}
(days?: number, cwd?: string | undefined) => Record<string, unknown>
```

## compareManifestVsFull()

Compare manifest vs full file token usage strategies.

**Signature**

```typescript theme={null}
(manifestEntries: number) => Record<string, unknown>
```

## getTrackingStatus()

Get tracking status.

**Signature**

```typescript theme={null}
() => { tracking_enabled: boolean; env_var: string; }
```

## computeChecksum(filePath)

Compute SHA-256 checksum of a file.

**Signature**

```typescript theme={null}
(filePath: string) => Promise<string>
```

**Parameters**

| Name       | Type     | Description      |
| ---------- | -------- | ---------------- |
| `filePath` | `string` | Path to the file |

**Returns** — Hex-encoded SHA-256 checksum  T4728

## verifyBackup(sourcePath, backupPath)

Verify that a backup file matches the source file and is a valid SQLite database.  Performs three checks: 1. Computes SHA-256 checksum of both files 2. Compares checksums to detect any content differences 3. Verifies the backup can be opened as a valid SQLite database

**Signature**

```typescript theme={null}
(sourcePath: string, backupPath: string) => Promise<VerificationResult>
```

**Parameters**

| Name         | Type     | Description                      |
| ------------ | -------- | -------------------------------- |
| `sourcePath` | `string` | Path to the source database file |
| `backupPath` | `string` | Path to the backup file          |

**Returns** — VerificationResult with checksums and validity status  T4728

## compareChecksums(filePath1, filePath2)

Quick checksum comparison without SQLite verification. Use when you only need to compare file contents.

**Signature**

```typescript theme={null}
(filePath1: string, filePath2: string) => Promise<boolean>
```

**Parameters**

| Name        | Type     | Description      |
| ----------- | -------- | ---------------- |
| `filePath1` | `string` | First file path  |
| `filePath2` | `string` | Second file path |

**Returns** — true if checksums match, false otherwise  T4728

## MigrationLogger

Structured logger for migration operations

**Signature**

```typescript theme={null}
typeof MigrationLogger
```

**Methods**

### getLevelPriority()

Get numeric priority for log level comparison.

```typescript theme={null}
(level: LogLevel) => number
```

### shouldLog()

Check if a log level should be recorded.

```typescript theme={null}
(level: LogLevel) => boolean
```

### log()

Write a log entry.

```typescript theme={null}
(level: LogLevel, phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void
```

### info()

Log an info-level message.

```typescript theme={null}
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void
```

### warn()

Log a warning-level message.

```typescript theme={null}
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void
```

### error()

Log an error-level message.

```typescript theme={null}
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void
```

### debug()

Log a debug-level message.

```typescript theme={null}
(phase: string, operation: string, message: string, data?: Record<string, unknown> | undefined) => void
```

### logFileOperation()

Log file operation with size information.

```typescript theme={null}
(phase: string, operation: "read" | "write" | "delete" | "rename" | "backup", sourcePath: string, targetPath?: string | undefined, additionalData?: Record<string, unknown> | undefined) => void
```

### logValidation()

Log validation result.

```typescript theme={null}
(phase: string, target: string, valid: boolean, details?: Record<string, unknown> | undefined, errors?: string[] | undefined) => void
```

### logImportProgress()

Log import progress.

```typescript theme={null}
(phase: string, entityType: string, imported: number, total: number, additionalData?: Record<string, unknown> | undefined) => void
```

### phaseStart()

Log phase start.

```typescript theme={null}
(phase: string, data?: Record<string, unknown> | undefined) => void
```

### phaseComplete()

Log phase completion.

```typescript theme={null}
(phase: string, data?: Record<string, unknown> | undefined) => void
```

### phaseFailed()

Log phase failure.

```typescript theme={null}
(phase: string, error: string | Error, data?: Record<string, unknown> | undefined) => void
```

### cleanupOldLogs()

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

```typescript theme={null}
() => void
```

### getLogPath()

Get the absolute path to the log file.

```typescript theme={null}
() => string
```

### getRelativeLogPath()

Get the path to the log file relative to cleoDir.

```typescript theme={null}
() => string
```

### getEntries()

Get all logged entries.

```typescript theme={null}
() => MigrationLogEntry[]
```

### getEntriesByLevel()

Get entries filtered by level.

```typescript theme={null}
(level: LogLevel) => MigrationLogEntry[]
```

### getEntriesByPhase()

Get entries for a specific phase.

```typescript theme={null}
(phase: string) => MigrationLogEntry[]
```

### getDurationMs()

Get the total duration of the migration so far.

```typescript theme={null}
() => number
```

### getSummary()

Get summary statistics for the migration.

```typescript theme={null}
() => { totalEntries: number; durationMs: number; errors: number; warnings: number; info: number; debug: number; phases: string[]; }
```

## createMigrationLogger()

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

**Signature**

```typescript theme={null}
(cleoDir: string, config?: MigrationLoggerConfig | undefined) => MigrationLogger
```

## readMigrationLog()

Read and parse a migration log file.

**Signature**

```typescript theme={null}
(logPath: string) => MigrationLogEntry[]
```

## logFileExists()

Check if a log file exists and is readable.

**Signature**

```typescript theme={null}
(logPath: string) => boolean
```

## getLatestMigrationLog()

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

**Signature**

```typescript theme={null}
(cleoDir: string) => string | null
```

## checkStorageMigration()

Check whether legacy JSON data needs to be migrated to SQLite.  Returns a diagnostic result that callers can use to warn users. This function is read-only and never modifies any files.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => PreflightResult
```

## createMigrationState(cleoDir, sourceFiles)

Create initial migration state at the start of migration.  Captures source file checksums and initializes progress tracking. Uses atomic write pattern to ensure state is never in an inconsistent state.

**Signature**

```typescript theme={null}
(cleoDir: string, sourceFiles?: { todoJson?: SourceFileInfo | undefined; sessionsJson?: SourceFileInfo | undefined; archiveJson?: SourceFileInfo | undefined; } | undefined) => Promise<...>
```

**Parameters**

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

**Returns** — The created migration state  T4726

## updateMigrationState(cleoDir, updates)

Update migration state with partial updates.  Merges updates with existing state and writes atomically. Automatically adds timestamp to phase transitions.

**Signature**

```typescript theme={null}
(cleoDir: string, updates: Partial<MigrationState>) => Promise<MigrationState>
```

**Parameters**

| Name      | Type                            | Description                    |
| --------- | ------------------------------- | ------------------------------ |
| `cleoDir` | `string`                        | Path to .cleo directory        |
| `updates` | `Partial&lt;MigrationState&gt;` | Partial state updates to apply |

**Returns** — The updated migration state  T4726

## updateMigrationPhase(cleoDir, phase)

Update just the migration phase. Convenience wrapper for common phase transition.

**Signature**

```typescript theme={null}
(cleoDir: string, phase: MigrationPhase) => Promise<MigrationState>
```

**Parameters**

| Name      | Type             | Description             |
| --------- | ---------------- | ----------------------- |
| `cleoDir` | `string`         | Path to .cleo directory |
| `phase`   | `MigrationPhase` | New phase               |

**Returns** — The updated migration state  T4726

## updateMigrationProgress(cleoDir, progress)

Update progress counters during import.

**Signature**

```typescript theme={null}
(cleoDir: string, progress: Partial<MigrationProgress>) => Promise<MigrationState>
```

**Parameters**

| Name       | Type                               | Description                                     |
| ---------- | ---------------------------------- | ----------------------------------------------- |
| `cleoDir`  | `string`                           | Path to .cleo directory                         |
| `progress` | `Partial&lt;MigrationProgress&gt;` | Progress updates (only changed counters needed) |

**Returns** — The updated migration state  T4726

## addMigrationError(cleoDir, error)

Add an error to the migration state.

**Signature**

```typescript theme={null}
(cleoDir: string, error: string) => Promise<MigrationState>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |
| `error`   | `string` | Error message           |

**Returns** — The updated migration state  T4726

## addMigrationWarning(cleoDir, warning)

Add a warning to the migration state.

**Signature**

```typescript theme={null}
(cleoDir: string, warning: string) => Promise<MigrationState>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |
| `warning` | `string` | Warning message         |

**Returns** — The updated migration state  T4726

## loadMigrationState(cleoDir)

Load existing migration state.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<MigrationState | null>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |

**Returns** — Migration state, or null if no state file exists  T4726

## isMigrationInProgress(cleoDir)

Check if a migration is in progress.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<boolean>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |

**Returns** — true if migration state exists and is not complete/failed  T4726

## canResumeMigration(cleoDir)

Check if migration can be resumed.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<{ canResume: boolean; phase: MigrationPhase; progress: MigrationProgress; errors: string[]; } | null>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |

**Returns** — Object with resume info, or null if cannot resume  T4726

## completeMigration(cleoDir)

Mark migration as complete.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<MigrationState>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |

**Returns** — The completed migration state  T4726

## failMigration(cleoDir, error)

Mark migration as failed with error details.

**Signature**

```typescript theme={null}
(cleoDir: string, error: string) => Promise<MigrationState>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |
| `error`   | `string` | Primary error message   |

**Returns** — The failed migration state  T4726

## clearMigrationState(cleoDir)

Clear migration state file. Safe to call even if state doesn't exist.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<void>
```

**Parameters**

| Name      | Type     | Description                    |
| --------- | -------- | ------------------------------ |
| `cleoDir` | `string` | Path to .cleo directory  T4726 |

## getMigrationSummary(cleoDir)

Get a summary of migration state for display.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<string | null>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |

**Returns** — Human-readable summary, or null if no state  T4726

## verifySourceIntegrity(cleoDir)

Verify source files haven't changed since migration started.  Compares current checksums with stored checksums to detect if source files were modified during migration.

**Signature**

```typescript theme={null}
(cleoDir: string) => Promise<{ valid: boolean; changed: string[]; missing: string[]; }>
```

**Parameters**

| Name      | Type     | Description             |
| --------- | -------- | ----------------------- |
| `cleoDir` | `string` | Path to .cleo directory |

**Returns** — Object with verification results  T4726

## validateSourceFiles(cleoDir)

Validate all JSON source files before migration.  This function MUST be called BEFORE any destructive database operations. It checks that all JSON files are parseable and contain expected data.

**Signature**

```typescript theme={null}
(cleoDir: string) => JsonValidationResult
```

**Parameters**

| Name      | Type     | Description                 |
| --------- | -------- | --------------------------- |
| `cleoDir` | `string` | Path to the .cleo directory |

**Returns** — Validation result with details for each file  T4725

## formatValidationResult(result)

Format validation result for human-readable output.

**Signature**

```typescript theme={null}
(result: JsonValidationResult) => string
```

**Parameters**

| Name     | Type                   | Description       |
| -------- | ---------------------- | ----------------- |
| `result` | `JsonValidationResult` | Validation result |

**Returns** — Formatted string

## checkTaskCountMismatch(cleoDir, jsonTaskCount)

Check for task count mismatch between existing database and JSON.  This helps detect cases where the database has data but JSON is empty (indicating a potential configuration or path issue).

**Signature**

```typescript theme={null}
(cleoDir: string, jsonTaskCount: number) => string | null
```

**Parameters**

| Name            | Type     | Description                   |
| --------------- | -------- | ----------------------------- |
| `cleoDir`       | `string` | Path to .cleo directory       |
| `jsonTaskCount` | `number` | Number of tasks found in JSON |

**Returns** — Warning message if mismatch detected, null otherwise

## detectVersion()

Detect schema version from a data file.  T4468

**Signature**

```typescript theme={null}
(data: unknown) => string
```

## compareSemver()

Compare two version strings (X.Y.Z format, works for both semver and CalVer). Returns -1 if a  b, 0 if equal, 1 if a  b.  T4468

**Signature**

```typescript theme={null}
(a: string, b: string) => number
```

## getMigrationStatus()

Get migration status for all data files.  T4468

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<MigrationStatus>
```

## runMigration()

Run migrations on a data file.  T4468

**Signature**

```typescript theme={null}
(fileType: string, options?: { dryRun?: boolean | undefined; }, cwd?: string | undefined) => Promise<MigrationResult>
```

## runAllMigrations()

Run all pending migrations.  T4468

**Signature**

```typescript theme={null}
(options?: { dryRun?: boolean | undefined; }, cwd?: string | undefined) => Promise<MigrationResult[]>
```

## invalidateGraphCache()

Invalidate the in-memory graph cache.

**Signature**

```typescript theme={null}
() => void
```

## buildGlobalGraph()

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

**Signature**

```typescript theme={null}
() => Promise<NexusGlobalGraph>
```

## nexusDeps()

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

**Signature**

```typescript theme={null}
(taskQuery: string, direction?: "forward" | "reverse") => Promise<DepsResult>
```

## resolveCrossDeps()

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

**Signature**

```typescript theme={null}
(depsArray: string[], sourceProject: string) => Promise<DepsEntry[]>
```

## criticalPath()

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

**Signature**

```typescript theme={null}
() => Promise<CriticalPathResult>
```

## blockingAnalysis()

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

**Signature**

```typescript theme={null}
(taskQuery: string) => Promise<BlockingAnalysisResult>
```

## orphanDetection()

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

**Signature**

```typescript theme={null}
() => Promise<OrphanEntry[]>
```

## compareLevels()

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

**Signature**

```typescript theme={null}
(a: PinoLevel, b: PinoLevel) => number
```

## matchesFilter()

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

**Signature**

```typescript theme={null}
(entry: PinoLogEntry, filter: LogFilter) => boolean
```

## filterEntries()

Filter an array of parsed log entries against criteria. Returns entries matching ALL specified criteria (AND logic). Does not apply pagination (limit/offset) -- use paginate() for that.

**Signature**

```typescript theme={null}
(entries: PinoLogEntry[], filter: LogFilter) => PinoLogEntry[]
```

## paginate()

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

**Signature**

```typescript theme={null}
(entries: PinoLogEntry[], limit?: number | undefined, offset?: number | undefined) => PinoLogEntry[]
```

## isValidLevel()

Validate that a string is a valid PinoLevel.

**Signature**

```typescript theme={null}
(level: string) => level is PinoLevel
```

## parseLogLine()

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

**Signature**

```typescript theme={null}
(line: string) => PinoLogEntry | null
```

## parseLogLines()

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

**Signature**

```typescript theme={null}
(lines: string[]) => PinoLogEntry[]
```

## getProjectLogDir()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string | null
```

## getGlobalLogDir()

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

**Signature**

```typescript theme={null}
() => string
```

## discoverLogFiles()

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

**Signature**

```typescript theme={null}
(options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => LogFileInfo[]
```

## readLogFileLines()

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

**Signature**

```typescript theme={null}
(filePath: string) => string[]
```

## streamLogFileLines()

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

**Signature**

```typescript theme={null}
(filePath: string) => AsyncGenerator<string, any, any>
```

## queryLogs()

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

**Signature**

```typescript theme={null}
(filter?: LogFilter | undefined, options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => LogQueryResult
```

## streamLogs()

Stream-based query for large log datasets. Yields matching entries one at a time. Respects limit. Does not support offset (streaming is forward-only).

**Signature**

```typescript theme={null}
(filter?: LogFilter | undefined, options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => AsyncGenerator<PinoLogEntry, any, any>
```

## getLogSummary()

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

**Signature**

```typescript theme={null}
(options?: LogDiscoveryOptions | undefined, cwd?: string | undefined) => LogSummary
```

## getOtelStatus()

Get token tracking status.

**Signature**

```typescript theme={null}
() => Promise<Record<string, unknown>>
```

## getOtelSummary()

Get combined token usage summary.

**Signature**

```typescript theme={null}
() => Promise<Record<string, unknown>>
```

## getOtelSessions()

Get session-level token data.

**Signature**

```typescript theme={null}
(opts: { session?: string | undefined; task?: string | undefined; }) => Promise<Record<string, unknown>>
```

## getOtelSpawns()

Get spawn-level token data.

**Signature**

```typescript theme={null}
(opts: { task?: string | undefined; epic?: string | undefined; }) => Promise<Record<string, unknown>>
```

## getRealTokenUsage()

Get real token usage from Claude Code API.

**Signature**

```typescript theme={null}
(_opts: { session?: string | undefined; since?: string | undefined; }) => Promise<Record<string, unknown>>
```

## clearOtelData()

Clear token tracking data with backup.

**Signature**

```typescript theme={null}
() => Promise<Record<string, unknown>>
```

## listPhases()

List all phases with status summaries.  T5326

**Signature**

```typescript theme={null}
(projectRoot: string, accessor?: DataAccessor | undefined) => Promise<{ success: boolean; data?: ListPhasesResult | undefined; error?: { code: string; message: string; } | undefined; }>
```

## showPhase()

Show phase details by slug or current phase.  T5326

**Signature**

```typescript theme={null}
(projectRoot: string, phaseId?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ success: boolean; data?: ShowPhaseResult | undefined; error?: { ...; } | undefined; }>
```

## getCurrentBranch()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<string>
```

## addRemote()

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

**Signature**

```typescript theme={null}
(url: string, name?: string, cwd?: string | undefined) => Promise<void>
```

## removeRemote()

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

**Signature**

```typescript theme={null}
(name?: string, cwd?: string | undefined) => Promise<void>
```

## listRemotes()

List configured remotes in .cleo/.git.  T4884

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<RemoteInfo[]>
```

## push()

Push .cleo/.git to a remote.  T4884

**Signature**

```typescript theme={null}
(remote?: string, options?: { force?: boolean | undefined; setUpstream?: boolean | undefined; } | undefined, cwd?: string | undefined) => Promise<PushResult>
```

## pull()

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

**Signature**

```typescript theme={null}
(remote?: string, cwd?: string | undefined) => Promise<PullResult>
```

## getSyncStatus()

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

**Signature**

```typescript theme={null}
(remote?: string, cwd?: string | undefined) => Promise<{ ahead: number; behind: number; branch: string; remote: string; }>
```

## getRoadmap()

Get roadmap from pending epics and CHANGELOG history.

**Signature**

```typescript theme={null}
(opts: { includeHistory?: boolean | undefined; upcomingOnly?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## getOperationMode()

Lookup the execution mode for a specific operation

**Signature**

```typescript theme={null}
(domain: string, operation: string, gateway: GatewayType) => ExecutionMode | undefined
```

## canRunNatively()

Check if an operation can run natively (without CLI)

**Signature**

```typescript theme={null}
(domain: string, operation: string, gateway: GatewayType) => boolean
```

## requiresCLI()

Check if an operation requires CLI

**Signature**

```typescript theme={null}
(domain: string, operation: string, gateway: GatewayType) => boolean
```

## getNativeOperations()

Get all native-capable operations for a domain

**Signature**

```typescript theme={null}
(domain: string) => OperationCapability[]
```

## generateCapabilityReport()

Generate a capability report for system.doctor

**Signature**

```typescript theme={null}
() => CapabilityReport
```

## getCapabilityMatrix()

Get the full capability matrix (for testing/introspection)

**Signature**

```typescript theme={null}
() => readonly OperationCapability[]
```

## findHighestId()

Find the highest existing task ID number

**Signature**

```typescript theme={null}
(existingIds: Set<string>) => number
```

## generateNextIdFromSet()

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

**Signature**

```typescript theme={null}
(existingIds: Set<string>) => string
```

## isValidTaskId()

Validate that a task ID matches the expected format

**Signature**

```typescript theme={null}
(id: string) => boolean
```

## normalizeTaskId()

Normalize a task ID input to canonical T#### format.  Accepts various loose formats (lowercase prefix, bare digits, underscore-suffixed descriptors) and returns the canonical form, or null if the input cannot be parsed as a task ID.

**Signature**

```typescript theme={null}
(input: unknown) => string | null
```

## SecurityError

Security validation error thrown when input fails sanitization

**Signature**

```typescript theme={null}
typeof SecurityError
```

## sanitizeTaskId()

Sanitize and validate a task ID

**Signature**

```typescript theme={null}
(value: unknown) => string
```

## sanitizePath()

Sanitize and validate a file path

**Signature**

```typescript theme={null}
(path: string, projectRoot: string) => string
```

## sanitizeContent()

Sanitize content string

**Signature**

```typescript theme={null}
(content: string, maxLength?: number) => string
```

## validateEnum()

Validate that a value is in an allowed enum set

**Signature**

```typescript theme={null}
(value: string, allowed: string[], fieldName: string) => string
```

## RateLimiter

In-memory sliding window rate limiter

**Signature**

```typescript theme={null}
typeof RateLimiter
```

**Methods**

### check()

```typescript theme={null}
(key: string) => RateLimitResult
```

### record()

```typescript theme={null}
(key: string) => void
```

### consume()

```typescript theme={null}
(key: string) => RateLimitResult
```

### reset()

```typescript theme={null}
(key?: string | undefined) => void
```

### getConfig()

```typescript theme={null}
(key: string) => RateLimitConfig | undefined
```

### setConfig()

```typescript theme={null}
(key: string, config: RateLimitConfig) => void
```

## ensureArray()

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

**Signature**

```typescript theme={null}
(value: unknown, separator?: string) => string[] | undefined
```

## sanitizeParams()

Sanitize all params in a request before routing

**Signature**

```typescript theme={null}
(params: Record<string, unknown> | undefined, projectRoot?: string | undefined, context?: { domain?: string | undefined; operation?: string | undefined; } | undefined) => Record<...> | undefined
```

## ClaudeCodeTransport

Claude Code transport — wraps the current provider-specific messaging.  Registration and deregistration are no-ops because the Claude Code Agent SDK manages agent identity internally. Message sending is logged but actual delivery happens through the SDK's SendMessage tool at the agent level.

**Signature**

```typescript theme={null}
typeof ClaudeCodeTransport
```

**Methods**

### register()

```typescript theme={null}
(name: string, agentClass: AgentClass, privacyTier: PrivacyTier) => Promise<AgentRegistration>
```

### deregister()

```typescript theme={null}
(agentId: string) => Promise<void>
```

### send()

```typescript theme={null}
(fromAgentId: string, toAgentId: string, content: string, conversationId?: string | undefined) => Promise<MessageResult>
```

### poll()

```typescript theme={null}
(agentId: string, since?: string | undefined) => Promise<Message[]>
```

### heartbeat()

```typescript theme={null}
(agentId: string) => Promise<void>
```

### createConversation()

```typescript theme={null}
(participants: string[], visibility?: ConversationVisibility | undefined) => Promise<Conversation>
```

### getAgent()

```typescript theme={null}
(agentId: string) => Promise<Agent | null>
```

## SignalDockTransport

SignalDock HTTP transport implementation.  Communicates with a SignalDock server via its REST API to provide provider-neutral inter-agent messaging with delivery guarantees.

**Signature**

```typescript theme={null}
typeof SignalDockTransport
```

**Methods**

### register()

```typescript theme={null}
(name: string, agentClass: AgentClass, privacyTier: PrivacyTier) => Promise<AgentRegistration>
```

### deregister()

```typescript theme={null}
(agentId: string) => Promise<void>
```

### send()

```typescript theme={null}
(fromAgentId: string, toAgentId: string, content: string, conversationId?: string | undefined) => Promise<MessageResult>
```

### poll()

```typescript theme={null}
(agentId: string, _since?: string | undefined) => Promise<Message[]>
```

### heartbeat()

```typescript theme={null}
(agentId: string) => Promise<void>
```

### createConversation()

```typescript theme={null}
(participants: string[], visibility?: ConversationVisibility) => Promise<Conversation>
```

### getAgent()

```typescript theme={null}
(agentId: string) => Promise<Agent | null>
```

### request()

Make an HTTP request to the SignalDock API.

```typescript theme={null}
<T>(method: string, path: string, body?: unknown, agentId?: string | undefined) => Promise<T>
```

## createTransport()

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

**Signature**

```typescript theme={null}
(config?: TransportFactoryConfig | undefined) => AgentTransport
```

## getSkillSearchPaths()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => SkillSearchPath[]
```

## getSkillsDir()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## getSharedDir()

Get the shared skills resources directory.  T4516

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## mapSkillName()

Map a user-friendly skill name to the canonical ct-prefixed directory name. Supports: UPPER-CASE, lower-case, with/without ct- prefix.  T4516

**Signature**

```typescript theme={null}
(input: string) => { canonical: string; mapped: boolean; }
```

## listCanonicalSkillNames()

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

**Signature**

```typescript theme={null}
() => string[]
```

## parseFrontmatter()

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

**Signature**

```typescript theme={null}
(content: string) => SkillFrontmatter
```

## discoverSkill()

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

**Signature**

```typescript theme={null}
(skillDir: string) => Skill | null
```

## discoverSkillsInDir()

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

**Signature**

```typescript theme={null}
(dir: string) => Skill[]
```

## discoverAllSkills()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Skill[]
```

## findSkill()

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

**Signature**

```typescript theme={null}
(name: string, cwd?: string | undefined) => Skill | null
```

## toSkillSummary()

Convert a Skill to a lightweight SkillSummary.  T4516

**Signature**

```typescript theme={null}
(skill: Skill) => SkillSummary
```

## generateManifest()

Generate a skill manifest from discovered skills.  T4516

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => SkillManifest
```

## resolveTemplatePath()

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

**Signature**

```typescript theme={null}
(name: string, cwd?: string | undefined) => string | null
```

## getAgentsDir()

Get the agents directory path.  T4518

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## parseAgentConfig()

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

**Signature**

```typescript theme={null}
(agentDir: string) => AgentConfig | null
```

## loadAgentConfig()

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

**Signature**

```typescript theme={null}
(agentName: string, cwd?: string | undefined) => AgentConfig | null
```

## getSubagentConfig()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => AgentConfig | null
```

## agentExists()

Check if an agent definition exists.  T4518

**Signature**

```typescript theme={null}
(agentName: string, cwd?: string | undefined) => boolean
```

## installAgent()

Install a single agent via symlink.  T4518

**Signature**

```typescript theme={null}
(agentDir: string) => { installed: boolean; path: string; error?: string | undefined; }
```

## installAllAgents()

Install all agents from the project agents/ directory.  T4518

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { name: string; installed: boolean; error?: string | undefined; }[]
```

## uninstallAgent()

Uninstall a single agent by removing its symlink.  T4518

**Signature**

```typescript theme={null}
(agentName: string) => boolean
```

## getRegistryPath()

Get the agent registry file path.  T4518

**Signature**

```typescript theme={null}
() => string
```

## readRegistry()

Read the agent registry, creating if needed.  T4518

**Signature**

```typescript theme={null}
() => AgentRegistry
```

## saveRegistry()

Save the agent registry.  T4518

**Signature**

```typescript theme={null}
(registry: AgentRegistry) => void
```

## registerAgent()

Register an agent in the registry.  T4518

**Signature**

```typescript theme={null}
(name: string, path: string, config: AgentConfig) => AgentRegistryEntry
```

## unregisterAgent()

Unregister an agent from the registry.  T4518

**Signature**

```typescript theme={null}
(name: string) => boolean
```

## getAgent()

Get an agent from the registry by name.  T4518

**Signature**

```typescript theme={null}
(name: string) => AgentRegistryEntry | null
```

## listAgents()

List all registered agents.  T4518

**Signature**

```typescript theme={null}
() => AgentRegistryEntry[]
```

## syncRegistry()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { added: string[]; removed: string[]; unchanged: string[]; }
```

## loadPlaceholders()

Load token definitions from placeholders.json.  T4521

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => PlaceholdersConfig | null
```

## buildDefaults()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => TokenValues
```

## validateTokenValue()

Validate a single token value against its pattern.  T4521

**Signature**

```typescript theme={null}
(token: string, value: string) => { valid: boolean; error?: string | undefined; }
```

## validateRequired()

Validate all required tokens are present and valid.  T4521

**Signature**

```typescript theme={null}
(values: TokenValues) => { valid: boolean; missing: string[]; invalid: { token: string; error: string; }[]; }
```

## validateAllTokens()

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

**Signature**

```typescript theme={null}
(values: TokenValues) => { valid: boolean; errors: { token: string; error: string; }[]; }
```

## injectTokens()

Inject token values into a template string. Replaces all TOKEN\_NAME patterns with corresponding values. Unresolved tokens are left as-is (for debugging).  T4521

**Signature**

```typescript theme={null}
(template: string, values: TokenValues) => string
```

## hasUnresolvedTokens()

Check if a template has unresolved tokens after injection.  T4521

**Signature**

```typescript theme={null}
(content: string) => string[]
```

## loadAndInject()

Load a skill template and inject tokens.  T4521

**Signature**

```typescript theme={null}
(templatePath: string, values: TokenValues) => { content: string; unresolvedTokens: string[]; }
```

## setFullContext()

Build a complete TokenValues map from a task, resolving all standard tokens. Ports ti\_set\_full\_context from lib/skills/token-inject.sh.  This is the primary entry point for orchestrators to prepare token values before spawning subagents. It populates: TASK\_ID, DATE, TOPIC\_SLUG, EPIC\_ID, TITLE, TASK\_TITLE, TASK\_DESCRIPTION, TOPICS\_JSON, DEPENDS\_LIST, RESEARCH\_ID, OUTPUT\_DIR, MANIFEST\_PATH, and all command defaults.   T4712  T4663

**Signature**

```typescript theme={null}
(task: { id: string; title: string; description?: string | undefined; parentId?: string | undefined; labels?: string[] | undefined; depends?: string[] | undefined; }, options?: { date?: string | undefined; topicSlug?: string | undefined; outputDir?: string | undefined; manifestPath?: string | undefined; } | undefine...
```

## autoDispatch()

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

**Signature**

```typescript theme={null}
(task: Task, cwd?: string | undefined) => DispatchResult
```

## dispatchExplicit()

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

**Signature**

```typescript theme={null}
(skillName: string, cwd?: string | undefined) => DispatchResult | null
```

## getProtocolForDispatch()

Get the protocol type for a dispatch result.  T4517

**Signature**

```typescript theme={null}
(result: DispatchResult) => SkillProtocolType | null
```

## prepareSpawnContext()

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

**Signature**

```typescript theme={null}
(task: Task, overrideSkill?: string | undefined, cwd?: string | undefined) => { skill: string; protocol: SkillProtocolType | null; dispatch: DispatchResult; }
```

## prepareSpawnMulti()

Compose multiple skills into a single prompt with progressive disclosure. Ports skill\_prepare\_spawn\_multi from lib/skills/skill-dispatch.sh.  The first skill is loaded fully (primary). Secondary skills use progressive disclosure (frontmatter + first section only) to save context budget.   T4712  T4663

**Signature**

```typescript theme={null}
(skillNames: string[], tokenValues: Record<string, string>, cwd?: string | undefined) => MultiSkillComposition
```

## loadProtocolBase()

Load the subagent protocol base content.  T4521

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string | null
```

## buildTaskContext()

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

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => string
```

## filterProtocolByTier()

Filter protocol content by MVI tier. Extracts sections based on !-- TIER:X -- markers. - tier 0: header + minimal only + footer - tier 1: header + minimal + standard + footer - tier 2: header + all tiers + footer (full content)  Header = content before first TIER marker. Footer = content after last /TIER marker.   T5155

**Signature**

```typescript theme={null}
(content: string, tier: 0 | 1 | 2) => string
```

## injectProtocol()

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

**Signature**

```typescript theme={null}
(skillContent: string, taskId: string, tokenValues: TokenValues, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => string
```

## orchestratorSpawnSkill()

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

**Signature**

```typescript theme={null}
(taskId: string, skillName: string, tokenValues: TokenValues, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => string
```

## prepareTokenValues()

Prepare standard token values for a task spawn.  T4521

**Signature**

```typescript theme={null}
(taskId: string, topicSlug: string, epicId?: string | undefined, _cwd?: string | undefined) => TokenValues
```

## installSkill()

Install a single skill via CAAMP.

**Signature**

```typescript theme={null}
(skillName: string, projectDir?: string | undefined) => Promise<{ installed: boolean; path: string; error?: string | undefined; }>
```

## generateContributionId()

Generate a unique contribution ID.  T4520

**Signature**

```typescript theme={null}
(taskId: string) => string
```

## validateContributionTask()

Validate that a task is suitable for contribution protocol.  T4520

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => { valid: boolean; issues: string[]; }
```

## getContributionInjection()

Generate the contribution injection block for a subagent prompt.  T4520

**Signature**

```typescript theme={null}
(taskId: string, protocolPath?: string | undefined, _cwd?: string | undefined) => string
```

## detectConflicts()

Detect conflicts between two sets of decisions.  T4520

**Signature**

```typescript theme={null}
(decisions1: ContributionDecision[], decisions2: ContributionDecision[]) => ContributionConflict[]
```

## computeConsensus()

Compute weighted consensus from multiple agent decisions.  T4520

**Signature**

```typescript theme={null}
(decisions: ContributionDecision[], weights?: Record<string, number> | undefined) => ConsensusResult
```

## createContributionManifestEntry()

Create a manifest entry for a contribution.  T4520

**Signature**

```typescript theme={null}
(taskId: string, contributionId: string, decisions: ContributionDecision[]) => ManifestEntry
```

## ensureOutputs()

Ensure agent outputs directory and manifest file exist.  T4520

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => { created: string[]; }
```

## readManifest()

Read all manifest entries.  T4520

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => ManifestEntry[]
```

## appendManifest()

Append a manifest entry (atomic JSONL append).  T4520

**Signature**

```typescript theme={null}
(entry: ManifestEntry, cwd?: string | undefined) => void
```

## findEntry()

Find a manifest entry by ID.  T4520

**Signature**

```typescript theme={null}
(id: string, cwd?: string | undefined) => ManifestEntry | null
```

## filterEntries()

Filter manifest entries by criteria.  T4520

**Signature**

```typescript theme={null}
(criteria: { status?: string | undefined; agentType?: string | undefined; topic?: string | undefined; linkedTask?: string | undefined; actionable?: boolean | undefined; }, cwd?: string | undefined) => ManifestEntry[]
```

## getPendingFollowup()

Get entries with pending follow-ups.  T4520

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => ManifestEntry[]
```

## getFollowupTaskIds()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string[]
```

## taskHasResearch()

Check if a task has linked research.  T4520

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => { hasResearch: boolean; count: number; }
```

## archiveEntry()

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

**Signature**

```typescript theme={null}
(entryId: string, cwd?: string | undefined) => boolean
```

## rotateManifest()

Rotate manifest by archiving old entries.  T4520

**Signature**

```typescript theme={null}
(maxEntries?: number, cwd?: string | undefined) => number
```

## isCacheFresh()

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

**Signature**

```typescript theme={null}
(cachePath?: string | undefined) => boolean
```

## invalidateCache()

Invalidate the cache (delete the cached manifest).  T4520

**Signature**

```typescript theme={null}
() => void
```

## resolveManifest()

Resolve the skills manifest. Returns a cached version if fresh, otherwise generates a new one.  Graceful degradation:   1. Fresh cached manifest (within TTL)   2. Stale cached manifest (expired but valid)   3. Embedded project manifest (skills/manifest.json)   4. Freshly generated manifest   T4520

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => SkillManifest
```

## regenerateCache()

Force regenerate the cache.  T4520

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => SkillManifest
```

## loadConfig()

Load SkillsMP configuration from skillsmp.json.  T4521

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => SkillsMpConfig | null
```

## searchSkills()

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

**Signature**

```typescript theme={null}
(query: string, _config?: SkillsMpConfig | undefined) => Promise<MarketplaceSkill[]>
```

## getSkill()

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

**Signature**

```typescript theme={null}
(skillId: string, _config?: SkillsMpConfig | undefined) => Promise<MarketplaceSkill | null>
```

## isEnabled()

Check if the marketplace is enabled and reachable.  T4521

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => boolean
```

## buildPrompt()

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

**Signature**

```typescript theme={null}
(taskId: string, templateName?: string, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => SpawnPromptResult
```

## spawn()

Generate full spawn command with metadata.  T4519

**Signature**

```typescript theme={null}
(taskId: string, templateName?: string, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => SpawnPromptResult & { spawnTimestamp: string; }
```

## canParallelize()

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

**Signature**

```typescript theme={null}
(taskIds: string[], cwd?: string | undefined) => { canParallelize: boolean; conflicts: (Pick<Task, "id"> & { dependsOn: string[]; })[]; safeToSpawn: string[]; }
```

## spawnBatch()

Spawn prompts for multiple tasks in a batch. Ports orchestrator\_spawn\_batch from lib/skills/orchestrator-spawn.sh.  Iterates over task IDs, building spawn prompts for each. Individual failures are captured per-entry rather than aborting the entire batch.   T4712  T4663

**Signature**

```typescript theme={null}
(taskIds: string[], templateName?: string | undefined, cwd?: string | undefined, tier?: 0 | 1 | 2 | undefined) => BatchSpawnResult
```

## getThresholds()

Get orchestrator context thresholds from config or defaults.  T4519

**Signature**

```typescript theme={null}
(config?: Record<string, unknown> | undefined) => OrchestratorThresholds
```

## getContextState()

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

**Signature**

```typescript theme={null}
(sessionId?: string | undefined, cwd?: string | undefined) => ContextState
```

## sessionInit()

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

**Signature**

```typescript theme={null}
(_epicId?: string | undefined, cwd?: string | undefined) => Promise<SessionInitResult>
```

## shouldPause()

Check if orchestrator should pause based on context usage.  T4519

**Signature**

```typescript theme={null}
(config?: Record<string, unknown> | undefined, sessionId?: string | undefined, cwd?: string | undefined) => PauseStatus
```

## analyzeDependencies()

Analyze dependency graph and compute execution waves.  T4519

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<DependencyAnalysis>
```

## getNextTask()

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

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<{ task: Task | null; readyCount: number; }>
```

## getReadyTasks()

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

**Signature**

```typescript theme={null}
(epicId: string, cwd?: string | undefined) => Promise<TaskRefPriority[]>
```

## generateHitlSummary()

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

**Signature**

```typescript theme={null}
(epicId?: string | undefined, stopReason?: string, cwd?: string | undefined) => Promise<HitlSummary>
```

## validateSubagentOutput()

Validate a subagent's manifest entry for protocol compliance.  T4519

**Signature**

```typescript theme={null}
(researchId: string, cwd?: string | undefined) => { passed: boolean; issues: string[]; checkedRules: string[]; }
```

## validateManifestIntegrity()

Validate the entire manifest file integrity.  T4519

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => ManifestValidationResult
```

## verifyCompliance()

Verify previous agent completed protocol compliance before spawning next.  T4519

**Signature**

```typescript theme={null}
(previousTaskId: string, researchId?: string | undefined, cwd?: string | undefined) => ComplianceResult
```

## validateOrchestratorCompliance()

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

**Signature**

```typescript theme={null}
(epicId?: string | undefined, cwd?: string | undefined) => { compliant: boolean; violations: string[]; warnings: string[]; }
```

## getSkillSearchPaths()

Get ordered skill search paths based on configuration.  Priority: 1. CLEO\_SKILL\_PATH entries (colon-separated, explicit overrides) 2. Source-determined paths based on CLEO\_SKILL\_SOURCE  CLEO\_SKILL\_SOURCE modes: - auto: CAAMP canonical + embedded (default) - caamp: CAAMP canonical only - embedded: Project embedded only   T4552

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => SkillSearchPath[]
```

## resolveSkillPath()

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

**Signature**

```typescript theme={null}
(skillName: string, projectRoot?: string | undefined) => string | null
```

## resolveProtocolPath()

Resolve a protocol .md file.  Search order per base path: 1. base/\_ct-skills-protocols/protocol\_name.md (Strategy B shared dir) 2. PROJECT\_ROOT/src/protocols/protocol\_name.md (legacy embedded fallback)   T4552

**Signature**

```typescript theme={null}
(protocolName: string, projectRoot?: string | undefined) => string | null
```

## resolveSharedPath()

Resolve a shared resource .md file.  Search order per base path: 1. base/\_ct-skills-shared/resource\_name.md (Strategy B shared dir) 2. base/\_shared/resource\_name.md (legacy embedded layout)   T4552

**Signature**

```typescript theme={null}
(resourceName: string, projectRoot?: string | undefined) => string | null
```

## getSkillSourceType()

Classify the source of a skill directory.  Determines where a skill directory lives in the search hierarchy: - "embedded": Within the project's skills/ directory - "caamp": Within the CAAMP canonical directory (\~/.agents/skills) - "project-link": Symlink pointing to project directory - "global-link": Symlink pointing to CAAMP or external location   T4552

**Signature**

```typescript theme={null}
(skillDir: string, projectRoot?: string | undefined) => SkillSourceType | null
```

## formatIsoDate(inputDate)

Format a date string in ISO 8601 format. Converts a YYYY-MM-DD date string to a full ISO 8601 timestamp.

**Signature**

```typescript theme={null}
(inputDate: string) => string
```

**Parameters**

| Name        | Type     | Description                      |
| ----------- | -------- | -------------------------------- |
| `inputDate` | `string` | Date string in YYYY-MM-DD format |

**Returns** — ISO 8601 formatted string (e.g., "2026-02-03T00:00:00Z")

**Throws**

* Error if date format is invalid or missing  T4552

## getCurrentTimestamp()

Get current timestamp in ISO 8601 format. Returns the current UTC time as an ISO 8601 string.

**Signature**

```typescript theme={null}
() => string
```

**Returns** — Current timestamp (e.g., "2026-02-16T14:30:00Z")  T4552

## isValidIsoDate()

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

**Signature**

```typescript theme={null}
(dateStr: string) => boolean
```

## formatDateYMD()

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

**Signature**

```typescript theme={null}
(date: Date) => string
```

## validateSkill()

Validate a skill directory structure and content.  T4517

**Signature**

```typescript theme={null}
(skillDir: string) => SkillValidationResult
```

## validateSkills()

Validate multiple skills at once.  T4517

**Signature**

```typescript theme={null}
(skillDirs: string[]) => SkillValidationResult[]
```

## validateReturnMessage()

Validate a return message against protocol-compliant patterns.  T4517

**Signature**

```typescript theme={null}
(message: string) => { valid: boolean; error?: string | undefined; }
```

## getInstalledVersionAsync()

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

**Signature**

```typescript theme={null}
(name: string) => Promise<string | null>
```

## checkSkillUpdateAsync()

Check if a specific skill needs an update via CAAMP.

**Signature**

```typescript theme={null}
(name: string) => Promise<{ needsUpdate: boolean; currentVersion?: string | undefined; latestVersion?: string | undefined; }>
```

## checkAllSkillUpdatesAsync()

Check all installed skills for available updates via CAAMP.

**Signature**

```typescript theme={null}
() => Promise<{ name: string; installedVersion: string; availableVersion: string; needsUpdate: boolean; }[]>
```

## exportSnapshot()

Export current task state to a snapshot.  T4882

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<Snapshot>
```

## writeSnapshot()

Write a snapshot to a file.  T4882

**Signature**

```typescript theme={null}
(snapshot: Snapshot, outputPath: string) => Promise<void>
```

## readSnapshot()

Read a snapshot from a file.  T4882

**Signature**

```typescript theme={null}
(inputPath: string) => Promise<Snapshot>
```

## getDefaultSnapshotPath()

Generate a default snapshot file path.  T4882

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => string
```

## importSnapshot()

Import a snapshot into the local task database. Uses last-write-wins strategy: if a task exists locally and in the snapshot, the snapshot version wins only if its updatedAt is newer.  T4882

**Signature**

```typescript theme={null}
(snapshot: Snapshot, cwd?: string | undefined) => Promise<ImportResult>
```

## SpawnAdapterRegistry

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

**Signature**

```typescript theme={null}
typeof SpawnAdapterRegistry
```

**Methods**

### register()

Register an adapter with the registry.

```typescript theme={null}
(adapter: CLEOSpawnAdapter) => void
```

### get()

Get an adapter by its unique ID.

```typescript theme={null}
(adapterId: string) => CLEOSpawnAdapter | undefined
```

### getForProvider()

Get the adapter registered for a specific provider.

```typescript theme={null}
(providerId: string) => CLEOSpawnAdapter | undefined
```

### hasAdapterForProvider()

Check if an adapter is registered for a given provider.

```typescript theme={null}
(providerId: string) => boolean
```

### list()

List all registered adapters.

```typescript theme={null}
() => CLEOSpawnAdapter[]
```

### listSpawnCapable()

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

```typescript theme={null}
() => Promise<CLEOSpawnAdapter[]>
```

### canProviderSpawn()

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

```typescript theme={null}
(providerId: string) => Promise<boolean>
```

### clear()

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

```typescript theme={null}
() => void
```

## getProvidersWithSpawnCapability(capability)

Get providers by specific spawn capability  Queries CAAMP for providers that support a specific spawn capability.

**Signature**

```typescript theme={null}
(capability: SpawnCapability) => Provider[]
```

**Parameters**

| Name         | Type              | Description                       |
| ------------ | ----------------- | --------------------------------- |
| `capability` | `SpawnCapability` | The spawn capability to filter by |

**Returns** — Array of providers with the specified capability

## hasParallelSpawnProvider()

Check if any provider supports parallel spawn

**Signature**

```typescript theme={null}
() => boolean
```

**Returns** — True if at least one provider supports parallel spawn

## initializeSpawnAdapters(manifests)

Initialize spawn adapters dynamically from discovered adapter manifests.  Scans all discovered manifests for adapters with `capabilities.supportsSpawn`, dynamically imports their spawn provider, and bridges it into the spawn registry.  Zero hardcoded adapter names — everything derives from manifests.

**Signature**

```typescript theme={null}
(manifests: AdapterManifest[]) => Promise<void>
```

**Parameters**

| Name        | Type                | Description                                                   |
| ----------- | ------------------- | ------------------------------------------------------------- |
| `manifests` | `AdapterManifest[]` | Discovered adapter manifests (from AdapterManager.discover()) |

**Returns** — Promise that resolves when initialization is complete

## initializeDefaultAdapters()

Initialize the registry with default adapters.  Legacy entry point that discovers adapters from the project root and delegates to initializeSpawnAdapters(). Maintains backward compatibility for callers that don't have manifests handy.

**Signature**

```typescript theme={null}
() => Promise<void>
```

**Returns** — Promise that resolves when initialization is complete

## getProjectStats()

Get project statistics.

**Signature**

```typescript theme={null}
(opts: { period?: string | undefined; verbose?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## rankBlockedTask()

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

**Signature**

```typescript theme={null}
(task: Task, allTasks: Task[], focusTask: Task | null) => number
```

## getDashboard()

Get project dashboard data.

**Signature**

```typescript theme={null}
(opts: { compact?: boolean | undefined; period?: number | undefined; showCharts?: boolean | undefined; sections?: string[] | undefined; verbose?: boolean | undefined; quiet?: boolean | undefined; cwd?: string | undefined; blockedTasksLimit?: number | undefined; }, accessor?: DataAccessor | undefined) => Promise<...>
```

## getCompletionHistory()

Get completion history data.

**Signature**

```typescript theme={null}
(opts: { days?: number | undefined; since?: string | undefined; until?: string | undefined; cwd?: string | undefined; }) => Promise<Record<string, unknown>>
```

## filterByDate()

Filter tasks by date range on archivedAt.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[], since?: string | undefined, until?: string | undefined) => AnalyticsTask[]
```

## summaryReport()

Generate summary statistics.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[]) => SummaryReportData
```

## byPhaseReport()

Group tasks by phase with cycle time averages.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[]) => PhaseGroupEntry[]
```

## byLabelReport()

Group tasks by label frequency.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[]) => LabelFrequencyEntry[]
```

## byPriorityReport()

Group tasks by priority with cycle time averages.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[]) => PriorityGroupEntry[]
```

## cycleTimesReport()

Compute cycle time statistics with distribution buckets.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[]) => CycleTimesReportData
```

## trendsReport()

Compute archive trends by day and month.

**Signature**

```typescript theme={null}
(tasks: AnalyticsTask[]) => TrendsReportData
```

## analyzeArchive()

Analyze archived tasks and produce a report.  This is the primary entry point for archive analytics. It loads archive data from the DataAccessor, normalizes task records, applies date filters, and delegates to the appropriate report function.

**Signature**

```typescript theme={null}
(opts: AnalyzeArchiveOptions, accessor?: DataAccessor | undefined) => Promise<ArchiveAnalyticsResult<ArchiveReportType>>
```

## getArchiveStats()

Get archive statistics.

**Signature**

```typescript theme={null}
(opts: { period?: number | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<ArchiveStatsResult>
```

## auditData()

Audit data integrity.

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { scope?: string | undefined; fix?: boolean | undefined; } | undefined) => Promise<AuditResult>
```

## createBackup()

Create a backup of CLEO data files.

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { type?: string | undefined; note?: string | undefined; } | undefined) => BackupResult
```

## restoreBackup()

Restore from a backup.

**Signature**

```typescript theme={null}
(projectRoot: string, params: { backupId: string; force?: boolean | undefined; }) => RestoreResult
```

## cleanupSystem()

Cleanup stale data (sessions, backups, logs).

**Signature**

```typescript theme={null}
(projectRoot: string, params: { target: string; olderThan?: string | undefined; dryRun?: boolean | undefined; }) => Promise<CleanupResult>
```

## writeJsonFileAtomic(filePath, data, indent)

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

**Signature**

```typescript theme={null}
<T>(filePath: string, data: T, indent?: number) => void
```

**Parameters**

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

```typescript theme={null}
<T = unknown>(filePath: string) => T | null
```

**Parameters**

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

```typescript theme={null}
(projectRoot: string, filename: string) => string
```

**Parameters**

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

**Signature**

```typescript theme={null}
() => string
```

## withLock(filePath, transform)

Read and write a JSON file with exclusive locking.  Acquires a cross-process lock, reads current state, applies the transform function, validates, and writes back atomically.

**Signature**

```typescript theme={null}
<T>(filePath: string, transform: (current: T | null) => T) => Promise<T>
```

**Parameters**

| Name        | Type                  | Description                                              |
| ----------- | --------------------- | -------------------------------------------------------- |
| `filePath`  | `string`              | File to lock and modify                                  |
| `transform` | `(current: T \| null` | Function that receives current data and returns new data |

**Returns** — The transformed data

## withFileLock()

Acquire a file lock and execute an operation. Unlike withLock, this doesn't read/write the file - caller manages I/O. The return type R is independent of the file content type.

**Signature**

```typescript theme={null}
<R>(filePath: string, operation: () => R | Promise<R>) => Promise<R>
```

## withMultiLock(filePaths, operation)

Acquire locks on multiple files in correct order. Used for operations that need to modify multiple files atomically (e.g., coordinated updates across task data and config).

**Signature**

```typescript theme={null}
<T>(filePaths: string[], operation: () => T | Promise<T>) => Promise<T>
```

**Parameters**

| 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

**Signature**

```typescript theme={null}
(projectRoot: string) => boolean
```

## listBackups()

List backup files for a given data file

**Signature**

```typescript theme={null}
(filePath: string) => string[]
```

## detectPlatform()

Detect the current platform.

**Signature**

```typescript theme={null}
() => Platform
```

## commandExists()

Check if a command exists on PATH.

**Signature**

```typescript theme={null}
(command: string) => boolean
```

## requireTool()

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

**Signature**

```typescript theme={null}
(tool: string, installHint?: string | undefined) => { available: boolean; error?: string | undefined; }
```

## checkRequiredTools()

Check all required tools.

**Signature**

```typescript theme={null}
(tools: { name: string; installHint?: string | undefined; }[]) => { allAvailable: boolean; missing: string[]; }
```

## getIsoTimestamp()

Get ISO 8601 UTC timestamp.

**Signature**

```typescript theme={null}
() => string
```

## isoToEpoch()

Convert ISO timestamp to epoch seconds.

**Signature**

```typescript theme={null}
(isoTimestamp: string) => number
```

## dateDaysAgo()

Get ISO date for N days ago.

**Signature**

```typescript theme={null}
(days: number) => string
```

## getFileSize()

Get file size in bytes.

**Signature**

```typescript theme={null}
(filePath: string) => number
```

## getFileMtime()

Get file modification time as ISO string.

**Signature**

```typescript theme={null}
(filePath: string) => string | null
```

## generateRandomHex()

Generate N random hex characters.

**Signature**

```typescript theme={null}
(bytes?: number) => string
```

## sha256()

Compute SHA-256 checksum of a string.

**Signature**

```typescript theme={null}
(data: string) => string
```

## createTempFilePath()

Create a temporary file path.

**Signature**

```typescript theme={null}
(prefix?: string, suffix?: string) => string
```

## getNodeVersionInfo()

Get Node.js version info.

**Signature**

```typescript theme={null}
() => { version: string; major: number; minor: number; patch: number; meetsMinimum: boolean; }
```

## getNodeUpgradeInstructions()

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

**Signature**

```typescript theme={null}
() => { platform: Platform; arch: string; instructions: string[]; recommended: string; }
```

## getSystemInfo()

Gather a snapshot of the host system.  This is the SSoT for system information. Use this instead of scattering `process.platform` / `os.type()` calls throughout the codebase.  Use cases:   - Logger base context (every log entry carries platform info)   - Error reports and issue submission   - Doctor diagnostics   - Startup health check results

**Signature**

```typescript theme={null}
() => SystemInfo
```

## checkCliInstallation()

T4525

**Signature**

```typescript theme={null}
(cleoHome?: string) => CheckResult
```

## checkCliVersion()

T4525

**Signature**

```typescript theme={null}
(cleoHome?: string) => CheckResult
```

## checkDocsAccessibility()

T4525

**Signature**

```typescript theme={null}
(cleoHome?: string) => CheckResult
```

## checkAtReferenceResolution()

T4525

**Signature**

```typescript theme={null}
(cleoHome?: string) => CheckResult
```

## checkAgentsMdHub()

Check that AGENTS.md exists in project root and contains the CAAMP:START marker, indicating it serves as the injection hub for CLEO protocol content.

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkRootGitignore()

Check if project root .gitignore is blocking the entire .cleo/ directory. This prevents core CLEO data from being tracked by git.  T4641  T4637

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkCleoGitignore()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkVitalFilesTracked()

Check that vital CLEO configuration files are tracked by git. Only checks config files (config.json, .gitignore, project-info.json, project-context.json). SQLite databases are excluded per ADR-013.  T4700

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkCoreFilesNotIgnored()

Check that core CLEO files are not being ignored by .gitignore. Uses `git check-ignore` to detect files that would be excluded by any gitignore rule (root, .cleo/, or global). Returns critical status if any protected file is gitignored.

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkSqliteNotTracked()

Check that SQLite databases (.cleo/tasks.db) are NOT tracked by project git. Tracked SQLite files cause data loss from merge conflicts (ADR-013). Warns if tasks.db is currently tracked so the user can untrack it.  T5160

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkLegacyAgentOutputs()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkCaampMarkerIntegrity()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkAtReferenceTargetExists()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkTemplateFreshness()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined, cleoHome?: string | undefined) => CheckResult
```

## checkTierMarkersPresent()

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

**Signature**

```typescript theme={null}
(cleoHome?: string | undefined) => CheckResult
```

## checkNodeVersion()

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

**Signature**

```typescript theme={null}
() => CheckResult
```

## checkGlobalSchemaHealth()

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

**Signature**

```typescript theme={null}
(_projectRoot?: string | undefined) => CheckResult
```

## checkNoLocalSchemas()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => CheckResult
```

## checkJsonSchemaIntegrity()

Check that active JSON files (config.json, project-info.json, etc.) are valid against their schemas and have current schema versions.  Maps JsonFileIntegrityResult\[] from checkSchemaIntegrity() into CheckResult\[], then returns a single rolled-up CheckResult for the doctor summary.

**Signature**

```typescript theme={null}
(projectDir: string) => Promise<CheckResult>
```

## runAllGlobalChecks()

Run all global health checks and return results array.  T4525

**Signature**

```typescript theme={null}
(cleoHome?: string | undefined, projectRoot?: string | undefined) => CheckResult[]
```

## calculateHealthStatus()

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

**Signature**

```typescript theme={null}
(checks: CheckResult[]) => number
```

## getSystemHealth()

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

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { detailed?: boolean | undefined; } | undefined) => HealthResult
```

## getSystemDiagnostics()

Run extended diagnostics with fix suggestions.

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { checks?: string[] | undefined; } | undefined) => Promise<DiagnosticsResult>
```

## coreDoctorReport()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<DoctorReport>
```

## runDoctorFixes()

Run auto-fix for failed doctor checks by calling the corresponding ensure\* functions. Returns a list of fix results for each attempted repair.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<FixResult[]>
```

## startupHealthCheck(projectRoot)

Unified startup health check for MCP server and CLI entry points.  This is the single entry point for startup diagnostics. It follows a three-phase approach:  Phase 1: Global scaffold (\~/.cleo/) — always auto-repaired.   The global home is CLEO infrastructure, not project data. It is safe   to create/repair unconditionally on every startup.  Phase 2: Project detection — determines if this is an initialized project.   Uses isProjectInitialized() from paths.ts as the SSoT for detection.  Phase 3: Project health — lightweight checks on the project scaffold.   If the project is initialized, runs check\* functions to detect drift.   Auto-repairs safe items (missing subdirs via ensureCleoStructure).   Flags items requiring full upgrade (missing DB, config issues).  Design principles:   - SSoT: All checks delegate to scaffold.ts check\* functions   - DRY: No duplicated health-check logic   - SRP: This function only diagnoses and does safe auto-repair   - Graceful: Never throws. All errors are captured as check results.   - Logged: Returns structured results for the caller to log via pino

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<StartupHealthResult>
```

**Parameters**

| Name          | Type                    | Description                                         |
| ------------- | ----------------------- | --------------------------------------------------- |
| `projectRoot` | `: string \| undefined` | Absolute path to the project root (defaults to cwd) |

## generateInjection()

Generate Minimum Viable Injection (MVI) markdown.

**Signature**

```typescript theme={null}
(projectRoot: string, accessor?: DataAccessor | undefined) => Promise<InjectGenerateResult>
```

## getLabels()

Get all labels with counts and task IDs per label.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<LabelsResult>
```

## getSystemMetrics()

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

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { scope?: string | undefined; since?: string | undefined; } | undefined, accessor?: DataAccessor | undefined) => Promise<SystemMetricsResult>
```

## getMigrationStatus()

Check/report schema migration status.

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { target?: string | undefined; dryRun?: boolean | undefined; } | undefined) => Promise<MigrateResult>
```

## getRuntimeDiagnostics()

**Signature**

```typescript theme={null}
(options?: { detailed?: boolean | undefined; } | undefined) => Promise<RuntimeDiagnostics>
```

## safestop()

Safe stop: signal clean shutdown for agents.

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { reason?: string | undefined; commit?: boolean | undefined; handoff?: string | undefined; noSessionEnd?: boolean | undefined; dryRun?: boolean | undefined; } | undefined) => SafestopResult
```

## uncancelTask()

Uncancel a cancelled task (restore to pending).

**Signature**

```typescript theme={null}
(projectRoot: string, params: { taskId: string; cascade?: boolean | undefined; notes?: string | undefined; dryRun?: boolean | undefined; }) => Promise<UncancelResult>
```

## detectCircularDeps()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## wouldCreateCycle()

Check if adding a dependency would create a cycle.

**Signature**

```typescript theme={null}
(fromId: string, toId: string, tasks: Task[]) => boolean
```

## getBlockedTasks()

Get tasks that are blocked (have unmet dependencies).

**Signature**

```typescript theme={null}
(tasks: Task[]) => Task[]
```

## getReadyTasks()

Get tasks that are ready (all dependencies met).

**Signature**

```typescript theme={null}
(tasks: Task[]) => Task[]
```

## getDependents()

Get tasks that depend on a given task.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => Task[]
```

## getDependentIds()

Get dependent IDs.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## getUnresolvedDeps()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## validateDependencyRefs()

Validate dependencies for missing references.

**Signature**

```typescript theme={null}
(tasks: Task[]) => DependencyError[]
```

## validateDependencies()

Full dependency graph validation.

**Signature**

```typescript theme={null}
(tasks: Task[]) => DependencyCheckResult
```

## topologicalSort()

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

**Signature**

```typescript theme={null}
(tasks: Task[]) => string[] | null
```

## getTransitiveBlockers()

Walk upstream recursively through a task's dependency chain. Returns all non-done/non-cancelled dependency IDs (deduplicated). Uses a visited set for cycle protection.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## getLeafBlockers()

From the transitive blockers, return only "leaf" blockers — those whose own dependencies are all resolved (done/cancelled) or that have no dependencies at all. These are the root-cause tasks that need action first.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

## currentTask()

Show current task work state.  T4462  T4750

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskCurrentResult>
```

## startTask()

Start working on a specific task.  T4462  T4750

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskStartResult>
```

## stopTask()

Stop working on the current task.  T4462  T4750

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ previousTask: string | null; }>
```

## getWorkHistory()

Get task work history from session notes.  T4462  T4750

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<TaskWorkHistoryEntry[]>
```

## parseIssueTemplates()

Parse all templates from the repo's .github/ISSUE\_TEMPLATE/ directory.  Reads YAML files directly (live parse, no caching). Excludes config.yml which is the GitHub template chooser config.

**Signature**

```typescript theme={null}
(projectRoot: string) => TemplateResult<TemplateConfig>
```

## getTemplateForSubcommand()

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

**Signature**

```typescript theme={null}
(projectRoot: string, subcommand: string) => TemplateResult<IssueTemplate>
```

## generateTemplateConfig()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<TemplateResult<TemplateConfig>>
```

## validateLabels()

Validate that labels exist on a GitHub repo.  Compares the template labels against a list of known repo labels. Returns which labels exist and which are missing.

**Signature**

```typescript theme={null}
(labels: string[], repoLabels: string[]) => TemplateResult<{ existing: string[]; missing: string[]; }>
```

## getCurrentShell()

Detect the current shell.

**Signature**

```typescript theme={null}
() => ShellType
```

## getRcFilePath()

Get the RC file path for a shell.

**Signature**

```typescript theme={null}
(shell?: ShellType | undefined) => string
```

## detectAvailableShells()

Detect which shells are available on the system.

**Signature**

```typescript theme={null}
() => ShellType[]
```

## generateBashAliases()

Generate bash/zsh alias content.

**Signature**

```typescript theme={null}
(cleoPath?: string | undefined) => string
```

## generatePowershellAliases()

Generate PowerShell alias content.

**Signature**

```typescript theme={null}
(cleoPath?: string | undefined) => string
```

## hasAliasBlock()

Check if aliases are already injected in a file.

**Signature**

```typescript theme={null}
(filePath: string) => boolean
```

## getInstalledVersion()

Get the installed alias version from an RC file.

**Signature**

```typescript theme={null}
(filePath: string) => string | null
```

## injectAliases()

Inject aliases into a shell RC file.

**Signature**

```typescript theme={null}
(filePath: string, shell?: ShellType, cleoPath?: string | undefined) => { action: "created" | "updated" | "added"; version: string; }
```

## removeAliases()

Remove aliases from a shell RC file.

**Signature**

```typescript theme={null}
(filePath: string) => boolean
```

## checkAliasesStatus()

Get alias status for the current shell.

**Signature**

```typescript theme={null}
(shell?: ShellType | undefined) => { shell: ShellType; rcFile: string; installed: boolean; version: string | null; needsUpdate: boolean; }
```

## discoverReleaseTasks()

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

**Signature**

```typescript theme={null}
(options?: { since?: string | undefined; until?: string | undefined; taskIds?: string[] | undefined; }, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<...>
```

## groupTasksIntoSections()

Group tasks into changelog sections.

**Signature**

```typescript theme={null}
(tasks: ChangelogTask[]) => ChangelogSection[]
```

## generateChangelogMarkdown()

Generate changelog markdown for a version.

**Signature**

```typescript theme={null}
(version: string, date: string, sections: ChangelogSection[]) => string
```

## formatChangelogJson()

Format changelog data as JSON.

**Signature**

```typescript theme={null}
(version: string, date: string, sections: ChangelogSection[]) => Record<string, unknown>
```

## writeChangelogFile()

Write changelog content to a file.

**Signature**

```typescript theme={null}
(filePath: string, content: string) => void
```

## appendToChangelog()

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

**Signature**

```typescript theme={null}
(filePath: string, newContent: string) => void
```

## generateChangelog()

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

**Signature**

```typescript theme={null}
(version: string, options?: { since?: string | undefined; until?: string | undefined; taskIds?: string[] | undefined; outputPath?: string | undefined; append?: boolean | undefined; }, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<...>
```

## parseCommandHeader()

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

**Signature**

```typescript theme={null}
(scriptPath: string) => CommandMeta | null
```

## scanAllCommands()

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

**Signature**

```typescript theme={null}
(scriptsDir: string) => Map<string, CommandMeta>
```

## validateHeader()

Validate a command header has required fields.

**Signature**

```typescript theme={null}
(meta: CommandMeta) => { valid: boolean; errors: string[]; }
```

## getCommandScriptMap()

Get command-to-script mapping.

**Signature**

```typescript theme={null}
(scriptsDir: string) => Record<string, string>
```

## getCommandsByCategory()

Group commands by category.

**Signature**

```typescript theme={null}
(scriptsDir: string) => Record<string, CommandMeta[]>
```

## getCommandsByRelevance()

Filter commands by relevance level.

**Signature**

```typescript theme={null}
(scriptsDir: string, relevance: string) => CommandMeta[]
```

## defaultFlags()

Default flag values.

**Signature**

```typescript theme={null}
() => ParsedFlags
```

## parseCommonFlags()

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

**Signature**

```typescript theme={null}
(args: string[]) => ParsedFlags
```

## resolveFormat()

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

**Signature**

```typescript theme={null}
(flagFormat: string) => "json" | "human"
```

## isJsonOutput()

Check if output should be JSON.

**Signature**

```typescript theme={null}
(flags: ParsedFlags) => boolean
```

## getValidationKey()

Get the validation key for a target filename.

**Signature**

```typescript theme={null}
(target: string) => string
```

## extractMarkerVersion()

Extract the CLEO version from an injection marker string. Returns null if no version is present (current format). Returns the version string for legacy format.

**Signature**

```typescript theme={null}
(markerLine: string) => string | null
```

## checkManifestEntry()

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

**Signature**

```typescript theme={null}
(entry: ManifestEntry | null) => ManifestIntegrity
```

## checkReturnFormat()

Check if a response matches the expected return format.  T4524

**Signature**

```typescript theme={null}
(response: string) => boolean
```

## scoreSubagentCompliance()

Calculate comprehensive compliance score for a subagent.  T4524

**Signature**

```typescript theme={null}
(taskId: string, agentId: string, manifestEntry: ManifestEntry | null, researchLinked: boolean, response: string) => ComplianceMetrics
```

## calculateTokenEfficiency()

Calculate token efficiency metrics.  T4524

**Signature**

```typescript theme={null}
(tokensUsed: number, maxTokens?: number, tasksCompleted?: number, inputTokens?: number, outputTokens?: number) => TokenEfficiency
```

## calculateOrchestrationOverhead()

Calculate orchestration overhead metrics.  T4524

**Signature**

```typescript theme={null}
(orchestratorTokens: number, totalSubagentTokens: number, numSubagents?: number) => OrchestrationOverhead
```

## getScriptCommands()

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

**Signature**

```typescript theme={null}
(scriptsDir: string) => string[]
```

## getIndexScripts()

Get script names from COMMANDS-INDEX.json.  T4527

**Signature**

```typescript theme={null}
(indexPath: string) => string[]
```

## getIndexCommands()

Get command names from COMMANDS-INDEX.json.  T4527

**Signature**

```typescript theme={null}
(indexPath: string) => string[]
```

## checkCommandsSync()

Check commands index vs scripts directory for sync.  T4527

**Signature**

```typescript theme={null}
(scriptsDir: string, indexPath: string) => DriftIssue[]
```

## checkWrapperSync()

Check wrapper template sync with COMMANDS-INDEX.  T4527

**Signature**

```typescript theme={null}
(wrapperPath: string, indexPath: string) => DriftIssue[]
```

## detectDrift()

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

**Signature**

```typescript theme={null}
(mode?: "full" | "quick", projectRoot?: string) => DriftReport
```

## shouldRunDriftDetection()

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

**Signature**

```typescript theme={null}
(enabled?: boolean, autoCheck?: boolean, command?: string | undefined, criticalCommands?: string[]) => boolean
```

## getCacheFilePath()

Get cache file path.  T4525

**Signature**

```typescript theme={null}
(cleoHome?: string | undefined) => string
```

## initCacheFile()

Initialize empty cache file.  T4525

**Signature**

```typescript theme={null}
(cacheFile: string) => DoctorProjectCache
```

## loadCache()

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

**Signature**

```typescript theme={null}
(cacheFile: string) => DoctorProjectCache | null
```

## getFileHash()

Get file hash for cache invalidation.  T4525

**Signature**

```typescript theme={null}
(filePath: string) => string
```

## getCachedValidation()

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

**Signature**

```typescript theme={null}
(projectHash: string, projectPath: string, cacheFile?: string | undefined) => ProjectCacheEntry | null
```

## cacheValidationResult()

Cache project validation results.  T4525

**Signature**

```typescript theme={null}
(projectHash: string, projectPath: string, validationStatus: "warning" | "failed" | "passed", issues?: string[], schemaVersions?: SchemaVersions, cacheFile?: string | undefined) => void
```

## clearProjectCache()

Clear cache for a specific project.  T4525

**Signature**

```typescript theme={null}
(projectHash: string, cacheFile?: string | undefined) => void
```

## clearEntireCache()

Clear entire cache.  T4525

**Signature**

```typescript theme={null}
(cacheFile?: string | undefined) => void
```

## isTempProject()

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

**Signature**

```typescript theme={null}
(path: string) => boolean
```

## categorizeProjects()

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

**Signature**

```typescript theme={null}
(projects: ProjectDetail[]) => CategorizedProjects
```

## getProjectCategoryName()

Get human-readable project category name.  T4525

**Signature**

```typescript theme={null}
(category: "active" | "orphaned" | "temp") => string
```

## formatProjectHealthSummary()

Format project health summary for display.  T4525

**Signature**

```typescript theme={null}
(summary: HealthSummary) => string
```

## getProjectGuidance()

Get actionable guidance for project issues.  T4525

**Signature**

```typescript theme={null}
(activeFailed: number, activeWarnings: number, tempCount: number, orphanedCount: number) => string[]
```

## getUserJourneyStage()

Check user journey stage based on system state.  T4525

**Signature**

```typescript theme={null}
(hasProjects: boolean, tempProjectCount: number, agentConfigsOk: boolean) => UserJourneyStage
```

## getJourneyGuidance()

Get journey-specific guidance text.  T4525

**Signature**

```typescript theme={null}
(stage: UserJourneyStage) => string[]
```

## sanitizeFilePath()

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

**Signature**

```typescript theme={null}
(path: string) => string
```

## validateTitle()

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

**Signature**

```typescript theme={null}
(title: string) => ValidationResult
```

## validateDescription()

T4523

**Signature**

```typescript theme={null}
(desc: string) => ValidationResult
```

## validateNote()

T4523

**Signature**

```typescript theme={null}
(note: string) => ValidationResult
```

## validateBlockedBy()

T4523

**Signature**

```typescript theme={null}
(reason: string) => ValidationResult
```

## validateSessionNote()

T4523

**Signature**

```typescript theme={null}
(note: string) => ValidationResult
```

## validateCancelReason()

Validate a cancellation reason.  T4523

**Signature**

```typescript theme={null}
(reason: string) => ValidationResult
```

## validateStatusTransition()

Validate that a status transition is allowed.  T4523

**Signature**

```typescript theme={null}
(oldStatus: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived", newStatus: "cancelled" | "pending" | "active" | "blocked" | "done" | "archived") => ValidationResult
```

## isValidStatus()

Check if a status string is valid.  T4523

**Signature**

```typescript theme={null}
(status: string) => status is "cancelled" | "pending" | "active" | "blocked" | "done" | "archived"
```

## checkTimestampSanity()

Check timestamp format and sanity.  T4523

**Signature**

```typescript theme={null}
(createdAt: string, completedAt?: string | undefined) => ValidationResult
```

## isMetadataOnlyUpdate()

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

**Signature**

```typescript theme={null}
(fields: string[]) => boolean
```

## normalizeLabels()

Deduplicate and normalize labels.  T4523

**Signature**

```typescript theme={null}
(labels: string) => string
```

## checkIdUniqueness()

Check ID uniqueness within and across files.  T4523

**Signature**

```typescript theme={null}
(taskFile: TaskFile, archiveFile?: ArchiveFile | undefined) => ValidationResult
```

## validateTask()

Validate a single task object.  T4523

**Signature**

```typescript theme={null}
(task: Task) => ValidationResult
```

## validateNoCircularDeps()

Check for circular dependencies using DFS.  T4523

**Signature**

```typescript theme={null}
(tasks: Task[], taskId: string, newDeps: string[]) => ValidationResult
```

## validateSingleActivePhase()

Validate only one phase is active.  T4523

**Signature**

```typescript theme={null}
(taskFile: TaskFile) => ValidationResult
```

## validateCurrentPhaseConsistency()

Validate currentPhase matches an active phase.  T4523

**Signature**

```typescript theme={null}
(taskFile: TaskFile) => ValidationResult
```

## validatePhaseTimestamps()

Validate phase timestamp ordering.  T4523

**Signature**

```typescript theme={null}
(taskFile: TaskFile) => ValidationResult
```

## validatePhaseStatusRequirements()

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

**Signature**

```typescript theme={null}
(taskFile: TaskFile) => ValidationResult
```

## validateAll()

Run all validation checks on a TaskFile.  T4523

**Signature**

```typescript theme={null}
(taskFile: TaskFile, archiveFile?: ArchiveFile | undefined) => ComprehensiveValidationResult
```

## parseManifest()

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

**Signature**

```typescript theme={null}
(content: string) => ManifestDoc[]
```

## findReviewDocs()

Find documents in review status.  T4524

**Signature**

```typescript theme={null}
(entries: ManifestDoc[], filterId?: string | undefined) => ManifestDoc[]
```

## extractTopics()

Extract markdown headings from file content.  T4524

**Signature**

```typescript theme={null}
(content: string) => string[]
```

## searchCanonicalCoverage()

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

**Signature**

```typescript theme={null}
(topic: string, docsFileContents: Map<string, string>) => { topic: string; matches: number; files: string[]; }
```

## analyzeCoverage()

Analyze documentation coverage for review documents.  T4524

**Signature**

```typescript theme={null}
(reviewDocs: ManifestDoc[], docsFileContents: Map<string, string>, filterId?: string | undefined) => GapReport
```

## formatGapReport()

Format a gap report for human-readable display.  T4524

**Signature**

```typescript theme={null}
(report: GapReport) => string
```

## findManifestEntry()

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

**Signature**

```typescript theme={null}
(taskId: string, manifestPath?: string | undefined) => Promise<ManifestEntry | null>
```

## validateManifestEntry()

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

**Signature**

```typescript theme={null}
(taskId: string, manifestEntry?: ManifestEntry | null | undefined, manifestPath?: string) => Promise<ManifestValidationResult>
```

## logRealCompliance()

Log validation results to the compliance JSONL file.  T4526

**Signature**

```typescript theme={null}
(taskId: string, validationResult: ManifestValidationResult, agentType?: string, compliancePath?: string) => Promise<void>
```

## validateAndLog()

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

**Signature**

```typescript theme={null}
(taskId: string, manifestPath?: string, compliancePath?: string) => Promise<ManifestValidationResult>
```

## checkOutputFileExists()

Check if expected output file exists.  T4527

**Signature**

```typescript theme={null}
(taskId: string, expectedDir: string, pattern?: string | undefined) => boolean
```

## checkDocumentationSections()

Check if file contains required documentation sections.  T4527

**Signature**

```typescript theme={null}
(filePath: string, sections: string[]) => boolean
```

## checkReturnMessageFormat()

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

**Signature**

```typescript theme={null}
(message: string, _protocolType?: string | undefined) => boolean
```

## checkManifestFieldPresent()

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

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>, fieldName: string) => boolean
```

## checkManifestFieldType()

Check if manifest field has expected type.  T4527

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>, fieldName: string, expectedType: "string" | "number" | "boolean" | "object" | "array") => boolean
```

## checkKeyFindingsCount()

Check if key\_findings array has valid count (3-7).  T4527

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>) => boolean
```

## checkStatusValid()

Check if status is valid enum value.  T4527

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>) => boolean
```

## checkAgentType()

Check if agent\_type matches expected value.  T4527

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>, expectedType: string) => boolean
```

## checkLinkedTasksPresent()

Check if linked\_tasks array contains required task IDs.  T4527

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>, requiredIds: string[]) => boolean
```

## checkProvenanceTags()

Check if file contains  provenance tag.  T4527

**Signature**

```typescript theme={null}
(filePath: string, taskId?: string | undefined) => boolean
```

## validateCommonManifestRequirements()

Validate common manifest requirements across all protocols.  T4527

**Signature**

```typescript theme={null}
(entry: Record<string, unknown>, _protocolType?: string | undefined) => ProtocolValidationResult
```

## isValidGateName()

T4526

**Signature**

```typescript theme={null}
(name: string) => name is "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented"
```

## isValidAgentName()

T4526

**Signature**

```typescript theme={null}
(name: string) => name is "testing" | "planner" | "coder" | "qa" | "cleanup" | "security" | "docs"
```

## getGateOrder()

T4526

**Signature**

```typescript theme={null}
() => ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]
```

## getGateIndex()

T4526

**Signature**

```typescript theme={null}
(gateName: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented") => number
```

## getDownstreamGates()

T4526

**Signature**

```typescript theme={null}
(fromGate: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented") => ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]
```

## initVerification()

Initialize a new verification object with default values.  T4526

**Signature**

```typescript theme={null}
() => Verification
```

## computePassed()

Compute whether verification has passed based on required gates.  T4526

**Signature**

```typescript theme={null}
(verification: Verification, requiredGates?: ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]) => boolean
```

## setVerificationPassed()

Update the passed field on a verification object.  T4526

**Signature**

```typescript theme={null}
(verification: Verification, passed: boolean) => Verification
```

## updateGate()

Update a single gate value.  T4526

**Signature**

```typescript theme={null}
(verification: Verification, gateName: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented", value: boolean | null, agent?: string | undefined) => Verification
```

## resetDownstreamGates()

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

**Signature**

```typescript theme={null}
(verification: Verification, fromGate: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented") => Verification
```

## incrementRound()

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

**Signature**

```typescript theme={null}
(verification: Verification, maxRounds?: number) => Verification | null
```

## logFailure()

Log a failure to the failureLog array.  T4526

**Signature**

```typescript theme={null}
(verification: Verification, gateName: "implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented", agent: string, reason: string) => Verification
```

## checkAllGatesPassed()

Check if all required gates have passed.  T4526

**Signature**

```typescript theme={null}
(verification: Verification, requiredGates?: ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]) => boolean
```

## isVerificationComplete()

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

**Signature**

```typescript theme={null}
(verification: Verification | null) => boolean
```

## getVerificationStatus()

Get verification status for display.  T4526

**Signature**

```typescript theme={null}
(verification: Verification | null) => VerificationStatus
```

## shouldRequireVerification()

Check if a task type should require verification.  T4526

**Signature**

```typescript theme={null}
(taskType?: string, verificationEnabled?: boolean) => boolean
```

## getMissingGates()

Get gate names that are not yet true.  T4526

**Signature**

```typescript theme={null}
(verification: Verification, requiredGates?: ("implemented" | "testsPassed" | "qaPassed" | "cleanupDone" | "securityPassed" | "documented")[]) => ("implemented" | ... 4 more ... | "documented")[]
```

## getGateSummary()

Get gate summary for display.  T4526

**Signature**

```typescript theme={null}
(verification: Verification) => { passed: boolean; round: number; gates: VerificationGates; lastAgent: string | null; lastUpdated: string; failureCount: number; }
```

## checkCircularValidation()

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

**Signature**

```typescript theme={null}
(currentAgent: string, createdBy?: string | null | undefined, validatedBy?: string | null | undefined, testedBy?: string | null | undefined) => CircularValidationResult
```

## allEpicChildrenVerified()

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

**Signature**

```typescript theme={null}
(epicId: string, tasks: TaskForVerification[]) => boolean
```

## allSiblingsVerified()

Check if all siblings of a task are verified.  T4526

**Signature**

```typescript theme={null}
(parentId: string, tasks: TaskForVerification[]) => boolean
```

## getProjectInfo()

Read project-info.json and return a typed ProjectInfo.  Falls back gracefully when projectId is missing (pre-T5333 installs) by returning an empty string, allowing callers to detect and handle.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<ProjectInfo>
```

**Throws**

* Error If .cleo/project-info.json does not exist or is invalid JSON.

## getProjectInfoSync()

Synchronous variant for use in hot paths where async is not feasible. Returns null if the file is missing or unparseable.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => ProjectInfo | null
```

## ProtocolEnforcer

Main protocol enforcement class

**Signature**

```typescript theme={null}
typeof ProtocolEnforcer
```

**Methods**

### validateProtocol()

Validate protocol compliance for a manifest entry

```typescript theme={null}
(protocol: ProtocolType, manifestEntry: Record<string, unknown>, additionalData?: Record<string, unknown> | undefined) => Promise<ProtocolValidationResult>
```

### validateRule()

Validate a single rule

```typescript theme={null}
(rule: ProtocolRule, manifestEntry: Record<string, unknown>, additionalData?: Record<string, unknown> | undefined) => Promise<ProtocolViolation | null>
```

### checkLifecycleGate()

Check lifecycle gate prerequisites

```typescript theme={null}
(_taskId: string, targetStage: string, lifecycleManifest?: Record<string, unknown> | undefined) => Promise<{ passed: boolean; missingPrerequisites: string[]; message: string; }>
```

### recordViolation()

Record a protocol violation

```typescript theme={null}
(protocol: ProtocolType, violations: ProtocolViolation[], score: number, taskId?: string | undefined) => void
```

### getViolations()

Get recent violations

```typescript theme={null}
(limit?: number | undefined) => ViolationLogEntry[]
```

### calculatePenalty()

Calculate penalty for violation severity

```typescript theme={null}
(severity: "error" | "warning") => number
```

### enforceProtocol()

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

```typescript theme={null}
(request: ProtocolRequest, next: () => Promise<ProtocolResponse>) => Promise<ProtocolResponse>
```

### requiresProtocolValidation()

Determine if operation requires protocol validation

```typescript theme={null}
(request: ProtocolRequest) => boolean
```

### detectProtocol()

Detect protocol type from request/response

```typescript theme={null}
(request: ProtocolRequest, _response: ProtocolResponse) => ProtocolType | null
```

### extractManifestEntry()

Extract manifest entry from response

```typescript theme={null}
(response: ProtocolResponse) => Record<string, unknown> | null
```

### setStrictMode()

Set strict mode

```typescript theme={null}
(strict: boolean) => void
```

### isStrictMode()

Get strict mode status

```typescript theme={null}
() => boolean
```

## getHookCapableProviders(event)

Get all providers that support a specific hook event

**Signature**

```typescript theme={null}
(event: HookEvent) => string[]
```

**Parameters**

| Name    | Type        | Description             |
| ------- | ----------- | ----------------------- |
| `event` | `HookEvent` | The hook event to query |

**Returns** — Array of provider IDs that support this event

## getSharedHookEvents(providerIds)

Get hook events supported by all specified providers

**Signature**

```typescript theme={null}
(providerIds?: string[] | undefined) => HookEvent[]
```

**Parameters**

| Name          | Type                      | Description                                                           |
| ------------- | ------------------------- | --------------------------------------------------------------------- |
| `providerIds` | `: string[] \| undefined` | Optional array of provider IDs (uses all active providers if omitted) |

**Returns** — Array of hook events supported by all specified providers

## validateChainShape()

Validate the topology/DAG of a chain shape.  Checks: - All link source/target IDs reference existing stages - entryPoint references an existing stage - All exitPoints reference existing stages - No cycles (topological sort) - All stages are reachable from the entry point   T5401

**Signature**

```typescript theme={null}
(shape: ChainShape) => string[]
```

## validateGateSatisfiability()

Validate that all gates in a chain reference valid stages and gate names.  Checks: - Every gate's stageId references an existing stage - Every stage\_complete check references an existing stage - Every verification\_gate check references a valid GateName   T5401

**Signature**

```typescript theme={null}
(chain: WarpChain) => string[]
```

## validateChain()

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

**Signature**

```typescript theme={null}
(chain: WarpChain) => ChainValidation
```

## addChain()

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

**Signature**

```typescript theme={null}
(chain: WarpChain, projectRoot: string) => Promise<void>
```

## showChain()

Retrieve a WarpChain definition by ID.   T5403

**Signature**

```typescript theme={null}
(id: string, projectRoot: string) => Promise<WarpChain | null>
```

## listChains()

List all stored WarpChain definitions.   T5403

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<WarpChain[]>
```

## findChains()

Find WarpChain definitions by criteria.   T5403

**Signature**

```typescript theme={null}
(criteria: ChainFindCriteria, projectRoot: string) => Promise<WarpChain[]>
```

## createInstance()

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

**Signature**

```typescript theme={null}
(params: { chainId: string; epicId: string; variables?: Record<string, unknown> | undefined; stageToTask?: Record<string, string> | undefined; }, projectRoot: string) => Promise<...>
```

## showInstance()

Retrieve a chain instance by ID.   T5403

**Signature**

```typescript theme={null}
(id: string, projectRoot: string) => Promise<WarpChainInstance | null>
```

## listInstanceGateResults()

Read persisted gate results for a chain instance.

**Signature**

```typescript theme={null}
(id: string, projectRoot: string) => Promise<GateResult[]>
```

## advanceInstance()

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

**Signature**

```typescript theme={null}
(id: string, nextStage: string, gateResults: GateResult[], projectRoot: string) => Promise<WarpChainInstance>
```

## validateResearchProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { strict?: boolean | undefined; hasCodeChanges?: boolean | undefined; }) => ProtocolValidationResult
```

## validateConsensusProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, votingMatrix?: VotingMatrix) => ProtocolValidationResult
```

## validateSpecificationProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, specContent?: string | undefined) => ProtocolValidationResult
```

## validateDecompositionProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { siblingCount?: number | undefined; descriptionClarity?: boolean | undefined; maxSiblings?: number | undefined; maxDepth?: number | undefined; }) => ProtocolValidationResult
```

## validateImplementationProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { hasTaskTags?: boolean | undefined; }) => ProtocolValidationResult
```

## validateContributionProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { hasContributionTags?: boolean | undefined; }) => ProtocolValidationResult
```

## validateReleaseProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { version?: string | undefined; hasChangelog?: boolean | undefined; }) => ProtocolValidationResult
```

## validateArtifactPublishProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { artifactType?: string | undefined; buildPassed?: boolean | undefined; }) => ProtocolValidationResult
```

## validateProvenanceProtocol()

T4499

**Signature**

```typescript theme={null}
(entry: ManifestEntryInput, options?: { hasAttestation?: boolean | undefined; hasSbom?: boolean | undefined; }) => ProtocolValidationResult
```

## validateProtocol()

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

**Signature**

```typescript theme={null}
(protocol: "research" | "consensus" | "specification" | "decomposition" | "implementation" | "release" | "contribution" | "provenance" | "artifact-publish", entry: ManifestEntryInput, options?: Record<...>, strict?: boolean) => ProtocolValidationResult
```

## buildDefaultChain()

Build the canonical 9-stage RCASD-IVTR+C WarpChain.  - Each PIPELINE\_STAGE becomes a WarpStage - Each prerequisite from STAGE\_PREREQUISITES becomes an entry GateContract - Each verification gate from VERIFICATION\_GATE\_ORDER becomes an exit GateContract - All 8 links are linear (stage\[i] - stage\[i+1])   T5399

**Signature**

```typescript theme={null}
() => WarpChain
```

## buildDefaultTessera()

Build the default RCASD Tessera template.  Wraps buildDefaultChain() with template variables: - epicId (required, type 'epicId') - projectName (optional, type 'string', default 'unnamed') - skipResearch (optional, type 'boolean', default false)   T5409

**Signature**

```typescript theme={null}
() => TesseraTemplate
```

## instantiateTessera()

Instantiate a Tessera template into a concrete WarpChainInstance.  Steps: 1. Validate all required variables are provided 2. Apply defaults for missing optional variables 3. Construct concrete WarpChain from template 4. Validate chain via validateChain() 5. Store via createInstance() from chain-store 6. Return instance   T5409

**Signature**

```typescript theme={null}
(template: TesseraTemplate, input: TesseraInstantiationInput, projectRoot: string) => Promise<WarpChainInstance>
```

## listTesseraTemplates()

List all registered Tessera templates.   T5409

**Signature**

```typescript theme={null}
() => TesseraTemplate[]
```

## showTessera()

Find a Tessera template by ID.   T5409

**Signature**

```typescript theme={null}
(id: string) => TesseraTemplate | null
```

## migrateClaudeMem(projectRoot, options)

Migrate observations from claude-mem's SQLite database into CLEO brain.db.  Reads from \~/.claude-mem/claude-mem.db (or a custom path) and inserts into: - brain\_observations (all observations, prefixed CM-) - brain\_decisions (decision-typed observations, prefixed CMD-) - brain\_learnings (session summaries with learned field, prefixed CML-)  Idempotent: skips rows whose ID already exists in brain.db. After all inserts, rebuilds FTS5 indexes.

**Signature**

```typescript theme={null}
(projectRoot: string, options?: ClaudeMemMigrationOptions) => Promise<ClaudeMemMigrationResult>
```

**Parameters**

| 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 through `depends` fields, collecting unresolved blockers and their associated brain decisions. Leaf blockers (no further unresolved deps) are reported as root causes.

**Signature**

```typescript theme={null}
(taskId: string, projectRoot: string, taskAccessor?: DataAccessor | undefined) => Promise<CausalTrace>
```

## reasonSimilar(entryId, projectRoot, limit)

Find entries similar to a given brain.db entry.  1. Loads the source entry's text from brain.db. 2. Calls searchSimilar() for vector-based similarity if embeddings exist. 3. Falls back to FTS5 keyword search if no embeddings are available. 4. Filters out the source entry itself.

**Signature**

```typescript theme={null}
(entryId: string, projectRoot: string, limit?: number | undefined) => Promise<SimilarEntry[]>
```

**Parameters**

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

**Returns** — Array of similar entries ranked by distance/relevance

## memoryShow()

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

**Signature**

```typescript theme={null}
(entryId: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryBrainStats()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryDecisionFind()

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

**Signature**

```typescript theme={null}
(params: { query?: string | undefined; taskId?: string | undefined; limit?: number | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryDecisionStore()

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

**Signature**

```typescript theme={null}
(params: { decision: string; rationale: string; alternatives?: string[] | undefined; taskId?: string | undefined; sessionId?: string | undefined; }, projectRoot?: string | undefined) => Promise<...>
```

## memoryFind()

memory.find - Token-efficient brain search

**Signature**

```typescript theme={null}
(params: { query: string; limit?: number | undefined; tables?: string[] | undefined; dateStart?: string | undefined; dateEnd?: string | undefined; }, projectRoot?: string | undefined) => Promise<...>
```

## memoryTimeline()

memory.timeline - Chronological context around anchor

**Signature**

```typescript theme={null}
(params: { anchor: string; depthBefore?: number | undefined; depthAfter?: number | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryFetch()

memory.fetch - Batch fetch brain entries by IDs

**Signature**

```typescript theme={null}
(params: { ids: string[]; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryObserve()

memory.observe - Save observation to brain

**Signature**

```typescript theme={null}
(params: { text: string; title?: string | undefined; type?: string | undefined; project?: string | undefined; sourceSessionId?: string | undefined; sourceType?: string | undefined; }, projectRoot?: string | undefined) => Promise<...>
```

## memoryPatternStore()

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

**Signature**

```typescript theme={null}
(params: StorePatternParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryPatternFind()

memory.pattern.find - Search patterns in BRAIN memory

**Signature**

```typescript theme={null}
(params: SearchPatternParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryPatternStats()

memory.pattern.stats - Get pattern memory statistics

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryLearningStore()

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

**Signature**

```typescript theme={null}
(params: StoreLearningParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryLearningFind()

memory.learning.find - Search learnings in BRAIN memory

**Signature**

```typescript theme={null}
(params: SearchLearningParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryLearningStats()

memory.learning.stats - Get learning memory statistics

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryContradictions()

memory.contradictions - Find contradictory entries in brain.db

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memorySuperseded()

memory.superseded - Find superseded entries in brain.db  Identifies entries that have been superseded by newer entries on the same topic. For brain.db, we group by: - Decisions: type + contextTaskId/contextEpicId - Patterns: type + context (first 100 chars for similarity) - Learnings: source + applicableTypes - Observations: type + project

**Signature**

```typescript theme={null}
(params?: { type?: string | undefined; project?: string | undefined; } | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryLink()

memory.link - Link a brain entry to a task

**Signature**

```typescript theme={null}
(params: { taskId: string; entryId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryUnlink()

memory.unlink - Remove a link between a brain entry and a task

**Signature**

```typescript theme={null}
(params: { taskId: string; entryId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryGraphAdd()

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

**Signature**

```typescript theme={null}
(params: { nodeId?: string | undefined; nodeType?: string | undefined; label?: string | undefined; metadataJson?: string | undefined; fromId?: string | undefined; toId?: string | undefined; edgeType?: string | undefined; weight?: number | undefined; }, projectRoot?: string | undefined) => Promise<...>
```

## memoryGraphShow()

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

**Signature**

```typescript theme={null}
(params: { nodeId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryGraphNeighbors()

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

**Signature**

```typescript theme={null}
(params: { nodeId: string; edgeType?: string | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryReasonWhy()

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

**Signature**

```typescript theme={null}
(params: { taskId: string; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memoryReasonSimilar()

memory.reason.similar - Find semantically similar entries

**Signature**

```typescript theme={null}
(params: { entryId: string; limit?: number | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## memorySearchHybrid()

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

**Signature**

```typescript theme={null}
(params: { query: string; ftsWeight?: number | undefined; vecWeight?: number | undefined; graphWeight?: number | undefined; limit?: number | undefined; }, projectRoot?: string | undefined) => Promise<...>
```

## memoryGraphRemove()

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

**Signature**

```typescript theme={null}
(params: { nodeId?: string | undefined; fromId?: string | undefined; toId?: string | undefined; edgeType?: string | undefined; }, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestShow()

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

**Signature**

```typescript theme={null}
(researchId: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestList()

pipeline.manifest.list - List manifest entries with filters

**Signature**

```typescript theme={null}
(params: PipelineManifestListParams, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestFind()

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

**Signature**

```typescript theme={null}
(query: string, options?: { confidence?: number | undefined; limit?: number | undefined; } | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestPending()

pipeline.manifest.pending - Get pending manifest items

**Signature**

```typescript theme={null}
(epicId?: string | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestStats()

pipeline.manifest.stats - Manifest statistics

**Signature**

```typescript theme={null}
(epicId?: string | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestRead()

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

**Signature**

```typescript theme={null}
(filter?: ResearchFilter | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestAppend()

pipeline.manifest.append - Append entry to pipeline\_manifest table

**Signature**

```typescript theme={null}
(entry: ExtendedManifestEntry, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestArchive()

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

**Signature**

```typescript theme={null}
(beforeDate: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestCompact()

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

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestValidate()

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

**Signature**

```typescript theme={null}
(taskId: string, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## pipelineManifestContradictions()

pipeline.manifest.contradictions - Find entries with overlapping topics but conflicting key\_findings

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<EngineResult<{ contradictions: ContradictionDetail[]; }>>
```

## pipelineManifestSuperseded()

pipeline.manifest.superseded - Identify entries replaced by newer work on same topic

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined, params?: { topic?: string | undefined; } | undefined) => Promise<EngineResult<{ superseded: SupersededDetail[]; }>>
```

## pipelineManifestLink()

pipeline.manifest.link - Link manifest entry to a task

**Signature**

```typescript theme={null}
(taskId: string, researchId: string, notes?: string | undefined, projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## readManifestEntries()

Read all manifest entries from the pipeline\_manifest table. Replaces readManifestEntries() from pipeline-manifest-compat.

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<ExtendedManifestEntry[]>
```

## filterEntries()

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

**Signature**

```typescript theme={null}
(entries: ExtendedManifestEntry[], filter: ResearchFilter) => ExtendedManifestEntry[]
```

## distillManifestEntry()

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

**Signature**

```typescript theme={null}
(_entryId: string, _projectRoot?: string | undefined) => Promise<EngineResult<unknown>>
```

## migrateManifestJsonlToSqlite()

Migrate existing .cleo/MANIFEST.jsonl entries into the pipeline\_manifest table. Skips entries that already exist (by id). Renames MANIFEST.jsonl to MANIFEST.jsonl.migrated when done.

**Signature**

```typescript theme={null}
(projectRoot?: string | undefined) => Promise<{ migrated: number; skipped: number; }>
```

**Returns** — Count of migrated and skipped entries.

## resolveProviderFromModelIndex()

**Signature**

```typescript theme={null}
(index: ModelsDevIndex, model?: string | undefined) => ModelProviderLookup
```

## resolveProviderFromModelRegistry()

**Signature**

```typescript theme={null}
(model?: string | undefined) => Promise<ModelProviderLookup>
```

## resetModelsDevCache()

**Signature**

```typescript theme={null}
() => void
```

## measureTokenExchange()

**Signature**

```typescript theme={null}
(input: TokenExchangeInput) => Promise<TokenMeasurement>
```

## recordTokenExchange()

**Signature**

```typescript theme={null}
(input: TokenExchangeInput) => Promise<{ sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; domain: string | null; ... 14 more ...; responseHash: string | null; }>
```

## showTokenUsage()

**Signature**

```typescript theme={null}
(id: string, cwd?: string | undefined) => Promise<{ sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; domain: string | null; operation: string | null; ... 13 more ...; responseHash: string | null; } | null>
```

## listTokenUsage()

**Signature**

```typescript theme={null}
(filters?: TokenUsageFilters, cwd?: string | undefined) => Promise<{ records: { sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; ... 15 more ...; responseHash: string | null; }[]; total: number; filtered: number; }>
```

## summarizeTokenUsage()

**Signature**

```typescript theme={null}
(filters?: TokenUsageFilters, cwd?: string | undefined) => Promise<TokenUsageSummary>
```

## deleteTokenUsage()

**Signature**

```typescript theme={null}
(id: string, cwd?: string | undefined) => Promise<{ deleted: boolean; id: string; }>
```

## clearTokenUsage()

**Signature**

```typescript theme={null}
(filters?: TokenUsageFilters, cwd?: string | undefined) => Promise<{ deleted: number; }>
```

## autoRecordDispatchTokenUsage()

**Signature**

```typescript theme={null}
(input: TokenExchangeInput) => Promise<void>
```

## getLatestTokenRecord()

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ sessionId: string | null; id: string; createdAt: string; taskId: string | null; metadataJson: string; domain: string | null; operation: string | null; ... 13 more ...; responseHash: string | null; } | null>
```

## getTokenUsageAggregateSql()

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ provider: string; transport: string; totalTokens: number; count: number; }[]>
```

## startParallelExecution()

Start parallel execution for a wave.

**Signature**

```typescript theme={null}
(epicId: string, wave: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; wave: number; tasks: string[]; taskCount: number; startedAt: string; }>
```

## endParallelExecution()

End parallel execution for a wave.

**Signature**

```typescript theme={null}
(epicId: string, wave: number, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<{ epicId: string; wave: number; tasks: string[]; taskCount: number; startedAt: string | null; endedAt: string; durationMs: number; alreadyEnded?: boolean | undefined; }>
```

## getParallelStatus()

Get current parallel execution state.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<ParallelState>
```

## listSkills()

List available skills.

**Signature**

```typescript theme={null}
(_projectRoot: string) => { skills: SkillEntry[]; total: number; }
```

## getSkillContent()

Read skill content for injection into agent context.

**Signature**

```typescript theme={null}
(skillName: string, _projectRoot: string) => SkillContent
```

## getUnblockOpportunities()

Analyze dependency graph for unblocking opportunities.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<UnblockResult>
```

## validateSpawnReadiness()

Validate spawn readiness for a task.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<SpawnValidationResult>
```

## injectContext()

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

**Signature**

```typescript theme={null}
(protocolType: string, params?: { taskId?: string | undefined; variant?: string | undefined; } | undefined, projectRoot?: string | undefined) => ContextInjectionData
```

## generateSessionId()

Generate a canonical session ID.  Format: ses\_YYYYMMDDHHmmss\_6hex Example: ses\_20260227171900\_a1b2c3

**Signature**

```typescript theme={null}
() => string
```

## isValidSessionId()

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

**Signature**

```typescript theme={null}
(id: string) => boolean
```

## isCanonicalSessionId()

Check if a session ID uses the canonical format.

**Signature**

```typescript theme={null}
(id: string) => boolean
```

## extractSessionTimestamp()

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

**Signature**

```typescript theme={null}
(id: string) => Date | null
```

## createSession()

Create a new session.

**Signature**

```typescript theme={null}
(session: Session, cwd?: string | undefined) => Promise<Session>
```

## getSession()

Get a session by ID.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<Session | null>
```

## updateSession()

Update a session.

**Signature**

```typescript theme={null}
(sessionId: string, updates: Partial<Session>, cwd?: string | undefined) => Promise<Session | null>
```

## listSessions()

List sessions with optional filters.

**Signature**

```typescript theme={null}
(filters?: { active?: boolean | undefined; limit?: number | undefined; } | undefined, cwd?: string | undefined) => Promise<Session[]>
```

## endSession()

End a session.

**Signature**

```typescript theme={null}
(sessionId: string, note?: string | undefined, cwd?: string | undefined) => Promise<Session | null>
```

## startTask()

Start working on a task within a session.

**Signature**

```typescript theme={null}
(sessionId: string, taskId: string, cwd?: string | undefined) => Promise<void>
```

## getCurrentTask()

Get current task for a session.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<{ taskId: string | null; since: string | null; }>
```

## stopTask()

Stop working on the current task for a session.

**Signature**

```typescript theme={null}
(sessionId: string, cwd?: string | undefined) => Promise<void>
```

## workHistory()

Get work history for a session.

**Signature**

```typescript theme={null}
(sessionId: string, limit?: number, cwd?: string | undefined) => Promise<{ taskId: string; setAt: string; clearedAt: string | null; }[]>
```

## gcSessions()

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

**Signature**

```typescript theme={null}
(maxAgeDays?: number, cwd?: string | undefined) => Promise<number>
```

## getActiveSession()

Get the currently active session (if any).

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<Session | null>
```

## computeDependencyWaves()

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

**Signature**

```typescript theme={null}
(tasks: Task[]) => DependencyWave[]
```

## getNextTask()

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

**Signature**

```typescript theme={null}
(tasks: Task[]) => Task | null
```

## getCriticalPath()

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

**Signature**

```typescript theme={null}
(tasks: Task[]) => string[]
```

## getTaskOrder()

Get task ordering by dependency + priority.

**Signature**

```typescript theme={null}
(tasks: Task[]) => string[]
```

## getParallelTasks()

Get parallelizable tasks (tasks with no unmet dependencies).

**Signature**

```typescript theme={null}
(tasks: Task[]) => string[]
```

## suggestRelated()

Suggest related tasks based on shared attributes.

**Signature**

```typescript theme={null}
(taskId: string, opts: { threshold?: number | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## addRelation()

Add a relation between tasks.

**Signature**

```typescript theme={null}
(from: string, to: string, type: string, reason: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## discoverRelated()

Discover related tasks using various methods.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## listRelations()

List existing relations for a task.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## canCancel()

Check if a task can be cancelled.

**Signature**

```typescript theme={null}
(task: Task) => { allowed: boolean; reason?: string | undefined; }
```

## cancelTask()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[], reason?: string | undefined) => { tasks: Task[]; result: CancelResult; }
```

## cancelMultiple()

Batch cancel multiple tasks.

**Signature**

```typescript theme={null}
(taskIds: string[], tasks: Task[], reason?: string | undefined) => { tasks: Task[]; results: CancelResult[]; }
```

## coreTaskNext()

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

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { count?: number | undefined; explain?: boolean | undefined; } | undefined) => Promise<{ suggestions: { id: string; title: string; priority: string; phase: string | null; score: number; reasons?: string[] | undefined; }[]; totalCandidates: number; }>
```

## coreTaskBlockers()

Show blocked tasks and analyze blocking chains.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { analyze?: boolean | undefined; limit?: number | undefined; } | undefined) => Promise<{ blockedTasks: { id: string; title: string; status: string; depends?: string[] | undefined; blockingChain: string[]; }[]; criticalBlockers: BottleneckTask[]; summary: string; total: number; limit: n...
```

## coreTaskTree()

Build hierarchy tree.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string | undefined) => Promise<{ tree: FlatTreeNode[]; totalNodes: number; }>
```

## coreTaskDeps()

Show dependencies for a task.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<TaskDepsResult>
```

## coreTaskRelates()

Show task relations.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<{ taskId: string; relations: { taskId: string; type: string; reason?: string | undefined; }[]; count: number; }>
```

## coreTaskRelatesAdd()

Add a relation between two tasks.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, relatedId: string, type: string, reason?: string | undefined) => Promise<{ from: string; to: string; type: string; reason?: string | undefined; added: boolean; }>
```

## coreTaskAnalyze()

Analyze tasks for priority and leverage.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string | undefined, params?: { tierLimit?: number | undefined; } | undefined) => Promise<TaskAnalysisResult & { tierLimit: number; }>
```

## coreTaskRestore()

Restore a cancelled task back to pending.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { cascade?: boolean | undefined; notes?: string | undefined; } | undefined) => Promise<{ task: string; restored: string[]; count: number; }>
```

## coreTaskCancel()

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

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { reason?: string | undefined; } | undefined) => Promise<{ task: string; cancelled: boolean; reason?: string | undefined; cancelledAt: string; }>
```

## coreTaskUnarchive()

Move an archived task back to active tasks.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { status?: string | undefined; preserveStatus?: boolean | undefined; } | undefined) => Promise<{ task: string; unarchived: boolean; title: string; status: string; }>
```

## coreTaskReorder()

Change task position within its sibling group.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, position: number) => Promise<{ task: string; reordered: boolean; newPosition: number; totalSiblings: number; }>
```

## coreTaskReparent()

Move task under a different parent.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, newParentId: string | null) => Promise<{ task: string; reparented: boolean; oldParent: string | null; newParent: string | null; newType?: string | undefined; }>
```

## coreTaskPromote()

Promote a subtask to task or task to root.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<{ task: string; promoted: boolean; previousParent: string | null; typeChanged: boolean; }>
```

## coreTaskReopen()

Reopen a completed task.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { status?: string | undefined; reason?: string | undefined; } | undefined) => Promise<{ task: string; reopened: boolean; previousStatus: string; newStatus: string; }>
```

## coreTaskComplexityEstimate()

Deterministic complexity scoring from task metadata.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, params: { taskId: string; }) => Promise<{ size: "medium" | "small" | "large"; score: number; factors: ComplexityFactor[]; dependencyDepth: number; subtaskCount: number; fileCount: number; }>
```

## coreTaskDepsOverview()

Overview of all dependencies across the project.  T5157

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ totalTasks: number; tasksWithDeps: number; blockedTasks: (TaskRef & { unblockedBy: string[]; })[]; readyTasks: TaskRef[]; validation: { valid: boolean; errorCount: number; warningCount: number; }; }>
```

## coreTaskDepsCycles()

Detect circular dependencies across the project.  T5157

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ hasCycles: boolean; cycles: { path: string[]; tasks: Pick<TaskRef, "id" | "title">[]; }[]; }>
```

## coreTaskDepends()

List dependencies for a task in a given direction.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, direction?: "upstream" | "downstream" | "both", options?: { tree?: boolean | undefined; } | undefined) => Promise<{ taskId: string; direction: string; ... 6 more ...; upstreamTree?: FlatTreeNode[] | undefined; }>
```

## coreTaskStats()

Compute task statistics.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, epicId?: string | undefined) => Promise<{ total: number; pending: number; active: number; blocked: number; done: number; cancelled: number; byPriority: Record<string, number>; byType: Record<...>; }>
```

## coreTaskExport()

Export tasks as JSON or CSV.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { format?: "json" | "csv" | undefined; status?: string | undefined; parent?: string | undefined; } | undefined) => Promise<unknown>
```

## coreTaskHistory()

Get task history from the log file.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, limit?: number | undefined) => Promise<Record<string, unknown>[]>
```

## coreTaskLint()

Lint tasks for common issues.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string | undefined) => Promise<{ taskId: string; severity: "error" | "warning"; rule: string; message: string; }[]>
```

## coreTaskBatchValidate()

Validate multiple tasks at once.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, taskIds: string[], checkMode?: "full" | "quick") => Promise<{ results: Record<string, { severity: "error" | "warning"; rule: string; message: string; }[]>; summary: { ...; }; }>
```

## coreTaskImport()

Import tasks from a JSON source string.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, source: string, overwrite?: boolean | undefined) => Promise<{ imported: number; skipped: number; errors: string[]; remapTable?: Record<string, string> | undefined; }>
```

## analyzeTaskPriority()

Analyze task priority with leverage scoring.

**Signature**

```typescript theme={null}
(opts: { autoStart?: boolean | undefined; cwd?: string | undefined; }, accessor?: DataAccessor | undefined) => Promise<AnalysisResult>
```

## listLabels()

List all labels with task counts.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<LabelInfo[]>
```

## showLabelTasks()

Show tasks with a specific label.

**Signature**

```typescript theme={null}
(label: string, cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## getLabelStats()

Get detailed label statistics.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<Record<string, unknown>>
```

## createStoreProvider()

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

**Signature**

```typescript theme={null}
(_engine?: "sqlite" | undefined, cwd?: string | undefined) => Promise<StoreProvider>
```

## getStore()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<StoreProvider>
```

## countJsonRecords()

Count records in JSON source files.

**Signature**

```typescript theme={null}
(cleoDir: string) => { tasks: number; archived: number; sessions: number; }
```

## migrateJsonToSqliteAtomic(cwd, tempDbPath, logger)

Migrate JSON data to SQLite with atomic rename pattern. Writes to a temporary database file first, then atomically renames.

**Signature**

```typescript theme={null}
(cwd?: string | undefined, tempDbPath?: string | undefined, logger?: MigrationLogger | undefined) => Promise<MigrationResult>
```

**Parameters**

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

**Returns** — Migration result

## migrateJsonToSqlite()

**Signature**

```typescript theme={null}
(cwd?: string | undefined, options?: MigrationOptions | undefined) => Promise<MigrationResult>
```

## exportToJson()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<{ tasks: Task[]; archived: Task[]; sessions: Session[]; }>
```

## repairMissingSizes()

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

**Signature**

```typescript theme={null}
(cwd: string | undefined, dryRun: boolean) => Promise<RepairAction>
```

## repairMissingCompletedAt()

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

**Signature**

```typescript theme={null}
(cwd: string | undefined, dryRun: boolean) => Promise<RepairAction>
```

## runAllRepairs()

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

**Signature**

```typescript theme={null}
(cwd: string | undefined, dryRun: boolean) => Promise<RepairAction[]>
```

## runUpgrade(, , , )

Run a full upgrade pass on the project .cleo/ directory.  Steps:   1. Pre-flight storage check (JSON → SQLite)   2. If migration needed and not dry-run, run auto-migration with backup   3. Schema version checks on JSON files   4. Structural repairs (checksums, missing fields)

**Signature**

```typescript theme={null}
(options?: { dryRun?: boolean | undefined; includeGlobal?: boolean | undefined; autoMigrate?: boolean | undefined; cwd?: string | undefined; }) => Promise<UpgradeResult>
```

**Parameters**

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

**Signature**

```typescript theme={null}
typeof VerificationGate
```

**Methods**

### verifyOperation()

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

```typescript theme={null}
(context: OperationContext) => Promise<VerificationResult>
```

### runLayer()

Run a single validation layer with timing

```typescript theme={null}
(layer: GateLayer, validator: () => Promise<LayerResult>) => Promise<LayerResult>
```

### buildSuccessResult()

Build success result when all gates pass

```typescript theme={null}
(layers: Record<GateLayer, LayerResult>) => VerificationResult
```

### buildFailureResult()

Build failure result when a gate fails

```typescript theme={null}
(layers: Record<GateLayer, LayerResult>, blockedAt: GateLayer) => VerificationResult
```

### determineSemanticExitCode()

Determine semantic layer exit code from violations

```typescript theme={null}
(violations: GateViolation[]) => ProtocolExitCode
```

### determineReferentialExitCode()

Determine referential layer exit code from violations

```typescript theme={null}
(violations: GateViolation[]) => ProtocolExitCode
```

### determineProtocolExitCode()

Determine protocol layer exit code from violations

```typescript theme={null}
(violations: GateViolation[]) => ProtocolExitCode
```

### requiresValidation()

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

```typescript theme={null}
(context: OperationContext) => boolean
```

### getLayerName()

Get human-readable layer name

```typescript theme={null}
(layer: GateLayer) => string
```

## createVerificationGate()

Factory function for creating verification gates

**Signature**

```typescript theme={null}
(strictMode?: boolean) => VerificationGate
```

## WorkflowGateTracker

WorkflowGateTracker  Tracks the status of all 6 workflow verification gates for a task. Implements Section 7.4 failure cascade behavior: when a gate fails, all downstream gates reset to null.   T3141

**Signature**

```typescript theme={null}
typeof WorkflowGateTracker
```

**Methods**

### getGateStatus()

Get the status of a specific gate

```typescript theme={null}
(gateName: WorkflowGateName) => WorkflowGateStatus
```

### getGateState()

Get the full state of a specific gate

```typescript theme={null}
(gateName: WorkflowGateName) => WorkflowGateState | undefined
```

### getAllGates()

Get all gate states

```typescript theme={null}
() => WorkflowGateState[]
```

### canAttempt()

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

```typescript theme={null}
(gateName: WorkflowGateName) => boolean
```

### passGate()

Mark a gate as passed.

```typescript theme={null}
(gateName: WorkflowGateName, agent?: string | undefined) => boolean
```

### failGate()

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

```typescript theme={null}
(gateName: WorkflowGateName, reason?: string | undefined) => boolean
```

### cascadeReset()

Reset a gate and all downstream gates to null.

```typescript theme={null}
(failedGateName: WorkflowGateName) => void
```

### updateBlockedStatus()

Update blocked status for all gates based on current state.

```typescript theme={null}
() => void
```

### allPassed()

Check if all gates have passed

```typescript theme={null}
() => boolean
```

### getPendingGates()

Get all gates that are currently blocked or have null status

```typescript theme={null}
() => WorkflowGateState[]
```

### getNextAttemptable()

Get the next gate that can be attempted

```typescript theme={null}
() => WorkflowGateName | null
```

### getDownstreamGates()

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

```typescript theme={null}
(gateName: WorkflowGateName) => WorkflowGateName[]
```

### toRecord()

Serialize gate states to a plain record

```typescript theme={null}
() => Record<string, WorkflowGateStatus>
```

### fromRecord()

Restore gate states from a record

```typescript theme={null}
(record: Record<string, WorkflowGateStatus>) => void
```

### isValidGate()

Check if a gate name is valid

```typescript theme={null}
(gateName: WorkflowGateName) => boolean
```

## isValidWorkflowGateName()

Validate a workflow gate name string

**Signature**

```typescript theme={null}
(name: string) => name is WorkflowGateName
```

## getWorkflowGateDefinition()

Get the definition for a workflow gate

**Signature**

```typescript theme={null}
(name: WorkflowGateName) => WorkflowGateDefinition | undefined
```

## validateLayer1Schema()

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

**Signature**

```typescript theme={null}
(context: OperationContext) => Promise<LayerResult>
```

## validateLayer2Semantic()

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

**Signature**

```typescript theme={null}
(context: OperationContext) => Promise<LayerResult>
```

## validateLayer3Referential()

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

**Signature**

```typescript theme={null}
(context: OperationContext) => Promise<LayerResult>
```

## validateLayer4Protocol()

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

**Signature**

```typescript theme={null}
(context: OperationContext, _enforcer: ProtocolEnforcer) => Promise<LayerResult>
```

## isFieldRequired()

Helper to check if a field is required for an operation

**Signature**

```typescript theme={null}
(domain: string, operation: string, field: string) => boolean
```

## validateWorkflowGateName()

Validate a workflow gate name   T3141

**Signature**

```typescript theme={null}
(name: string) => boolean
```

## validateWorkflowGateStatus()

Validate a workflow gate status value per Section 7.3   T3141

**Signature**

```typescript theme={null}
(status: unknown) => status is "failed" | "blocked" | "passed" | null
```

## validateWorkflowGateUpdate()

Validate a gate update operation.   T3141

**Signature**

```typescript theme={null}
(gateName: string, status: string, agent?: string | undefined, tracker?: WorkflowGateTracker | undefined) => GateViolation[]
```

## buildMcpInputSchema()

Build a JSON Schema `input_schema` object from an `OperationDef`.  Algorithm:  1. Iterate `def.params`  2. Skip params where `mcp.hidden === true`  3. Map ParamType → JSON Schema type  4. Collect names where `required === true` into `required[]`  5. Return  type: 'object', properties, required

**Signature**

```typescript theme={null}
(def: OperationDef) => JSONSchemaObject
```

## buildCommanderArgs()

Split `OperationDef.params` into positional arguments and option flags, suitable for Commander.js registration.  - `cli.positional === true` → goes into `positionals[]` - everything else with a `cli` key → goes into `options[]` - Params with no `cli` key → MCP-only; excluded from both arrays

**Signature**

```typescript theme={null}
(def: OperationDef) => CommanderArgSplit
```

## buildCommanderOptionString()

Build the Commander option string for a single non-positional ParamDef.  Examples:    name:'taskId', type:'string', cli:      → '--taskId '    name:'status', type:'string', cli:short:'-s', flag:'status'      → '-s, --status '    name:'dryRun', type:'boolean', cli:flag:'dry-run'      → '--dry-run'    name:'limit', type:'number', cli:      → '--limit '

**Signature**

```typescript theme={null}
(param: ParamDef) => string
```

## camelToKebab()

Convert a camelCase string to kebab-case. e.g. 'includeArchive' → 'include-archive'

**Signature**

```typescript theme={null}
(s: string) => string
```

## validateRequiredParamsDef()

Validates that all required parameters are present in the request. Returns an array of missing parameter names.  Replaces the old `requiredParams: string[]` check in registry.ts.

**Signature**

```typescript theme={null}
(def: OperationDef, params?: Record<string, unknown> | undefined) => string[]
```

## validateConsensusTask()

Validate consensus protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; votingMatrixFile?: string | undefined; }) => Promise<ValidationResult>
```

## checkConsensusManifest()

Validate consensus protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; votingMatrixFile?: string | undefined; }) => Promise<ValidationResult>
```

## validateContributionTask()

Validate contribution protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## checkContributionManifest()

Validate contribution protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## validateDecompositionTask()

Validate decomposition protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; epicId?: string | undefined; }) => Promise<ValidationResult>
```

## checkDecompositionManifest()

Validate decomposition protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; epicId?: string | undefined; }) => Promise<ValidationResult>
```

## validateImplementationTask()

Validate implementation protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## checkImplementationManifest()

Validate implementation protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## validateSpecificationTask()

Validate specification protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; specFile?: string | undefined; }) => Promise<ValidationResult>
```

## checkSpecificationManifest()

Validate specification protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; specFile?: string | undefined; }) => Promise<ValidationResult>
```

## validateSchema(schemaType, data)

Validate data against a CLEO schema

**Signature**

```typescript theme={null}
(schemaType: "config", data: unknown) => ValidationResult
```

**Parameters**

| Name         | Type       | Description                      |
| ------------ | ---------- | -------------------------------- |
| `schemaType` | `"config"` | Which schema to validate against |
| `data`       | `unknown`  | The data to validate             |

**Returns** — Validation result with errors if invalid

## validateTask(task)

Validate a single task object against the drizzle-zod insert schema. Uses drizzle-derived Zod schemas as the single source of truth for field-level constraints (pattern, length, enum).

**Signature**

```typescript theme={null}
(task: unknown) => ValidationResult
```

**Parameters**

| Name   | Type      | Description             |
| ------ | --------- | ----------------------- |
| `task` | `unknown` | Task object to validate |

**Returns** — Validation result

## clearSchemaCache()

Clear the schema cache (useful for testing)

**Signature**

```typescript theme={null}
() => void
```

## validateTitleDescription()

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

**Signature**

```typescript theme={null}
(title?: string | undefined, description?: string | undefined) => RuleViolation[]
```

## validateTimestamps()

Validate that timestamps are not in the future

**Signature**

```typescript theme={null}
(task: TaskLike) => RuleViolation[]
```

## validateIdUniqueness()

Validate ID uniqueness across all tasks (todo + archive)

**Signature**

```typescript theme={null}
(taskId: string, existingIds: Set<string>) => RuleViolation[]
```

## validateNoDuplicateDescription()

Validate no duplicate task descriptions

**Signature**

```typescript theme={null}
(description: string, existingDescriptions: string[], _excludeTaskId?: string | undefined) => RuleViolation[]
```

## validateHierarchy()

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

**Signature**

```typescript theme={null}
(parentId: string | null | undefined, tasks: { id: string; parentId?: string | null | undefined; type?: string | undefined; }[], _taskType?: string | undefined, limits?: { maxDepth?: number | undefined; maxSiblings?: number | undefined; } | undefined) => RuleViolation[]
```

## validateStatusTransition()

Validate status transition

**Signature**

```typescript theme={null}
(currentStatus: string, newStatus: string) => RuleViolation[]
```

## validateNewTask()

Run all validation rules on a task being created

**Signature**

```typescript theme={null}
(task: TaskLike, existingIds: Set<string>, existingDescriptions: string[], existingTasks: { id: string; parentId?: string | null | undefined; type?: string | undefined; }[], limits?: { ...; } | undefined) => RuleViolation[]
```

## hasErrors()

Check if violations contain any errors (not just warnings)

**Signature**

```typescript theme={null}
(violations: RuleViolation[]) => boolean
```

## coreValidateReport()

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

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<ValidateReportResult>
```

## coreValidateAndFix()

Run validation report, then apply data repairs for fixable issues. Calls runAllRepairs() from src/core/repair.ts (same repairs used by `upgrade`).  T4795

**Signature**

```typescript theme={null}
(projectRoot: string, dryRun?: boolean) => Promise<ValidateAndFixResult>
```

## coreValidateSchema()

Validate data against a schema type.  For SQLite-backed types (todo, archive, sessions, log), queries rows directly from SQLite and validates with drizzle-zod schemas. For config type, uses AJV against the JSON schema file. If raw `data` is provided, validates directly with AJV (backward compat).   T4786

**Signature**

```typescript theme={null}
(type: string, data: unknown, projectRoot: string) => Promise<{ type: string; valid: boolean; errors: unknown[]; errorCount: number; }>
```

## coreValidateTask()

Validate a single task against anti-hallucination rules.  T4786

**Signature**

```typescript theme={null}
(taskId: string, projectRoot: string) => Promise<{ taskId: string; valid: boolean; violations: RuleViolation[]; errorCount: number; warningCount: number; }>
```

## coreValidateProtocol()

Check basic protocol compliance for a task.  T4786

**Signature**

```typescript theme={null}
(taskId: string, protocolType: string | undefined, projectRoot: string) => Promise<{ taskId: string; protocolType: string; compliant: boolean; violations: { code: string; message: string; severity: string; }[]; }>
```

## coreValidateManifest()

Validate manifest JSONL entries for required fields.  T4786

**Signature**

```typescript theme={null}
(projectRoot: string) => { valid: boolean; totalEntries: number; validEntries: number; invalidEntries: number; errors: { line: number; entryId: string; errors: string[]; }[]; message?: string | undefined; }
```

## coreValidateOutput()

Validate an output file for required sections.  T4786

**Signature**

```typescript theme={null}
(filePath: string, taskId: string | undefined, projectRoot: string) => { filePath: string; valid: boolean; issues: { code: string; message: string; severity: string; }[]; fileSize: number; lineCount: number; }
```

## coreComplianceSummary()

Get aggregated compliance metrics.  T4786

**Signature**

```typescript theme={null}
(projectRoot: string) => { total: number; pass: number; fail: number; partial: number; passRate: number; byProtocol: Record<string, { pass: number; fail: number; partial: number; }>; }
```

## coreComplianceViolations()

List compliance violations.  T4786

**Signature**

```typescript theme={null}
(limit: number | undefined, projectRoot: string) => { violations: { timestamp: string; taskId: string; protocol: string; result: string; violations?: { code: string; message: string; severity: "error" | "warning"; }[] | undefined; }[]; total: number; }
```

## coreComplianceRecord()

Record a compliance check result to COMPLIANCE.jsonl.  T4786

**Signature**

```typescript theme={null}
(taskId: string, result: string, protocol: string | undefined, violations: { code: string; message: string; severity: "error" | "warning"; }[] | undefined, projectRoot: string) => { ...; }
```

## coreTestStatus()

Check test suite availability.  T4786

**Signature**

```typescript theme={null}
(projectRoot: string) => { batsTests: { available: boolean; directory: string | null; }; mcpTests: { available: boolean; directory: string | null; }; message: string; }
```

## coreCoherenceCheck()

Cross-validate task graph for consistency.  T4786

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ coherent: boolean; issues: CoherenceIssue[]; }>
```

## coreTestRun()

Execute test suite via subprocess.  T4786

**Signature**

```typescript theme={null}
(params: { scope?: string | undefined; pattern?: string | undefined; parallel?: boolean | undefined; } | undefined, projectRoot: string) => { ran: boolean; runner?: string | undefined; ... 5 more ...; message?: string | undefined; }
```

## coreBatchValidate()

Batch validate all tasks against schema and rules.  T4786

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<{ totalTasks: number; validTasks: number; invalidTasks: number; totalErrors: number; totalWarnings: number; results: { taskId: string; valid: boolean; errorCount: number; warningCount: number; violations: RuleViolation[]; }[]; }>
```

## coreTestCoverage()

Get test coverage metrics.  T4786

**Signature**

```typescript theme={null}
(projectRoot: string) => { [key: string]: unknown; available: boolean; message?: string | undefined; }
```

## buildBrainState()

Build brain state for agent bootstrapping.

**Signature**

```typescript theme={null}
(projectRoot: string, opts?: { speed?: "full" | "fast" | "complete" | undefined; } | undefined, accessor?: DataAccessor | undefined) => Promise<BrainState>
```

## getCriticalPath()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined, accessor?: DataAccessor | undefined) => Promise<CriticalPathResult>
```

## resolveSkillPathsForProvider(providerId, scope, projectRoot)

Get effective skill paths for a provider considering precedence

**Signature**

```typescript theme={null}
(providerId: string, scope: "global" | "project", projectRoot?: string | undefined) => Promise<ResolvedSkillPath[]>
```

**Parameters**

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

**Returns** — Array of resolved skill paths with precedence information

**Throws**

* Error if provider not found

## getProvidersWithPrecedence(precedence)

Get all providers that use a specific precedence mode

**Signature**

```typescript theme={null}
(precedence: SkillsPrecedence) => string[]
```

**Parameters**

| Name         | Type               | Description                      |
| ------------ | ------------------ | -------------------------------- |
| `precedence` | `SkillsPrecedence` | The precedence mode to filter by |

**Returns** — Array of provider IDs using the specified precedence

## getSkillsMapWithPrecedence()

Build complete skills map with precedence information

**Signature**

```typescript theme={null}
() => { providerId: string; toolName: string; precedence: SkillsPrecedence; paths: { global: string | null; project: string | null; }; }[]
```

**Returns** — Array of provider skill configurations with precedence data

## determineInstallationTargets(context)

Determine target installation paths for a skill

**Signature**

```typescript theme={null}
(context: SkillInstallationContext) => Promise<{ providerId: string; path: string; }[]>
```

**Parameters**

| Name      | Type                       | Description                                                          |
| --------- | -------------------------- | -------------------------------------------------------------------- |
| `context` | `SkillInstallationContext` | The installation context including target providers and project root |

**Returns** — Array of installation targets with provider ID and path

## supportsAgentsPath(providerId)

Check if provider supports agents path

**Signature**

```typescript theme={null}
(providerId: string) => Promise<boolean>
```

**Parameters**

| Name         | Type     | Description                     |
| ------------ | -------- | ------------------------------- |
| `providerId` | `string` | The ID of the provider to check |

**Returns** — True if provider has agents path configuration

## coreTaskPlan()

Build composite planning view.  T4914

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<PlanResult>
```

## buildIndex(cwd)

Scan .cleo/rcasd/ and legacy .cleo/rcsd/ directories and build the RCASD index.  Reads all \_manifest.json files and any spec/report markdown files to produce a complete index.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => RcasdIndex
```

**Parameters**

| Name  | Type                    | Description       |
| ----- | ----------------------- | ----------------- |
| `cwd` | `: string \| undefined` | Working directory |

**Returns** — Populated RcasdIndex  T4801

## writeIndex(index, cwd)

Write RCASD-INDEX.json to disk.

**Signature**

```typescript theme={null}
(index: RcasdIndex, cwd?: string | undefined) => void
```

**Parameters**

| Name    | Type                    | Description              |
| ------- | ----------------------- | ------------------------ |
| `index` | `RcasdIndex`            | The index to write       |
| `cwd`   | `: string \| undefined` | Working directory  T4801 |

## readIndex(cwd)

Read RCASD-INDEX.json from disk.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => RcasdIndex | null
```

**Parameters**

| Name  | Type                    | Description       |
| ----- | ----------------------- | ----------------- |
| `cwd` | `: string \| undefined` | Working directory |

**Returns** — The index or null if not found  T4801

## rebuildIndex(cwd)

Rebuild and write the index from current disk state.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => RcasdIndex
```

**Parameters**

| Name  | Type                    | Description       |
| ----- | ----------------------- | ----------------- |
| `cwd` | `: string \| undefined` | Working directory |

**Returns** — The rebuilt index  T4801

## getTaskAnchor(taskId, cwd)

Get task anchor by task ID.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => TaskAnchor | null
```

**Parameters**

| Name     | Type                    | Description            |
| -------- | ----------------------- | ---------------------- |
| `taskId` | `string`                | The task ID to look up |
| `cwd`    | `: string \| undefined` | Working directory      |

**Returns** — TaskAnchor or null  T4801

## findByStage(stage, cwd)

Find tasks by pipeline stage.

**Signature**

```typescript theme={null}
(stage: string, cwd?: string | undefined) => [string, TaskAnchor][]
```

**Parameters**

| Name    | Type                    | Description                     |
| ------- | ----------------------- | ------------------------------- |
| `stage` | `string`                | The pipeline stage to filter by |
| `cwd`   | `: string \| undefined` | Working directory               |

**Returns** — Array of \[taskId, anchor] pairs  T4801

## findByStatus(status, cwd)

Find tasks by status.

**Signature**

```typescript theme={null}
(status: "completed" | "failed" | "active" | "archived" | "paused", cwd?: string | undefined) => [string, TaskAnchor][]
```

**Parameters**

| Name     | Type                                                            | Description             |
| -------- | --------------------------------------------------------------- | ----------------------- |
| `status` | `"completed" \| "failed" \| "active" \| "archived" \| "paused"` | The status to filter by |
| `cwd`    | `: string \| undefined`                                         | Working directory       |

**Returns** — Array of \[taskId, anchor] pairs  T4801

## getIndexTotals(cwd)

Get index summary statistics.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => IndexTotals | null
```

**Parameters**

| Name  | Type                    | Description       |
| ----- | ----------------------- | ----------------- |
| `cwd` | `: string \| undefined` | Working directory |

**Returns** — Index totals or null  T4801

## generateCodebaseMapSummary()

**Signature**

```typescript theme={null}
(result: CodebaseMapResult) => string
```

## sequenceChains()

Sequence two chains: connect A's exit points to B's entry point.  B's stage IDs are prefixed with "b" to avoid collision with A. The result is validated and throws if invalid.   T5406

**Signature**

```typescript theme={null}
(a: WarpChain, b: WarpChain) => WarpChain
```

## parallelChains()

Compose chains in parallel with a common fork entry and join stage.  Creates a fork entry stage that links to each chain's entry, and all chain exits link to the provided joinStage.  Each chain's IDs are prefixed with "pindex" to avoid collisions.   T5406

**Signature**

```typescript theme={null}
(chains: WarpChain[], joinStage: WarpStage) => WarpChain
```

## resolveEpicFromContent()

Extract an epic/task ID from file content by searching for:   1. `@task T####` or `@epic T####` annotations (highest priority)   2. JSON `"task"`, `"epicId"`, or `"taskId"` fields   3. First `T####` at a word boundary (fallback)

**Signature**

```typescript theme={null}
(content: string) => string | null
```

## resolveEpicFromFilename()

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

**Signature**

```typescript theme={null}
(filename: string) => string | null
```

## normalizeDirectoryNames()

Rename suffixed epic directories (e.g. `T4881_install-channels` → `T4881`).

**Signature**

```typescript theme={null}
(options?: ConsolidateOptions) => MoveRecord[]
```

## migrateConsensusFiles()

Migrate `.cleo/consensus/` files to appropriate epic's consensus/ subdirectory.  - T4869-checkpoint-consensus.json → rcasd/T4869/consensus/ - Agent finding files and CONSENSUS-REPORT.md → resolve epic from content - phase1-best-practices-evidence.md → resolve epic from content → research/

**Signature**

```typescript theme={null}
(options?: ConsolidateOptions) => MoveRecord[]
```

## migrateContributionFiles()

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

**Signature**

```typescript theme={null}
(options?: ConsolidateOptions) => MoveRecord[]
```

## migrateLooseFiles()

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

**Signature**

```typescript theme={null}
(options?: ConsolidateOptions) => MoveRecord[]
```

## consolidateRcasd(, )

Consolidate all provenance files into the unified `.cleo/rcasd/\{epicId\}/` structure with stage subdirectories.  Performs migrations in order:   1. Rename suffixed directories (T4881\_install-channels → T4881)   2. Move consensus files to appropriate epic's consensus/ subdirectory   3. Move contribution files to appropriate epic's contributions/ subdirectory   4. Move loose research files to appropriate epic's research/ subdirectory

**Signature**

```typescript theme={null}
(options?: ConsolidateOptions) => MigrationResult
```

**Parameters**

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

```typescript theme={null}
(taskId: string, options?: InitializePipelineOptions) => Promise<Pipeline>
```

**Parameters**

| Name      | Type                          | Description                 |
| --------- | ----------------------------- | --------------------------- |
| `taskId`  | `string`                      | The task ID (e.g., 'T4800') |
| `options` | `: InitializePipelineOptions` | Optional configuration      |

**Returns** — Promise resolving to the created Pipeline

**Throws**

* CleoError If pipeline already exists or database operation fails

**Example**

```typescript theme={null}
const pipeline = await initializePipeline('T4800', {
  startStage: 'research',
  assignedAgent: 'agent-001'
});
console.log(`Pipeline initialized: ${pipeline.id}`);
```

## getPipeline(taskId)

Retrieve a pipeline by task ID.  Returns the complete pipeline state including current stage and status. Returns null if no pipeline exists for the given task ID.

**Signature**

```typescript theme={null}
(taskId: string) => Promise<Pipeline | null>
```

**Parameters**

| Name     | Type     | Description                 |
| -------- | -------- | --------------------------- |
| `taskId` | `string` | The task ID (e.g., 'T4800') |

**Returns** — Promise resolving to Pipeline or null

**Throws**

* CleoError If database query fails

**Example**

```typescript theme={null}
const pipeline = await getPipeline('T4800');
if (pipeline) {
  console.log(`Current stage: ${pipeline.currentStage}`);
}
```

## advanceStage(taskId, options)

Advance a pipeline to the next stage.  Performs atomic stage transition with prerequisite checking and audit logging. Validates the transition is allowed, updates stage statuses, and records the transition in the audit trail.

**Signature**

```typescript theme={null}
(taskId: string, options: AdvanceStageOptions) => Promise<void>
```

**Parameters**

| Name      | Type                  | Description                                       |
| --------- | --------------------- | ------------------------------------------------- |
| `taskId`  | `string`              | The task ID                                       |
| `options` | `AdvanceStageOptions` | Advance options including target stage and reason |

**Returns** — Promise resolving when transition is complete

**Throws**

* CleoError If transition is invalid or prerequisites not met

**Example**

```typescript theme={null}
await advanceStage('T4800', {
  toStage: 'consensus',
  reason: 'Research completed, moving to consensus',
  initiatedBy: 'agent-001'
});
```

## getCurrentStage(taskId)

Get the current stage of a pipeline.  Convenience method to quickly check which stage a task is currently in.

**Signature**

```typescript theme={null}
(taskId: string) => Promise<"research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release">
```

**Parameters**

| Name     | Type     | Description |
| -------- | -------- | ----------- |
| `taskId` | `string` | The task ID |

**Returns** — Promise resolving to the current Stage

**Throws**

* CleoError If database query fails

**Example**

```typescript theme={null}
const currentStage = await getCurrentStage('T4800');
if (currentStage === 'validation') {
  console.log('Task is in verification');
}
```

## listPipelines(options)

List pipelines with optional filtering.

**Signature**

```typescript theme={null}
(options?: PipelineQueryOptions) => Promise<Pipeline[]>
```

**Parameters**

| Name      | Type                     | Description                                |
| --------- | ------------------------ | ------------------------------------------ |
| `options` | `: PipelineQueryOptions` | Query options for filtering and pagination |

**Returns** — Promise resolving to array of Pipelines

**Throws**

* CleoError If database query fails

**Example**

```typescript theme={null}
const activePipelines = await listPipelines({
  status: 'active',
  limit: 10
});
```

## completePipeline(taskId, \_reason)

Complete a pipeline (mark all stages done).  Marks the pipeline as completed and sets the completion timestamp. Only valid when the pipeline is in the 'release' stage.

**Signature**

```typescript theme={null}
(taskId: string, _reason?: string | undefined) => Promise<void>
```

**Parameters**

| Name      | Type                    | Description                                                |
| --------- | ----------------------- | ---------------------------------------------------------- |
| `taskId`  | `string`                | The task ID                                                |
| `_reason` | `: string \| undefined` | Optional completion reason (unused, for API compatibility) |

**Returns** — Promise resolving when complete   T4800  T4912 - Implemented SQLite wiring

**Throws**

* CleoError If pipeline not found or not in releasable state

## cancelPipeline(taskId, reason)

Cancel a pipeline before completion.  Marks the pipeline as cancelled (user-initiated). Once cancelled, the pipeline cannot be resumed (a new one must be created). Use this for deliberate user decisions to abandon a pipeline. System-forced terminations should use the 'aborted' status directly.

**Signature**

```typescript theme={null}
(taskId: string, reason: string) => Promise<void>
```

**Parameters**

| Name     | Type     | Description             |
| -------- | -------- | ----------------------- |
| `taskId` | `string` | The task ID             |
| `reason` | `string` | Reason for cancellation |

**Returns** — Promise resolving when cancelled   T4800  T4912 - Implemented SQLite wiring

**Throws**

* CleoError If pipeline not found or already completed

## pipelineExists(taskId)

Check if a pipeline exists for a task.

**Signature**

```typescript theme={null}
(taskId: string) => Promise<boolean>
```

**Parameters**

| Name     | Type     | Description |
| -------- | -------- | ----------- |
| `taskId` | `string` | The task ID |

**Returns** — Promise resolving to boolean   T4800  T4912 - Implemented SQLite wiring

## getPipelineStatistics()

Get pipeline statistics.  Returns aggregate counts of pipelines by status and stage.

**Signature**

```typescript theme={null}
() => Promise<{ total: number; byStatus: Record<"completed" | "failed" | "cancelled" | "active" | "blocked" | "aborted", number>; byStage: Partial<Record<"research" | "consensus" | "architecture_decision" | ... 5 more ... | "release", number>>; }>
```

**Returns** — Promise resolving to statistics object   T4800  T4912 - Implemented SQLite wiring

**Throws**

* CleoError If database query fails

## getPipelineStages(taskId)

Get all stages for a pipeline.

**Signature**

```typescript theme={null}
(taskId: string) => Promise<PipelineStageRecord[]>
```

**Parameters**

| Name     | Type     | Description |
| -------- | -------- | ----------- |
| `taskId` | `string` | The task ID |

**Returns** — Promise resolving to array of stage records   T4912

## findResumablePipelines(options, cwd)

Query active pipelines that can be resumed.  Searches the lifecycle\_pipelines table for pipelines with status 'active' and joins with lifecycle\_stages to determine current stage status. Also joins with tasks table to get task metadata.

**Signature**

```typescript theme={null}
(options?: FindResumableOptions, cwd?: string | undefined) => Promise<ResumablePipeline[]>
```

**Parameters**

| Name      | Type                     | Description                    |
| --------- | ------------------------ | ------------------------------ |
| `options` | `: FindResumableOptions` | Query options for filtering    |
| `cwd`     | `: string \| undefined`  | Working directory for database |

**Returns** — Promise resolving to array of resumable pipelines

**Example**

```typescript theme={null}
// Find all active pipelines
const resumable = await findResumablePipelines();

// Find specific tasks
const specific = await findResumablePipelines({
  taskIds: ['T4805', 'T4806']
});

// Include blocked pipelines
const withBlocked = await findResumablePipelines({
  includeBlocked: true
});
```

## loadPipelineContext(taskId, cwd)

Load complete pipeline context for session resume.  Uses SQL JOINs to efficiently load all related data: - Pipeline and current stage - All stages with their status - Gate results for current stage - Evidence linked to current stage - Recent transitions - Task details

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<PipelineContext>
```

**Parameters**

| Name     | Type                    | Description                     |
| -------- | ----------------------- | ------------------------------- |
| `taskId` | `string`                | The task ID to load context for |
| `cwd`    | `: string \| undefined` | Working directory for database  |

**Returns** — Promise resolving to pipeline context

**Example**

```typescript theme={null}
const context = await loadPipelineContext('T4805');
console.log(`Current stage: ${context.currentStage}`);
console.log(`Stage status: ${context.stages.find(s => s.stage === context.currentStage)?.status}`);
```

## resumeStage(taskId, targetStage, options, cwd)

Resume a specific stage in a pipeline.  Updates the stage status from 'blocked' or 'not\_started' to 'in\_progress', records the transition, and returns the resume result.

**Signature**

```typescript theme={null}
(taskId: string, targetStage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", options?: { ...; }, cwd?: string | undefined) => Promise<...>
```

**Parameters**

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

**Returns** — Promise resolving to resume result

**Example**

```typescript theme={null}
const result = await resumeStage('T4805', 'implement');
if (result.success) {
  console.log(`Resumed ${result.taskId} at ${result.stage}`);
}
```

## autoResume(cwd)

Auto-detect where to resume across all active pipelines.  Finds the best candidate for resuming work based on: 1. Active stages (currently in progress) 2. Blocked stages (can be unblocked) 3. Failed stages (can be retried) 4. Priority ordering

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<AutoResumeResult>
```

**Parameters**

| Name  | Type                    | Description                    |
| ----- | ----------------------- | ------------------------------ |
| `cwd` | `: string \| undefined` | Working directory for database |

**Returns** — Promise resolving to auto-resume result

**Example**

```typescript theme={null}
const result = await autoResume();
if (result.canResume) {
  console.log(`Recommended: Resume ${result.taskId} at ${result.stage}`);
} else if (result.options && result.options.length > 0) {
  console.log('Multiple options available:', result.options);
}
```

## checkSessionResume(options, cwd)

Check for resumable work on session start.  Integrates with session initialization to check for active pipelines and present resumable work to the user. Can auto-resume if there's a clear single candidate.

**Signature**

```typescript theme={null}
(options?: SessionResumeCheckOptions, cwd?: string | undefined) => Promise<SessionResumeCheckResult>
```

**Parameters**

| Name      | Type                          | Description                    |
| --------- | ----------------------------- | ------------------------------ |
| `options` | `: SessionResumeCheckOptions` | Resume check options           |
| `cwd`     | `: string \| undefined`       | Working directory for database |

**Returns** — Promise resolving to resume check result

**Example**

```typescript theme={null}
// On session start
const resumeCheck = await checkSessionResume({ autoResume: true });
if (resumeCheck.didResume) {
  console.log(`Auto-resumed ${resumeCheck.resumedTaskId}`);
} else if (resumeCheck.requiresUserChoice) {
  console.log('Multiple options:', resumeCheck.options);
}
```

## formatResumeSummary(pipelines)

Get resume summary for display to user.  Formats resumable pipelines into a human-readable summary.

**Signature**

```typescript theme={null}
(pipelines: ResumablePipeline[]) => string
```

**Parameters**

| Name        | Type                  | Description         |
| ----------- | --------------------- | ------------------- |
| `pipelines` | `ResumablePipeline[]` | Resumable pipelines |

**Returns** — Formatted summary string   T4805

## handleCompletedStage(context)

Handle completed stage edge case.  If the current stage is completed, suggests advancing to next stage.

**Signature**

```typescript theme={null}
(context: PipelineContext) => { action: "review" | "advance" | "stay"; message: string; nextStage?: "research" | "consensus" | "architecture_decision" | "specification" | ... 5 more ... | undefined; }
```

**Parameters**

| Name      | Type              | Description      |
| --------- | ----------------- | ---------------- |
| `context` | `PipelineContext` | Pipeline context |

**Returns** — Recommendation for handling completed stage   T4805

## handleBlockedStage(context)

Handle blocked stage edge case.  Provides information about why a stage is blocked and potential resolutions.

**Signature**

```typescript theme={null}
(context: PipelineContext) => { isBlocked: boolean; blockReason?: string | undefined; blockedSince?: Date | undefined; resolutions: string[]; canUnblock: boolean; }
```

**Parameters**

| Name      | Type              | Description      |
| --------- | ----------------- | ---------------- |
| `context` | `PipelineContext` | Pipeline context |

**Returns** — Block analysis and resolution hints   T4805

## checkBlockedStageDetails(taskId, cwd)

Handle blocked stage edge case - async version with database lookup.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<{ isBlocked: boolean; blockReason?: string | undefined; blockedSince?: Date | undefined; resolutions: string[]; canUnblock: boolean; prerequisites?: { ...; }[] | undefined; }>
```

**Parameters**

| Name     | Type                    | Description       |
| -------- | ----------------------- | ----------------- |
| `taskId` | `string`                | Task ID to check  |
| `cwd`    | `: string \| undefined` | Working directory |

**Returns** — Block analysis with prerequisite details   T4805

## checkPrerequisites(targetStage, currentStages)

Check if prerequisites are met for a stage.  Validates that all prerequisite stages are in an acceptable state (completed or skipped) for the target stage to proceed.

**Signature**

```typescript theme={null}
(targetStage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", currentStages: Record<"research" | ... 7 more ... | "release", StageState>) => Promise<...>
```

**Parameters**

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

**Returns** — Promise resolving to PrereqCheck result

**Throws**

* CleoError If validation fails

**Example**

```typescript theme={null}
const check = await checkPrerequisites('implement', {
  research: { status: 'completed' },
  spec: { status: 'completed' },
  decompose: { status: 'completed' },
  // ... other stages
});
if (check.met) {
  console.log('Ready to implement');
}
```

## validateTransition(transition, context)

Validate a stage transition.  Comprehensive validation that checks both transition rules and prerequisites. This is the core state machine validation logic.

**Signature**

```typescript theme={null}
(transition: StateTransition, context: StateMachineContext) => Promise<TransitionValidation>
```

**Parameters**

| Name         | Type                  | Description                   |
| ------------ | --------------------- | ----------------------------- |
| `transition` | `StateTransition`     | The transition to validate    |
| `context`    | `StateMachineContext` | Current state machine context |

**Returns** — Promise resolving to TransitionValidation

**Throws**

* CleoError If validation fails unexpectedly

**Example**

```typescript theme={null}
const validation = await validateTransition(
  { from: 'spec', to: 'implement', initiatedBy: 'agent-001' },
  pipelineContext
);
if (!validation.valid) {
  console.log(validation.errors);
}
```

## executeTransition(transition, context)

Execute a state transition.  Applies the transition to the state machine context, updating stage statuses and returning the new state. This function does NOT persist to database - that is handled by the pipeline module.

**Signature**

```typescript theme={null}
(transition: StateTransition, context: StateMachineContext) => Promise<StateTransitionResult>
```

**Parameters**

| Name         | Type                  | Description                   |
| ------------ | --------------------- | ----------------------------- |
| `transition` | `StateTransition`     | The transition to execute     |
| `context`    | `StateMachineContext` | Current state machine context |

**Returns** — Promise resolving to StateTransitionResult

**Throws**

* CleoError If transition is invalid

**Example**

```typescript theme={null}
const result = await executeTransition(
  { from: 'spec', to: 'implement', initiatedBy: 'agent-001' },
  pipelineContext
);
if (result.success) {
  console.log(`Transitioned to ${result.newState.stage}`);
}
```

## setStageStatus(stage, status, context)

Set the status of a stage.  Updates stage status with validation of allowed state transitions.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", status: "completed" | ... 4 more ... | "skipped", context: StateMachineContext) => StageState
```

**Parameters**

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

**Returns** — Updated StageState   T4800

**Throws**

* CleoError If status transition is invalid

## getStageStatus(stage, context)

Get the status of a stage.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", context: StateMachineContext) => "completed" | ... 4 more ... | "skipped"
```

**Parameters**

| Name      | Type                                                                                                                                                       | Description                   |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `stage`   | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | The stage to check            |
| `context` | `StateMachineContext`                                                                                                                                      | Current state machine context |

**Returns** — The stage status   T4800

## isValidStatusTransition(from, to)

Check if a status transition is valid.  State transitions:   not\_started → in\_progress, skipped   in\_progress → completed, blocked, failed   blocked     → in\_progress   failed      → in\_progress (retry)   completed   → (no transition - use force to override)   skipped     → (no transition)

**Signature**

```typescript theme={null}
(from: "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped", to: "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped") => { ...; }
```

**Parameters**

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

**Returns** — Object with valid flag and reason   T4800

## createInitialContext(pipelineId, assignedAgent)

Create initial state machine context for a pipeline.

**Signature**

```typescript theme={null}
(pipelineId: string, assignedAgent?: string | undefined) => StateMachineContext
```

**Parameters**

| Name            | Type                    | Description              |
| --------------- | ----------------------- | ------------------------ |
| `pipelineId`    | `string`                | The pipeline/task ID     |
| `assignedAgent` | `: string \| undefined` | Optional agent to assign |

**Returns** — Initial StateMachineContext   T4800

## getValidNextStages(context, includeForce)

Get stages that can be transitioned to from the current stage.

**Signature**

```typescript theme={null}
(context: StateMachineContext, includeForce?: boolean) => ("research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release")[]
```

**Parameters**

| Name           | Type                  | Description                                       |
| -------------- | --------------------- | ------------------------------------------------- |
| `context`      | `StateMachineContext` | Current state machine context                     |
| `includeForce` | `: boolean`           | Whether to include transitions that require force |

**Returns** — Array of valid next stages   T4800

## getCurrentStageState(context)

Get the current stage state.

**Signature**

```typescript theme={null}
(context: StateMachineContext) => StageState
```

**Parameters**

| Name      | Type                  | Description           |
| --------- | --------------------- | --------------------- |
| `context` | `StateMachineContext` | State machine context |

**Returns** — Current StageState   T4800

## isTerminalState(context)

Check if the pipeline is in a terminal state.

**Signature**

```typescript theme={null}
(context: StateMachineContext) => boolean
```

**Parameters**

| Name      | Type                  | Description           |
| --------- | --------------------- | --------------------- |
| `context` | `StateMachineContext` | State machine context |

**Returns** — True if in release stage and completed   T4800

## isBlocked(context)

Check if the pipeline is blocked.

**Signature**

```typescript theme={null}
(context: StateMachineContext) => boolean
```

**Parameters**

| Name      | Type                  | Description           |
| --------- | --------------------- | --------------------- |
| `context` | `StateMachineContext` | State machine context |

**Returns** — True if current stage is blocked   T4800

## validateTransitions(transitions, context)

Validate multiple transitions.

**Signature**

```typescript theme={null}
(transitions: StateTransition[], context: StateMachineContext) => Promise<TransitionValidation[]>
```

**Parameters**

| Name          | Type                  | Description                      |
| ------------- | --------------------- | -------------------------------- |
| `transitions` | `StateTransition[]`   | Array of transitions to validate |
| `context`     | `StateMachineContext` | State machine context            |

**Returns** — Array of validation results   T4800

## canSkipStage(stage)

Check if a stage can be skipped.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release") => boolean
```

**Parameters**

| Name    | Type                                                                                                                                                       | Description        |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| `stage` | `"research" \| "consensus" \| "architecture_decision" \| "specification" \| "decomposition" \| "implementation" \| "validation" \| "testing" \| "release"` | The stage to check |

**Returns** — True if stage is skippable   T4800

## skipStage(stage, reason, context)

Skip a stage with validation.

**Signature**

```typescript theme={null}
(stage: "research" | "consensus" | "architecture_decision" | "specification" | "decomposition" | "implementation" | "validation" | "testing" | "release", _reason: string, context: StateMachineContext) => StageState
```

**Parameters**

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

**Returns** — Updated StageState   T4800

**Throws**

* CleoError If stage cannot be skipped

## getContextStatusFromPercentage()

Determine status from percentage.

**Signature**

```typescript theme={null}
(percentage: number) => ContextStatus
```

## processContextInput()

Process context window input and write state file. Returns the status line string for display.  Tries adapter-based context monitoring first; falls back to local implementation.

**Signature**

```typescript theme={null}
(input: ContextWindowInput, cwd?: string | undefined) => Promise<string>
```

## isHITLEnabled()

Check if HITL warnings are enabled.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => boolean
```

## generateHITLWarnings()

Generate HITL warnings based on lock state.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => HITLWarningsResult
```

## getHighestLevel()

Get highest warning level from warnings.

**Signature**

```typescript theme={null}
(warnings: HITLWarning[]) => HITLLevel
```

## getConcurrencyJson()

Get concurrency data for analyze JSON output.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Record<string, unknown>
```

## getEnforcementMode()

Get the current enforcement mode.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => EnforcementMode
```

## isSessionEnforcementEnabled()

Check if session enforcement is enabled.

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => boolean
```

## getActiveSessionInfo()

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

**Signature**

```typescript theme={null}
(cwd?: string | undefined) => Promise<ActiveSessionInfo | null>
```

## requireActiveSession()

Require an active session for write operations. In strict mode, throws if no session is active. In warn mode, returns a warning but allows the operation. In none mode, always allows.

**Signature**

```typescript theme={null}
(operation: string, cwd?: string | undefined) => Promise<EnforcementResult>
```

## validateTaskInScope()

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

**Signature**

```typescript theme={null}
(taskId: string, taskEpicId?: string | undefined, cwd?: string | undefined) => Promise<{ inScope: boolean; warning?: string | undefined; }>
```

## checkStatuslineIntegration()

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

**Signature**

```typescript theme={null}
() => StatuslineStatus
```

## getStatuslineConfig()

Get the statusline setup command for Claude Code settings.

**Signature**

```typescript theme={null}
() => Record<string, unknown>
```

## getSetupInstructions()

Get human-readable setup instructions.

**Signature**

```typescript theme={null}
() => string
```

## getPreferredChannel(domain, operation)

Look up the preferred channel for a given domain + operation.

**Signature**

```typescript theme={null}
(domain: string, operation: string) => "cli" | "mcp" | "either"
```

**Parameters**

| Name        | Type     | Description    |
| ----------- | -------- | -------------- |
| `domain`    | `string` | Domain name    |
| `operation` | `string` | Operation name |

**Returns** — Preferred channel ('mcp', 'cli', or 'either' as fallback)

## getRoutingForDomain(domain)

Get routing entries for a specific domain.

**Signature**

```typescript theme={null}
(domain: string) => RoutingEntry[]
```

**Parameters**

| Name     | Type     | Description |
| -------- | -------- | ----------- |
| `domain` | `string` | Domain name |

**Returns** — All routing entries for the domain

## getOperationsByChannel(channel)

Get all operations that prefer a specific channel.

**Signature**

```typescript theme={null}
(channel: "cli" | "mcp" | "either") => RoutingEntry[]
```

**Parameters**

| Name      | Type                         | Description                     |
| --------- | ---------------------------- | ------------------------------- |
| `channel` | `"cli" \| "mcp" \| "either"` | Channel preference to filter by |

**Returns** — Matching routing entries

## generateMemoryProtocol(context)

Generate dynamic memory protocol instructions based on provider capabilities.

**Signature**

```typescript theme={null}
(context: ProviderContext) => string
```

**Parameters**

| Name      | Type              | Description                 |
| --------- | ----------------- | --------------------------- |
| `context` | `ProviderContext` | Provider capability context |

**Returns** — Markdown content for memory protocol guidance

## generateRoutingGuide(context)

Generate a dynamic routing guide based on operation preferences.

**Signature**

```typescript theme={null}
(context: ProviderContext) => string
```

**Parameters**

| Name      | Type              | Description                 |
| --------- | ----------------- | --------------------------- |
| `context` | `ProviderContext` | Provider capability context |

**Returns** — Markdown content showing preferred channels per operation

## generateDynamicSkillContent(context)

Generate complete dynamic skill content for the current provider.

**Signature**

```typescript theme={null}
(context: ProviderContext) => string
```

**Parameters**

| Name      | Type              | Description                 |
| --------- | ----------------- | --------------------------- |
| `context` | `ProviderContext` | Provider capability context |

**Returns** — Complete dynamic skill markdown content

## TaskCache

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

**Signature**

```typescript theme={null}
typeof TaskCache
```

**Methods**

### computeChecksum()

Compute a checksum from task data for staleness detection.

```typescript theme={null}
(tasks: Task[]) => string
```

### init()

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

```typescript theme={null}
(tasks: Task[]) => boolean
```

### buildLabelIndex()

```typescript theme={null}
(tasks: Task[]) => void
```

### buildPhaseIndex()

```typescript theme={null}
(tasks: Task[]) => void
```

### buildHierarchyIndex()

```typescript theme={null}
(tasks: Task[]) => void
```

### getTasksByLabel()

Get task IDs by label.

```typescript theme={null}
(label: string) => string[]
```

### getTasksByPhase()

Get task IDs by phase.

```typescript theme={null}
(phase: string) => string[]
```

### getAllLabels()

Get all labels.

```typescript theme={null}
() => string[]
```

### getAllPhases()

Get all phases.

```typescript theme={null}
() => string[]
```

### getLabelCount()

Get label count for a specific label.

```typescript theme={null}
(label: string) => number
```

### getParent()

Get parent ID for a task.

```typescript theme={null}
(taskId: string) => string | null
```

### getChildren()

Get children IDs for a task.

```typescript theme={null}
(taskId: string) => string[]
```

### getDepth()

Get depth for a task.

```typescript theme={null}
(taskId: string) => number
```

### getChildCount()

Get child count.

```typescript theme={null}
(taskId: string) => number
```

### getRootTasks()

Get root tasks (no parent).

```typescript theme={null}
() => string[]
```

### getLeafTasks()

Get leaf tasks (no children).

```typescript theme={null}
() => string[]
```

### invalidate()

Force invalidation and rebuild.

```typescript theme={null}
() => void
```

### getStats()

Get cache statistics.

```typescript theme={null}
() => { initialized: boolean; labelCount: number; phaseCount: number; taskCount: number; maxDepth: number; }
```

## extractPackageMeta()

Extract package metadata from an export file.  T4552

**Signature**

```typescript theme={null}
(sourceFilePath: string) => Promise<ImportPackageMeta>
```

## logImportStart()

Log import operation start with package metadata.  T4552

**Signature**

```typescript theme={null}
(sourceFilePath: string, sessionId?: string | undefined, cwd?: string | undefined) => Promise<void>
```

## logImportSuccess()

Log import operation completion with full metadata.  T4552

**Signature**

```typescript theme={null}
(sourceFilePath: string, tasksImported: string[], idRemap: Record<string, string>, conflicts?: { type: string; resolution: string; }[] | undefined, options?: ImportOptions | undefined, sessionId?: string | undefined, cwd?: string | undefined) => Promise<...>
```

## logImportError()

Log import operation error with diagnostic details.  T4552

**Signature**

```typescript theme={null}
(sourceFilePath: string, errorMessage: string, errorCode: string | number, stage?: "validation" | "unknown" | "parsing" | "remapping" | "writing", sessionId?: string | undefined, cwd?: string | undefined) => Promise<...>
```

## logImportConflict()

Log import conflict detection and resolution.  T4552

**Signature**

```typescript theme={null}
(conflictType: ImportConflictType, taskId: string, conflictDetails: Record<string, unknown>, resolution: ImportConflictResolution, sessionId?: string | undefined, cwd?: string | undefined) => Promise<...>
```

## topologicalSortTasks()

Topological sort for task import order using Kahn's algorithm.  Ensures tasks are imported in dependency order: - Parents before children (parentId references) - Dependencies before dependents (depends\[] references) - Only counts edges to tasks within the set (external deps ignored)   T4552

**Signature**

```typescript theme={null}
(tasks: SortableTask[]) => string[]
```

## detectCycles()

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

**Signature**

```typescript theme={null}
(tasks: SortableTask[]) => boolean
```

## findActivePipelinesWithStagesAndTasks(taskIds, cwd)

Find active pipelines joined with their stages and tasks. Optionally filters by specific task IDs.

**Signature**

```typescript theme={null}
(taskIds?: string[] | undefined, cwd?: string | undefined) => Promise<PipelineStageTaskRow[]>
```

**Parameters**

| Name      | Type                      | Description                            |
| --------- | ------------------------- | -------------------------------------- |
| `taskIds` | `: string[] \| undefined` | Optional list of task IDs to filter by |
| `cwd`     | `: string \| undefined`   | Working directory for database         |

**Returns** — Rows with pipeline, stage, and task data

## findPipelineWithCurrentStageAndTask(taskId, cwd)

Find a pipeline with its current stage and task by taskId. Matches stages where stageName equals the pipeline's currentStageId.

**Signature**

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<PipelineStageTaskRow[]>
```

**Parameters**

| Name     | Type                    | Description                    |
| -------- | ----------------------- | ------------------------------ |
| `taskId` | `string`                | Task ID to look up             |
| `cwd`    | `: string \| undefined` | Working directory for database |

**Returns** — Matching rows (typically 0 or 1)

## findPipelineWithStage(taskId, stageName, cwd)

Find a pipeline and a specific stage by taskId and stageName.

**Signature**

```typescript theme={null}
(taskId: string, stageName: string, cwd?: string | undefined) => Promise<PipelineStageRow[]>
```

**Parameters**

| Name        | Type                    | Description                    |
| ----------- | ----------------------- | ------------------------------ |
| `taskId`    | `string`                | Task ID                        |
| `stageName` | `string`                | Stage name to match            |
| `cwd`       | `: string \| undefined` | Working directory for database |

**Returns** — Matching rows (typically 0 or 1)

## updatePipelineCurrentStage(pipelineId, currentStageId, cwd)

Update pipeline's currentStageId.

**Signature**

```typescript theme={null}
(pipelineId: string, currentStageId: string, cwd?: string | undefined) => Promise<void>
```

**Parameters**

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

```typescript theme={null}
(pipelineId: string, cwd?: string | undefined) => Promise<{ id: string; status: "completed" | "failed" | "blocked" | "not_started" | "in_progress" | "skipped"; notesJson: string | null; ... 15 more ...; provenanceChainJson: string | null; }[]>
```

**Parameters**

| Name         | Type                    | Description                    |
| ------------ | ----------------------- | ------------------------------ |
| `pipelineId` | `string`                | Pipeline ID                    |
| `cwd`        | `: string \| undefined` | Working directory for database |

**Returns** — All stage rows for the pipeline

## activateStage(stageId, startedAt, cwd)

Update a stage's status to 'in\_progress' and clear block fields.

**Signature**

```typescript theme={null}
(stageId: string, startedAt: string, cwd?: string | undefined) => Promise<void>
```

**Parameters**

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

```typescript theme={null}
(taskId: string, cwd?: string | undefined) => Promise<PipelineStageRow[]>
```

**Parameters**

| Name     | Type                    | Description                    |
| -------- | ----------------------- | ------------------------------ |
| `taskId` | `string`                | Task ID                        |
| `cwd`    | `: string \| undefined` | Working directory for database |

**Returns** — Matching rows

## getGateResultsByStageId(stageId, cwd)

Get gate results for a stage, ordered by checkedAt descending.

**Signature**

```typescript theme={null}
(stageId: string, cwd?: string | undefined) => Promise<{ id: string; reason: string | null; stageId: string; gateName: string; result: "warn" | "pass" | "fail"; checkedAt: string; checkedBy: string; details: string | null; }[]>
```

**Parameters**

| Name      | Type                    | Description                    |
| --------- | ----------------------- | ------------------------------ |
| `stageId` | `string`                | Stage ID                       |
| `cwd`     | `: string \| undefined` | Working directory for database |

**Returns** — Gate result rows

## getGateResultsByStageIdUnordered(stageId, cwd)

Get gate results for a stage without ordering (for simple checks).

**Signature**

```typescript theme={null}
(stageId: string, cwd?: string | undefined) => Promise<{ id: string; reason: string | null; stageId: string; gateName: string; result: "warn" | "pass" | "fail"; checkedAt: string; checkedBy: string; details: string | null; }[]>
```

**Parameters**

| Name      | Type                    | Description                    |
| --------- | ----------------------- | ------------------------------ |
| `stageId` | `string`                | Stage ID                       |
| `cwd`     | `: string \| undefined` | Working directory for database |

**Returns** — Gate result rows

## getEvidenceByStageId(stageId, cwd)

Get evidence for a stage, ordered by recordedAt descending.

**Signature**

```typescript theme={null}
(stageId: string, cwd?: string | undefined) => Promise<{ id: string; description: string | null; type: "file" | "url" | "manifest"; stageId: string; uri: string; recordedAt: string; recordedBy: string | null; }[]>
```

**Parameters**

| Name      | Type                    | Description                    |
| --------- | ----------------------- | ------------------------------ |
| `stageId` | `string`                | Stage ID                       |
| `cwd`     | `: string \| undefined` | Working directory for database |

**Returns** — Evidence rows

## getRecentTransitions(pipelineId, limit, cwd)

Get recent transitions for a pipeline, ordered by createdAt descending.

**Signature**

```typescript theme={null}
(pipelineId: string, limit?: number, cwd?: string | undefined) => Promise<{ id: string; createdAt: string; pipelineId: string; fromStageId: string; toStageId: string; transitionType: "automatic" | "manual" | "forced"; transitionedBy: string | null; }[]>
```

**Parameters**

| Name         | Type                    | Description                      |
| ------------ | ----------------------- | -------------------------------- |
| `pipelineId` | `string`                | Pipeline ID                      |
| `limit`      | `: number`              | Max rows to return (default: 10) |
| `cwd`        | `: string \| undefined` | Working directory for database   |

**Returns** — Transition rows

## insertTransition(transition, cwd)

Insert a new transition record.

**Signature**

```typescript theme={null}
(transition: { id: string; pipelineId: string; fromStageId: string; toStageId: string; createdAt?: string | undefined; transitionType?: "automatic" | "manual" | "forced" | undefined; transitionedBy?: string | ... 1 more ... | undefined; }, cwd?: string | undefined) => Promise<...>
```

**Parameters**

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

**Signature**

```typescript theme={null}
(task: Task, threshold?: number) => AtomicityResult
```

## extractTaskRefs()

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

**Signature**

```typescript theme={null}
(text: string, excludeId?: string | undefined) => string[]
```

## createRelatesEntries()

Create relates entries from extracted task IDs.

**Signature**

```typescript theme={null}
(refs: string[], relType?: RelatesType, reason?: string | undefined) => RelatesEntry[]
```

## mergeRelatesArrays()

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

**Signature**

```typescript theme={null}
(existing: RelatesEntry[], newEntries: RelatesEntry[]) => RelatesEntry[]
```

## validateRelatesRefs()

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

**Signature**

```typescript theme={null}
(relates: RelatesEntry[], validTaskIds: string[]) => string[]
```

## extractAndCreateRelates()

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

**Signature**

```typescript theme={null}
(text: string, excludeId?: string | undefined, relType?: RelatesType, reason?: string | undefined) => RelatesEntry[]
```

## calculateAffectedTasks()

Calculate which tasks would be affected by a delete operation.

**Signature**

```typescript theme={null}
(taskId: string, strategy: string, tasks: Task[]) => AffectedTasks
```

## calculateImpact()

Calculate impact of deletion.

**Signature**

```typescript theme={null}
(affected: AffectedTasks, tasks: Task[]) => DeleteImpact
```

## generateWarnings()

Generate warnings based on impact analysis.

**Signature**

```typescript theme={null}
(affected: AffectedTasks, impact: DeleteImpact, strategy: string) => DeleteWarning[]
```

## previewDelete()

Main preview function - coordinates all preview calculations.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[], options?: { strategy?: string | undefined; reason?: string | undefined; } | undefined) => DeletePreview
```

## isValidStrategy()

Validate a strategy name.

**Signature**

```typescript theme={null}
(strategy: string) => strategy is ChildStrategy
```

## handleChildren()

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

**Signature**

```typescript theme={null}
(taskId: string, strategy: ChildStrategy, tasks: Task[], options?: { force?: boolean | undefined; cascadeThreshold?: number | undefined; allowCascade?: boolean | undefined; } | undefined) => { ...; }
```

## GraphCache

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

**Signature**

```typescript theme={null}
typeof GraphCache
```

**Methods**

### computeChecksum()

Compute a simple checksum from task data to detect changes.

```typescript theme={null}
(tasks: Task[]) => string
```

### isValid()

Check if cache is still valid for given tasks.

```typescript theme={null}
(tasks: Task[]) => boolean
```

### isExpired()

Check if a cache entry has expired.

```typescript theme={null}
<T>(entry: CacheEntry<T>) => boolean
```

### invalidate()

Invalidate all caches.

```typescript theme={null}
() => void
```

### ensureFresh()

Ensure cache is fresh for the given task set.

```typescript theme={null}
(tasks: Task[]) => void
```

### getDescendants()

Get descendants of a task (cached).

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

### getChildren()

Get children of a task (cached).

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

### getDependents()

Get dependents of a task (cached).

```typescript theme={null}
(taskId: string, tasks: Task[]) => string[]
```

### getWaves()

Get dependency waves (cached).

```typescript theme={null}
(tasks: Task[]) => DependencyWave[]
```

### getStats()

Get cache statistics.

```typescript theme={null}
() => { descendantsSize: number; childrenSize: number; dependentsSize: number; hasWaves: boolean; }
```

## discoverByLabels()

Discover related tasks by shared labels.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => DiscoveryMatch[]
```

## discoverByDescription()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => DiscoveryMatch[]
```

## discoverByFiles()

Discover related tasks by shared files.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[]) => DiscoveryMatch[]
```

## discoverByHierarchy()

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

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[], options?: { siblingBoost?: number | undefined; cousinBoost?: number | undefined; } | undefined) => DiscoveryMatch[]
```

## discoverRelatedTasks()

Discover related tasks using all methods combined.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[], method?: DiscoveryMethod) => DiscoveryMatch[]
```

## suggestRelates()

Suggest relates entries filtered by threshold.

**Signature**

```typescript theme={null}
(taskId: string, tasks: Task[], threshold?: number) => DiscoveryMatch[]
```

## getCurrentPhase()

Get the current active phase from project metadata.

**Signature**

```typescript theme={null}
(project: ProjectMeta) => Phase | null
```

## getTasksByPhase()

Get tasks belonging to a specific phase.

**Signature**

```typescript theme={null}
(phaseName: string, tasks: Task[]) => Task[]
```

## calculatePhaseProgress()

Calculate progress for a phase.

**Signature**

```typescript theme={null}
(phaseName: string, tasks: Task[]) => PhaseProgress
```

## getAllPhaseProgress()

Get progress for all phases.

**Signature**

```typescript theme={null}
(phases: Record<string, Phase>, tasks: Task[]) => PhaseProgress[]
```

## validatePhaseTransition()

**Signature**

```typescript theme={null}
(fromPhase: string | null, toPhase: string, phases: Record<string, Phase>) => PhaseTransitionValidation
```

## createPhaseTransition()

Create a phase transition record.

**Signature**

```typescript theme={null}
(phase: string, transitionType: "completed" | "started" | "rollback", taskCount: number, fromPhase?: string | null | undefined, reason?: string | undefined) => PhaseTransition
```

## applyPhaseTransition()

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

**Signature**

```typescript theme={null}
(project: ProjectMeta, toPhase: string, transitionType: "completed" | "started" | "rollback", taskCount: number, reason?: string | undefined) => ProjectMeta
```

## getNextPhase()

Get the next phase in order.

**Signature**

```typescript theme={null}
(currentPhaseName: string | null, phases: Record<string, Phase>) => string | null
```

## allPhasesComplete()

Check if all phases are complete.

**Signature**

```typescript theme={null}
(phases: Record<string, Phase>) => boolean
```

## reparentTask(data, opts)

Reparent a task within a TaskFile.  Mutates the task in-place within `data.tasks`. Updates `parentId`, `type`, and `updatedAt` on the target task, and `lastUpdated` on the TaskFile.

**Signature**

```typescript theme={null}
(data: TaskFile, opts: ReparentOptions) => Promise<ReparentResult>
```

**Parameters**

| Name   | Type              | Description                            |
| ------ | ----------------- | -------------------------------------- |
| `data` | `TaskFile`        | The loaded TaskFile (mutated in place) |
| `opts` | `ReparentOptions` | Reparent options (taskId, newParentId) |

**Returns** — Result with old/new parent and new type

## getSizeWeight()

Get weight for a task size.

**Signature**

```typescript theme={null}
(size: TaskSize | null | undefined) => number
```

## getPriorityWeight()

Get weight for a task priority.

**Signature**

```typescript theme={null}
(priority: TaskPriority) => number
```

## calculateTaskScore()

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

**Signature**

```typescript theme={null}
(task: Task) => number
```

## sortByWeight()

Sort tasks by weighted score (highest first).

**Signature**

```typescript theme={null}
(tasks: Task[]) => Task[]
```

## calculateTotalEffort()

Calculate total weighted effort for a set of tasks.

**Signature**

```typescript theme={null}
(tasks: Task[]) => number
```

## calculateWeightedProgress()

Calculate completion percentage by weight.

**Signature**

```typescript theme={null}
(tasks: Task[]) => number
```

## calculateRemainingEffort()

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

**Signature**

```typescript theme={null}
(tasks: Task[]) => number
```

## getLastActivity()

Get the most recent activity timestamp for a task.

**Signature**

```typescript theme={null}
(task: Task) => string
```

## classifyStaleness()

Classify staleness level for a task.

**Signature**

```typescript theme={null}
(task: Task, thresholds?: StalenessThresholds) => StalenessLevel
```

## getStalenessInfo()

Get staleness info for a single task.

**Signature**

```typescript theme={null}
(task: Task, thresholds?: StalenessThresholds | undefined) => StalenessInfo
```

## findStaleTasks()

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

**Signature**

```typescript theme={null}
(tasks: Task[], thresholds?: StalenessThresholds | undefined) => StalenessInfo[]
```

## getStalenessSummary()

**Signature**

```typescript theme={null}
(tasks: Task[], thresholds?: StalenessThresholds | undefined) => StalenessSummary
```

## validateReleaseTask()

Validate release protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## checkReleaseManifest()

Validate release protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## validateResearchTask()

Validate research protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## checkResearchManifest()

Validate research protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## validateTestingTask()

Validate testing protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## checkTestingManifest()

Validate testing protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## validateValidationTask()

Validate verification/validation protocol for a task.

**Signature**

```typescript theme={null}
(taskId: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```

## checkValidationManifest()

Validate validation protocol from manifest file.

**Signature**

```typescript theme={null}
(manifestFile: string, opts: { strict?: boolean | undefined; }) => Promise<ValidationResult>
```
