/**
 * Dream Sub-agent — CC autoDream parity.
 *
 * Memory consolidation runs as a restricted sub-agent:
 *   - Read-only tool access (bash: ls/grep/cat/find/stat/wc/head/tail)
 *   - File writes restricted to memory directory
 *   - 4-phase system prompt: Orient → Gather → Consolidate → Prune
 *   - Trigger gates: time (24h) + session count (5)
 *   - PID-based consolidation lock
 *
 * Reference: claude-code src/services/autoDream/
 */
import type { DreamTaskState, DreamTurn } from "../tasks/task-types.js";
import type { ToolDefinition, ToolInvoker, AgentLogger, HookRegistry, ForkedAgentRunnerFactory } from "../ports/agent-execution-contracts.js";
import type { LLMTransport } from "../ports/index.js";
import type { TaskStore } from "../infra/task-runtime.js";
export interface DreamTriggerConfig {
    /** Minimum hours since last consolidation. Default: 24. */
    minHours: number;
    /** Minimum sessions since last consolidation. Default: 5. */
    minSessions: number;
    /** Minimum turns in current session as alternative gate. Default: 20. */
    minTurnsInSession: number;
    /** Scan throttle interval (ms). Default: 600_000 (10 min). */
    scanIntervalMs: number;
    /** Force run, ignoring gates. */
    force?: boolean;
}
export interface DreamContext {
    /** Root directory where memory files live. */
    memoryRoot: string;
    /** Directory containing session transcript JSONL files. */
    transcriptDir: string;
    /** Current agent session ID (excluded from session count). */
    currentSessionId: string;
    /** Callback to list session IDs touched since a timestamp. */
    listSessionsSince: (sinceMs: number) => Promise<string[]>;
    /** Turn count in current session (for single-session users). */
    currentSessionTurnCount?: number;
}
export interface DreamToolRestriction {
    toolName: string;
    input: Record<string, unknown>;
}
export type DreamToolVerdict = {
    allowed: true;
} | {
    allowed: false;
    reason: string;
};
/** Result of a dream consolidation run. */
export interface DreamRunResult {
    /** Whether dream ran successfully. */
    ok: boolean;
    /** Number of sessions reviewed. */
    sessionsReviewed: number;
    /** Memory files touched. */
    filesTouched: string[];
    /** Dream turns produced. */
    turns: DreamTurn[];
    /** Total duration (ms). */
    durationMs: number;
    /** Error message if failed. */
    error?: string;
}
/**
 * Check if a tool invocation is allowed during dream consolidation.
 *
 * Allowed:
 *   - read_file, grep, glob, search — unrestricted read-only tools
 *   - bash — only read-only commands (ls, grep, cat, find, stat, wc, head, tail)
 *   - file_edit, file_write — only within memoryRoot
 *   - Everything else — denied
 */
export declare function canUseDreamTool(memoryRoot: string, restriction: DreamToolRestriction): DreamToolVerdict;
/**
 * Build the 4-phase memory consolidation prompt.
 *
 * Adapted from CC's consolidationPrompt.ts with our project context.
 * P5: Enhanced with category-aware merge rules from write gate taxonomy.
 */
export declare function buildConsolidationPrompt(memoryRoot: string, transcriptDir: string, sessionIds: string[], opts?: {
    hasQMemory?: boolean;
    categoryContext?: string;
    temporalContext?: string;
    profileContext?: string;
    sessionDigest?: string;
}): string;
/**
 * Check whether dream consolidation should run.
 *
 * Gate order (cheapest first):
 *   1. Time gate — hours since lastConsolidatedAt >= minHours
 *   2. Scan throttle — 10-minute interval to suppress redundant scans
 *   3. Session gate — session count since lastConsolidatedAt >= minSessions
 *
 * @returns Session IDs to review, or null if gates failed.
 */
export declare function shouldTriggerDream(ctx: DreamContext, config?: Partial<DreamTriggerConfig>): Promise<{
    sessionIds: string[];
} | null>;
/**
 * Attempt to acquire the consolidation liveness lock.
 *
 * A held lock is "live" only if its mtime is fresh (< MAX_DREAM_RUN_MS) AND the
 * recorded PID is alive. A stale mtime reclaims unconditionally — this defends
 * against a crashed holder whose PID was reused by an unrelated process (the old
 * pure-PID check would falsely see it as alive and deadlock for up to an hour).
 *
 * @returns 0 on acquisition, or null if blocked by a live holder.
 */
export declare function tryAcquireConsolidationLock(memoryRoot: string): Promise<number | null>;
/**
 * Refresh the lock mtime so a long-but-legitimate dream is not reclaimed.
 * Called periodically by the dream runner. No-op if we no longer own the lock.
 */
export declare function heartbeatConsolidationLock(memoryRoot: string): Promise<void>;
/** Release the liveness lock explicitly (on failure, abort, or shutdown). */
export declare function releaseConsolidationLock(memoryRoot: string): Promise<void>;
/**
 * Rollback after a FAILED dream run: release the lock. The gate marker is NOT
 * touched (only success advances it), so a failed run never delays the next gate.
 * `_priorMtime` is retained for call-site compatibility and ignored.
 */
export declare function rollbackConsolidationLock(memoryRoot: string, _priorMtime: number): Promise<void>;
/**
 * Record a SUCCESSFUL consolidation: advance the gate marker (mtime = now) and
 * release the liveness lock.
 */
export declare function markConsolidationComplete(memoryRoot: string): Promise<void>;
/** Create initial DreamTaskState. */
export declare function createDreamTaskState(opts: {
    sessionId: string;
    sessionsReviewing: number;
    priorLockMtime: number;
    parentTaskId?: string;
}): DreamTaskState;
/** Add a turn to the dream state. */
export declare function addDreamTurn(state: DreamTaskState, turn: DreamTurn, touchedPaths: string[]): DreamTaskState;
/** Mark dream as completed. */
export declare function completeDreamState(state: DreamTaskState): DreamTaskState;
/** Mark dream as failed. */
export declare function failDreamState(state: DreamTaskState): DreamTaskState;
/**
 * Full dream orchestration entry point.
 *
 * This coordinates the entire dream lifecycle:
 *   1. Check trigger gates
 *   2. Acquire consolidation lock
 *   3. Build consolidation prompt
 *   4. Return dream context for the caller to run through agent loop
 *
 * The caller (stdio-server) is responsible for:
 *   - Running the prompt through the agent's tool loop
 *   - Applying canUseDreamTool() restrictions via tool.before_invoke hook
 *   - Calling markConsolidationComplete() on success
 *   - Calling rollbackConsolidationLock() on failure
 */
export declare function prepareDreamRun(ctx: DreamContext, config?: Partial<DreamTriggerConfig>): Promise<{
    prompt: string;
    taskState: DreamTaskState;
    sessionIds: string[];
} | null>;
export interface DreamRunDeps {
    /** Dream context (memoryRoot, transcriptDir, etc.) */
    context: DreamContext;
    /** Trigger configuration */
    triggerConfig?: Partial<DreamTriggerConfig>;
    /** LLM transport */
    transport: LLMTransport;
    /** Tool invoker */
    toolInvoker: ToolInvoker;
    /** Concrete agent runner factory injected by CLI/app layer. */
    createAgentRunner: ForkedAgentRunnerFactory;
    /** Available tools (will be filtered by canUseDreamTool) */
    tools: ToolDefinition[];
    /** Task store — when provided, the dream registers as a `dream` task (lifecycle visible to host + LLM). */
    taskStore?: TaskStore;
    /** API key */
    apiKey: string;
    /** Model for dream */
    model: string;
    /** Logger */
    log: AgentLogger;
    /** Hook registry */
    hooks?: HookRegistry;
    /** Parent abort signal */
    parentSignal?: AbortSignal;
    /**
     * Memory provider — when provided, Dream Agent acts as the "hippocampus":
     * reads existing long-term memories, writes classified session insights,
     * and submits feedback on outdated/contradicted memories.
     */
    memoryProvider?: {
        search(query: string, userId: string, options?: {
            limit?: number;
        }): Promise<Array<{
            blockId: string;
            text: string;
            score: number;
        }>>;
        proposeExtracted?(items: Array<{
            text: string;
            category?: string;
            importance?: number;
        }>, userId: string, options?: {
            sessionId?: string;
            source?: string;
        }): Promise<{
            proposalsAdded?: number;
        }>;
        feedback?(memoryIds: string[], signal: "useful" | "irrelevant" | "outdated" | "wrong"): Promise<{
            affected: number;
        }>;
        /** Recent activity summary for temporal context injection into Dream. */
        getActivitySummary?(userId: string, days?: number): {
            dailyCounts: Array<{
                date: string;
                count: number;
            }>;
            highlights: Array<{
                text: string;
                category: string;
                importance: number;
                date: string;
            }>;
        };
        /** Synthesize a timeline narrative for a time range. */
        synthesizeTimeline?(userId: string, startMs: number, endMs: number): string;
        /** Get/set user profile entries. */
        getProfile?(userId: string, key: string): string | null;
        setProfile?(userId: string, key: string, value: string): void;
        getAllProfiles?(userId: string): Record<string, string>;
        /** Drain consolidation backlog: resolve conflicts + promote corroborated pending claims. */
        resolveConflicts?(userId: string, opts?: {
            minEvidenceToPromote?: number;
        }): Promise<{
            conflictsResolved: number;
            claimsPromoted: number;
        }>;
    };
    /** User ID for memory operations. */
    memoryUserId?: string;
}
/**
 * Run a complete dream consolidation using an isolated forked agent.
 *
 * CC parity: This uses runForkedAgent() for true isolation instead of
 * hook-based tool restriction on the shared agent loop. The dream runs
 * in its own message history with its own AbortController.
 *
 * Full lifecycle:
 *   1. Check trigger gates
 *   2. Acquire consolidation lock
 *   3. Build consolidation prompt
 *   4. Fork sub-agent with restricted tools
 *   5. Run to completion
 *   6. Mark consolidation complete (or rollback on failure)
 */
export declare function runDream(deps: DreamRunDeps): Promise<DreamRunResult>;
