/**
 * Evolution Manager — the feedback loop that turns running into evolving.
 *
 * Four subsystems, one principle: every interaction is an opportunity
 * to improve. Not during batch reflection hours later, but at the
 * moment the insight is freshest.
 *
 * Subsystems:
 * 1. Evolution Queue — staged self-improvement proposals
 * 2. Learning Registry — structured, searchable insights
 * 3. Capability Gap Tracker — "what am I missing?"
 * 4. Action Queue — commitment tracking with stale detection
 *
 * Born from Portal's engagement pipeline (Steps 8-11) and proven
 * across 100+ evolution proposals and 10 platform engagement skills.
 */
import type { EvolutionProposal, EvolutionType, EvolutionStatus, LearningEntry, LearningSource, CapabilityGap, GapCategory, ActionItem, EvolutionManagerConfig } from './types.js';
import type { TrustElevationTracker } from './TrustElevationTracker.js';
import type { AutonomousEvolution, ReviewResult } from './AutonomousEvolution.js';
import type { AutonomyProfileManager } from './AutonomyProfileManager.js';
import type { TaskFlowRegistry } from '../tasks/TaskFlowRegistry.js';
import type { SemanticMemory } from '../memory/SemanticMemory.js';
import type { MemoryEvidence } from './types.js';
/**
 * WS2.2 (multi-machine-replicated-store-foundation) — the learning-record replication
 * emitter seam. server.ts injects a journal-backed emitter (built from the
 * CoherenceJournal clock + the `learning-record` kind) ONLY when
 * `multiMachine.stateSync.learnings.enabled` is true (default false ⇒ NOT injected ⇒ a
 * strict no-op, byte-identical single-machine behavior). The emitter NEVER throws out of
 * a learning write — a replication failure must never break a local write (the emitter
 * swallows + counts internally), so the manager calls it best-effort.
 *
 * CRITICAL: emitDelete MUST fire for every learning PRUNED over maxLearnings (the
 * saveLearnings prune path) — else a peer re-replicates the locally-pruned learning
 * forever (resurrection). The emitter keys the tombstone on the SAME content-fingerprint
 * recordKey the put used, so the delete reaches the same lesson on every machine even
 * though the local LRN-NNN ids differ.
 */
export interface LearningReplicationEmitter {
    /** Emit a `put` for a persisted learning (called from the save funnel). */
    emitPut(record: LearningEntry): void;
    /** Emit a `delete` tombstone for a removed/pruned learning, keyed on its content
     *  fingerprint (title/category/source). */
    emitDelete(title: string, category: string, source: LearningSource, deletedAt: string): void;
}
/**
 * WS2.5 (multi-machine-replicated-store-foundation) — the evolution-action-record
 * replication emitter seam. server.ts injects a journal-backed emitter (built from the
 * CoherenceJournal clock + the `evolution-action-record` kind) ONLY when
 * `multiMachine.stateSync.evolutionActions.enabled` is true (default false ⇒ NOT injected ⇒
 * a strict no-op, byte-identical single-machine behavior). The emitter NEVER throws out of an
 * action write — a replication failure must never break a local write (the emitter swallows +
 * counts internally), so the manager calls it best-effort.
 *
 * CRITICAL: emitPut MUST re-fire on a STATUS CHANGE (the whole point — a peer must SEE an
 * action was already completed/in_progress elsewhere so it does not redo it). The save funnel
 * re-emits every surviving action on every saveActions, so addAction AND updateAction both
 * re-emit.
 *
 * CRITICAL: emitDelete MUST fire for every action actually REMOVED from the queue (the
 * prune-over-maxActions path) — else a peer re-replicates the locally-removed action forever
 * (resurrection). A `completed`/`cancelled` action is a TERMINAL state, NOT a delete — its
 * record is retained (history); only an actual queue-removal tombstones. The emitter keys the
 * tombstone on the SAME content-fingerprint recordKey the put used, so the delete reaches the
 * same action on every machine even though the local ACT-NNN ids differ.
 */
export interface EvolutionActionReplicationEmitter {
    /** Emit a `put` for a persisted action (called from the save funnel; re-fires on every
     *  status change). */
    emitPut(record: ActionItem): void;
    /** Emit a `delete` tombstone for an action removed from the queue, keyed on its content
     *  fingerprint (title/commitTo/createdAt). */
    emitDelete(title: string, commitTo: string | null | undefined, createdAt: string, deletedAt: string): void;
}
interface EvolutionState {
    proposals: EvolutionProposal[];
    stats: {
        totalProposals: number;
        byStatus: Record<string, number>;
        byType: Record<string, number>;
        lastUpdated: string;
    };
}
interface LearningState {
    learnings: LearningEntry[];
    stats: {
        totalLearnings: number;
        applied: number;
        pending: number;
        byCategory: Record<string, number>;
        lastUpdated: string;
    };
}
interface GapState {
    gaps: CapabilityGap[];
    stats: {
        totalGaps: number;
        bySeverity: Record<string, number>;
        byCategory: Record<string, number>;
        addressed: number;
        lastUpdated: string;
    };
}
interface ActionState {
    actions: ActionItem[];
    stats: {
        totalActions: number;
        pending: number;
        completed: number;
        overdue: number;
        lastUpdated: string;
    };
}
export declare class EvolutionManager {
    private stateDir;
    private config;
    private trustElevationTracker;
    private autonomousEvolution;
    private autonomyManager;
    /** Registry handle (set when TaskFlow is enabled). */
    private taskFlowRegistry;
    /** Per-process controller-instance id (server uuid). */
    private taskFlowControllerInstanceId;
    /**
     * Set to true by DivergenceChecker when state-divergence is detected.
     * When true, EvolutionManager continues JSON-only writes and DOES NOT
     * dual-write to TaskFlow. The signal is reset on next divergence pass that
     * reports zero divergence. This is a signal-emitted brake, not a hard gate.
     */
    private taskFlowShadowWritesHalted;
    /** Most recent reason for halting; surfaced in /health and tests. */
    private taskFlowShadowWritesHaltReason;
    /**
     * Source of the most recent halt. DivergenceChecker uses this to ensure it
     * only auto-clears halts that DivergenceChecker itself imposed — an operator
     * or sibling system's manual halt stays in place until that source clears it.
     */
    private taskFlowShadowWritesHaltSource;
    /**
     * SemanticMemory handle. When wired, EvolutionManager creates a `pattern`
     * MemoryEntity for each new proposal (the cluster) and populates evidence
     * rows linking the cluster to its constituent feedback IDs / commit SHAs /
     * session IDs. JSON state remains the source of truth for proposals; the
     * cluster entity is a parallel surface for inverse-traceability queries.
     *
     * See docs/specs/OPENCLAW-IMPORT-WIKICLAIM-EVIDENCE-SPEC.md § Producers.
     */
    private semanticMemory;
    /**
     * WS2.2 learning-record replication emitter (injected, dark by default). Absent ⇒
     * strict no-op (single-machine, byte-identical). server.ts late-binds a journal-backed
     * emitter ONLY when `multiMachine.stateSync.learnings.enabled` is true.
     */
    private learningReplication;
    /**
     * WS2.5 evolution-action-record replication emitter (injected, dark by default). Absent ⇒
     * strict no-op (single-machine, byte-identical). server.ts late-binds a journal-backed
     * emitter ONLY when `multiMachine.stateSync.evolutionActions.enabled` is true.
     */
    private actionReplication;
    constructor(config: EvolutionManagerConfig);
    /**
     * Late-bind the WS2.2 learning-record replication emitter (server.ts constructs the
     * journal/clock AFTER the manager). Idempotent; passing undefined/null detaches (back
     * to single-machine no-op). The emit funnel checks `this.learningReplication` per
     * write, so attaching mid-life takes effect on the next save.
     */
    setLearningReplicationEmitter(emitter: LearningReplicationEmitter | null | undefined): void;
    /**
     * Late-bind the WS2.5 evolution-action-record replication emitter (server.ts constructs the
     * journal/clock AFTER the manager). Idempotent; passing undefined/null detaches (back to
     * single-machine no-op). The emit funnel checks `this.actionReplication` per write, so
     * attaching mid-life takes effect on the next save (add/updateAction).
     */
    setEvolutionActionReplicationEmitter(emitter: EvolutionActionReplicationEmitter | null | undefined): void;
    /**
     * Wire a TaskFlow registry for Phase 3a dual-write. After this call:
     *   - addProposal / updateProposalStatus shadow-write to TaskFlow
     *   - migrateExistingToTaskFlow() backfills any in-flight clusters
     *   - DivergenceChecker can call setShadowWritesHalted() to brake writes
     *
     * Idempotent — safe to call multiple times; subsequent calls overwrite.
     */
    setTaskFlowRegistry(registry: TaskFlowRegistry, controllerInstanceId: string): void;
    getTaskFlowRegistry(): TaskFlowRegistry | null;
    /**
     * Halt or resume TaskFlow shadow-writes. Called by DivergenceChecker on a
     * mismatch. Signal-vs-authority compliance: this is a signal-consumed brake,
     * not a brittle blocker — the divergence checker decides, EvolutionManager
     * obeys. JSON writes continue regardless (read-authoritative TaskFlow is
     * shadow-mode in Phase 3a).
     *
     * The optional `source` parameter tags the halt with its origin so an
     * automatic clearer (DivergenceChecker) only cancels halts it caused.
     * Defaults to `'manual'` when omitted.
     */
    setShadowWritesHalted(halted: boolean, reason?: string, source?: string): void;
    isShadowWritesHalted(): {
        halted: boolean;
        reason: string | null;
        source: string | null;
    };
    /**
     * Wire a SemanticMemory handle for cluster evidence emission. After this
     * call, `addProposal()` creates a `pattern` MemoryEntity for the cluster
     * with evidence linking to the proposal source, and `addClusterEvidence()`
     * appends evidence atomically as more inputs join the cluster.
     *
     * Idempotent — safe to call multiple times; subsequent calls overwrite.
     * Producers emit signals (evidence rows); they do NOT gate proposal flow.
     *
     * See docs/specs/OPENCLAW-IMPORT-WIKICLAIM-EVIDENCE-SPEC.md § Producers.
     */
    setSemanticMemory(memory: SemanticMemory): void;
    getSemanticMemory(): SemanticMemory | null;
    /**
     * Append evidence to the cluster MemoryEntity for an existing proposal.
     * Used when more feedback / commits / sessions join an open cluster.
     * No-op when SemanticMemory is not wired or when the proposal has no
     * cluster entity yet (legacy proposals from before Phase 2).
     *
     * Allowed kinds (per spec § Producers): `feedback`, `pattern-entity`,
     * `supersedes-evidence`. Mismatches throw `EvidencePolicyError`.
     */
    addClusterEvidence(proposalId: string, evidence: MemoryEvidence | MemoryEvidence[]): void;
    /**
     * Build the initial evidence array for a newly-created cluster from the
     * proposal's `source` field. Recognized patterns (mirrors backfill rules
     * in spec § Migration of Existing MemoryEntity Records, restricted to
     * EvolutionManager's allowlist):
     *
     *   - `feedback:<id>` → kind: 'feedback', sourceId: '<id>'
     *
     * Unrecognized sources produce no evidence (cluster is created with
     * `evidence: []`). Subsequent `addClusterEvidence()` calls populate as
     * inputs join. Empty evidence arrays are valid — `rememberWithEvidence`
     * with `evidence: []` is functionally equivalent to `remember()` plus the
     * consolidated JSONL action.
     */
    private buildInitialClusterEvidence;
    /**
     * Best-effort cluster-entity creation for a new proposal. Never throws to
     * the caller — JSON state remains the source of truth for proposals.
     * `EvidencePolicyError` (e.g., cap exceeded, kind mismatch) is logged and
     * swallowed; subsequent `addClusterEvidence()` calls can recover.
     *
     * Returns the entity id when created, or null when memory is not wired or
     * the cluster entity cannot be created.
     */
    private createClusterEntity;
    private taskFlowPrincipal;
    /**
     * Best-effort dual-write to TaskFlow. NEVER throws to the caller — JSON
     * remains the local durability path; TaskFlow is shadow until Phase 3b
     * cutover. All TaskFlow errors land in console and the divergence checker
     * picks up via state comparison.
     */
    private dualWriteCreate;
    private dualWriteTransition;
    private logTaskFlowError;
    /**
     * Backfill all in-flight proposals (status !== 'implemented' && !== 'rejected')
     * into TaskFlow. Idempotent via `findIdempotent` on
     * `evolution:cluster:<proposalId>` ownerKey. Safe to call multiple times.
     *
     * Returns counts: created, alreadyExisted, advanced (transitioned beyond
     * 'queued' to match the proposal's current status).
     */
    migrateExistingToTaskFlow(): Promise<{
        created: number;
        alreadyExisted: number;
        advanced: number;
        skipped: number;
    }>;
    /** Catch a flow record up to the proposal's current status. */
    private catchUpFlowToStatus;
    /**
     * Wire adaptive autonomy modules for runtime integration.
     * - TrustElevationTracker: receives proposal approval/rejection events
     * - AutonomousEvolution: handles auto-implementation when in autonomous mode
     * - AutonomyProfileManager: provides current autonomy profile state
     */
    setAdaptiveAutonomyModules(modules: {
        trustElevationTracker?: TrustElevationTracker | null;
        autonomousEvolution?: AutonomousEvolution | null;
        autonomyManager?: AutonomyProfileManager | null;
    }): void;
    /**
     * Get the wired TrustElevationTracker (for external access, e.g. routes).
     */
    getTrustElevationTracker(): TrustElevationTracker | null;
    /**
     * Get the wired AutonomousEvolution module (for external access, e.g. routes).
     */
    getAutonomousEvolution(): AutonomousEvolution | null;
    private filePath;
    private readFile;
    private writeFile;
    private now;
    private loadEvolution;
    private saveEvolution;
    private nextProposalId;
    addProposal(opts: {
        title: string;
        source: string;
        description: string;
        type: EvolutionType;
        impact?: 'high' | 'medium' | 'low';
        effort?: 'high' | 'medium' | 'low';
        proposedBy?: string;
        tags?: string[];
    }): EvolutionProposal;
    updateProposalStatus(id: string, status: EvolutionStatus, resolution?: string): boolean;
    /**
     * Process a proposal through the autonomous evolution pipeline.
     * If in autonomous mode and the review approves with safe scope,
     * the proposal is auto-implemented via sidecar pattern.
     *
     * Returns the action taken, or null if autonomous modules aren't wired.
     */
    processProposalAutonomously(proposalId: string, review: ReviewResult): {
        action: string;
        reason: string;
    } | null;
    listProposals(filter?: {
        status?: EvolutionStatus;
        type?: EvolutionType;
    }): EvolutionProposal[];
    getEvolutionStats(): EvolutionState['stats'];
    private loadLearnings;
    private saveLearnings;
    private nextLearningId;
    addLearning(opts: {
        title: string;
        category: string;
        description: string;
        source: LearningSource;
        tags?: string[];
        evolutionRelevance?: string;
    }): LearningEntry;
    markLearningApplied(id: string, appliedTo: string): boolean;
    listLearnings(filter?: {
        category?: string;
        applied?: boolean;
    }): LearningEntry[];
    getLearningStats(): LearningState['stats'];
    private loadGaps;
    private saveGaps;
    private nextGapId;
    addGap(opts: {
        title: string;
        category: GapCategory;
        severity: 'critical' | 'high' | 'medium' | 'low';
        description: string;
        context: string;
        platform?: string;
        session?: string;
        currentState?: string;
        proposedSolution?: string;
    }): CapabilityGap;
    addressGap(id: string, resolution: string): boolean;
    listGaps(filter?: {
        severity?: string;
        category?: GapCategory;
        status?: string;
    }): CapabilityGap[];
    getGapStats(): GapState['stats'];
    private loadActions;
    private saveActions;
    private nextActionId;
    addAction(opts: {
        title: string;
        description: string;
        priority?: 'critical' | 'high' | 'medium' | 'low';
        commitTo?: string;
        dueBy?: string;
        source?: ActionItem['source'];
        tags?: string[];
    }): ActionItem;
    updateAction(id: string, updates: {
        status?: ActionItem['status'];
        resolution?: string;
    }): boolean;
    listActions(filter?: {
        status?: ActionItem['status'];
        priority?: string;
    }): ActionItem[];
    getOverdueActions(): ActionItem[];
    getActionStats(): ActionState['stats'];
    /**
     * Get a full dashboard of evolution health.
     * Useful for session-start orientation and status reporting.
     */
    getDashboard(): {
        evolution: EvolutionState['stats'];
        learnings: LearningState['stats'];
        gaps: GapState['stats'];
        actions: ActionState['stats'];
        highlights: string[];
    };
    /**
     * Detect gaps or proposals that may already be resolved by existing infrastructure.
     *
     * Scans open gaps and proposed items against:
     *   - Implemented proposals (already built)
     *   - Applied learnings (already absorbed)
     *   - Addressed gaps (already resolved)
     *
     * Returns items that appear to have implicit resolutions, with evidence.
     */
    detectImplicitEvolution(): Array<{
        type: 'gap' | 'proposal';
        id: string;
        title: string;
        matchedBy: {
            type: string;
            id: string;
            title: string;
            similarity: string;
        };
    }>;
    /**
     * Verify that implemented proposals left actual file traces in the workspace.
     *
     * Inspired by Dawn's lesson-behavior-gap analyzer: proposals marked
     * "implemented" should have corresponding infrastructure (hooks, scripts,
     * config entries, code files). Proposals with no detectable traces may be
     * "phantom implementations" — marked done without actual changes.
     *
     * Returns proposals that lack verifiable infrastructure traces.
     */
    verifyImplementationTraces(): Array<{
        id: string;
        title: string;
        implementedAt: string;
        tracesFound: string[];
        verdict: 'verified' | 'unverified' | 'weak';
    }>;
    /**
     * Simple keyword overlap matching. Returns the best match if overlap
     * exceeds a threshold, or null if no match is strong enough.
     */
    private findKeywordMatch;
    /**
     * Extract meaningful keywords from text, filtering stop words.
     */
    private extractKeywords;
}
export {};
//# sourceMappingURL=EvolutionManager.d.ts.map