import type { IMatrixContext } from '../engine/core/IMatrixContext';
import { SubscriptionBag } from '../engine/messaging/SubscriptionBag';
import { ActorBehavior } from './actor/ActorBehavior';
import type { IMailbox, IExitSignal } from '../engine/mailbox/IMailbox';
import { LamportClock } from '../engine/messaging/LamportClock';
import { ChildManager } from './children/ChildManager';
import { type ISupervisionPolicy } from './Supervision';
import { SupervisorBehavior } from './actor/SupervisorBehavior';
import { SecurityRealm, type ISupervisorSecurityPolicy } from './security';
import type { ICapabilityToken } from './security/ICapabilityToken';
import type { ICompositeIntrospectChild, IComponentTreeDescriptor, Position, IAddChildOptions, IDynamicComponentDefinition } from './composite';
export type MessageHandler = (payload: unknown, meta: {
    topic: string;
    ts: number;
}) => void | Promise<void>;
export type ComponentHandler = (payload: unknown, meta: {
    topic: string;
    ts: number;
}) => unknown | Promise<unknown>;
/**
 * Deep binding descriptor — produced by the DSL compiler.
 * Maps a descendant event to a handler on the template author's actor.
 */
export interface DeepBindingDescriptor {
    /** Dot-delimited descendant path relative to this actor, e.g., 'split.preview.syntax' */
    relativePath: string;
    /** Event name, e.g., 'HighlightReady' */
    event: string;
    /** Handler method name on this actor, e.g., 'onHighlightReadyFromSyntax' */
    handler: string;
}
export type { Position } from './composite';
export declare abstract class MatrixActor {
    /**
     * Index signature for dynamic handler method access.
     * Enables type-safe lookup of onFoo handlers by name.
     */
    [key: string]: unknown;
    /**
     * Static metadata declaring what DOMAIN commands this actor accepts.
     * System commands ($join, $leave, introspect, $ping) are auto-subscribed.
     * Override in subclass.
     */
    static accepts: Record<string, unknown>;
    /**
     * Static metadata declaring what events this actor emits.
     * Override in subclass.
     */
    static emits: Record<string, unknown>;
    /**
     * Theme tokens this actor declares support for.
     * Each key is a token name (without --mx- prefix), value is metadata.
     * Used by the $tokens handler and surfaced in $introspect / oracle snapshots.
     * Subclass declarations merge with (and override) parent declarations.
     */
    static tokens: Record<string, {
        default: string;
        description: string;
    }>;
    /**
     * Output schemas per op. Describes what each handler returns.
     * Surfaced via $introspect { depth: 'full' } alongside acceptsSchema.
     */
    static outputSchemas?: Record<string, Record<string, unknown>>;
    /**
     * Error specifications per op. Documents known error conditions.
     * Each entry is an array of { code, description } objects.
     */
    static errorSpecs?: Record<string, Array<{
        code: string;
        description: string;
    }>>;
    /**
     * Optional self-documenting examples surfaced via $introspect { depth: 'full' }.
     * Per-op examples with input/output pairs for AI agent discovery.
     */
    static examples?: Record<string, Array<{
        input: Record<string, unknown>;
        output?: Record<string, unknown>;
    }>>;
    /**
     * Optional intent filters for capability-based resolution.
     */
    static intentFilters?: unknown[];
    /**
     * Higher-level skill bundles that compose multiple accepts into meaningful actions.
     * Skills are the primary discovery surface for AI agents (R18).
     * Each key is a skill name, value describes what it does and which ops it composes.
     *
     * See: ARCHITECTURE-SKILLS.md §2
     */
    static skills: Record<string, {
        description: string;
        ops?: string[];
        examples?: Array<{
            input: Record<string, unknown>;
            expected?: string;
        }>;
    }>;
    /**
     * Optional state schema for named type matching.
     */
    static stateSchema?: Record<string, unknown>;
    /**
     * Persistence scope for this actor's state.
     * Determines the KV key prefix used by NatsStateTap and the cascade
     * resolution order used by BlackboardActor on read.
     *
     * Scopes (most specific → least specific):
     *   session   — per-session (default). Survives F5 reload.
     *   user      — per-user. Survives new sessions. Use for preferences.
     *   page      — per-page/tab. Scoped to a single browser page.
     *   workspace — per-workspace. Shared across workspace members.
     *   org       — per-organization. Company defaults.
     *   root      — per-root. Root-wide shared state.
     *   global    — cross-root. Federation-wide.
     */
    static stateScope: 'session' | 'user' | 'page' | 'workspace' | 'org' | 'root' | 'realm' | 'global';
    /**
     * Whether this actor's state should be persisted to KV.
     * Set to false for ephemeral actors (loading spinners, animations).
     */
    static persistState: boolean;
    /** The injected context */
    protected _context?: IMatrixContext;
    /** Optional fact-plane emit capability token. */
    protected _factCapability: ICapabilityToken | null;
    /** Subscription cleanup bag */
    protected _subs: SubscriptionBag;
    /** Replica mounts for multi-bind state replication */
    protected _replicaMounts: string[];
    /** Lamport logical clock for causal message ordering */
    protected _lamportClock: LamportClock;
    /** Actor mailbox for exclusive message receiving */
    protected _mailbox?: IMailbox;
    /** Composed actor behavior (mailbox + dispatch) */
    protected _actor?: ActorBehavior;
    /** LISP dispatch strategy (if using LISP handlers) */
    private _lispStrategy?;
    /** Shell metadata injected by MatrixActorHtmlElement for introspect */
    _shellInfo?: {
        shellTag: string;
        moduleUrl?: string;
        description?: string;
    };
    /** Shell element reference — set by MatrixActorHtmlElement during _receiveContext.
     *  Used by $source-code to return the shell's source (LLM-written code) instead of
     *  the inner actor's source (minified DynamicActor). */
    _shellElement?: unknown;
    /** Whether the actor has been initialized */
    private _initialized;
    /** Whether the actor has been bootstrapped */
    private _bootstrapped;
    /** Whether the actor has been disposed */
    private _disposed;
    /** Callback for shell/adapter to receive state change notifications (FP-0.5). */
    _shellUpdateCallback: (() => void) | null;
    /** Reference to the shell element's ShadowRoot, so schema handlers can access DOM (e.g. iframes). */
    _shellRoot: ShadowRoot | null;
    /** Convenience getter for schema handler code: `this.shell.querySelector(...)` */
    get shell(): ShadowRoot | null;
    /** Promise that resolves when actor is ready */
    readonly ready: Promise<void>;
    private _resolveReady;
    /** Actor name/id */
    private _name;
    /** Child Manager — NOT allocated until first use */
    protected _children?: ChildManager;
    /** Supervisor behavior — NOT allocated until first use */
    protected _supervisor?: SupervisorBehavior;
    /** Security realm — NOT allocated until first use */
    protected _securityRealm?: SecurityRealm;
    /** Child event binding tracking */
    private _childBindings;
    /** Monitor references for tracked children */
    private _monitors;
    /** Dynamic child metadata */
    private _dynamicMetadata;
    /** Observable state store */
    protected _state: Record<string, unknown>;
    /** Optional CQRS-style command history for inspector tooling. */
    protected _commandHistory: Array<{
        op: string;
        ts: number;
        from?: string;
    }>;
    /** Optional CQRS-style event history for inspector tooling. */
    protected _eventHistory: Array<{
        op: string;
        ts: number;
    }>;
    protected _historyLimit: number;
    constructor();
    get name(): string;
    get mount(): string;
    get context(): IMatrixContext | undefined;
    get isInitialized(): boolean;
    get isReady(): boolean;
    get isDisposed(): boolean;
    get mailbox(): IMailbox | undefined;
    get lamportClock(): LamportClock;
    get replicaMounts(): readonly string[];
    get state(): Readonly<Record<string, unknown>>;
    /** Get the child manager (undefined if no children have been added) */
    protected get children(): ChildManager | undefined;
    /**
     * Initialize the actor with a context.
     *
     * @param context - The matrix context
     * @param name - Optional actor name
     */
    initialize(context: IMatrixContext, name?: string): Promise<void>;
    /**
     * Lazy-initialize child management infrastructure.
     * Called on first addChild() or $join — zero overhead if never used.
     */
    protected _ensureChildManagement(): void;
    /**
     * Handle $join handshake from child shells.
     * Lazy-initializes child management on first join.
     */
    on$join(payload: {
        id: string;
        mount: string;
        componentClass?: string;
        props?: unknown;
    }): void;
    /**
     * Handle $leave when a child disconnects voluntarily.
     */
    on$leave(_payload: {
        id: string;
        mount: string;
    }): void;
    /**
     * Handle $ping liveness check.
     */
    on$ping(_payload?: unknown): {
        status: string;
        mount: string;
    };
    /**
     * Handle $join_ack from parent (when this actor is a child).
     * Stub in Phase 20a-1 — full implementation in MatrixActorHtmlElement.
     */
    on$joinAck(_payload: unknown): void;
    /**
     * Handle $reply for request/reply pattern.
     * Stub in Phase 20a-1 — full implementation in FP-20b.
     */
    on$reply(_payload: unknown): void;
    /**
     * Alias for protocol-style $introspect operation.
     * Supports payload shape: { depth: 'full' }.
     */
    on$introspect(payload?: {
        depth?: 'basic' | 'full';
    }): ReturnType<MatrixActor['onIntrospect']>;
    /**
     * $source-code — Return this actor's source code via constructor.toString().
     */
    on$sourceCode(): {
        source: string;
        mount: string;
        tag?: string;
    };
    /**
     * System-plane state snapshot for Actor Inspector.
     */
    on$getState(): Record<string, unknown>;
    /**
     * System-plane history snapshot for CQRS log viewers.
     */
    on$getHistory(): {
        commands: Array<{
            op: string;
            ts: number;
            from?: string;
        }>;
        events: Array<{
            op: string;
            ts: number;
        }>;
    };
    /**
     * System-plane handler for activity frames pushed via `activityTo`.
     * Default is no-op. Browser elements and subclasses override for UI feedback.
     */
    on$activity(_payload: unknown): void;
    /**
     * G11: Query effective preferences for this actor's mount.
     * Delegates to system.preferences service via RequestReply.
     */
    on$preferences(payload?: {
        key?: string;
    }): Promise<Record<string, unknown>>;
    /**
     * G11: Query effective config for this actor's mount.
     * Delegates to system.config service via RequestReply.
     */
    on$config(payload?: {
        key?: string;
    }): Promise<Record<string, unknown>>;
    /**
     * Factory: create a child actor from a code string.
     *
     * Headless (daemon) path: evals the code into a class, uses addChild()
     * to create, initialize, and register the child in ChildManager.
     *
     * MatrixActorHtmlElement overrides this with DOM concerns (custom element
     * registration, shadow DOM insertion, versioned tag names).
     */
    onFactoryCreateFromCode(payload: {
        name: string;
        code: string;
    }): Promise<Record<string, unknown>>;
    /**
     * factory.load — Load a saved component from ComponentStoreActor.
     *
     * Invokes component.get-source on system.component-store,
     * then delegates to factory.create-from-code.
     */
    onFactoryLoad(payload: {
        name: string;
    }): Promise<Record<string, unknown>>;
    /**
     * component.save — Extract source from a running child and persist it.
     *
     * Finds the child by mount segment, invokes $source-code on it,
     * then sends component.persist to daemon.system.component-store.
     */
    onComponentSave(payload: {
        mount: string;
        name?: string;
        surface?: 'dom' | 'headless';
        description?: string;
    }): Promise<Record<string, unknown>>;
    /**
     * Framework op handler: $prompt (FP-0.4).
     *
     * Makes any MatrixActor promptable — forwards the prompt to the daemon.
     * MatrixActorHtmlElement overrides this with a richer implementation
     * (snapshot tree, session management, blocking mode).
     *
     * For dynamically created components this is the minimum needed to
     * receive and forward a prompt to the agent system.
     */
    on$prompt(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
    /**
     * Placeholder protocol hook for dynamic viewer/control creation.
     * Concrete runtimes may override this behavior.
     */
    on$createControl(payload?: unknown): {
        ok: false;
        op: '$createControl';
        message: string;
        requested?: unknown;
    };
    /**
     * Introspect handler — returns actor capabilities.
     * Always available on every actor.
     */
    protected onIntrospect(payload?: {
        depth?: 'basic' | 'full';
    }): {
        mount: string;
        componentClass: string;
        accepts: string[];
        emits: string[];
        tracks: string[];
        acceptsSchema: Record<string, unknown>;
        emitsSchema: Record<string, unknown>;
        tokens: string[];
        tokensSchema?: Record<string, {
            default: string;
            description: string;
        }>;
        children?: Array<ICompositeIntrospectChild>;
        shellTag?: string;
        moduleUrl?: string;
        description?: string;
        outputSchemas?: Record<string, Record<string, unknown>>;
        errorSpecs?: Record<string, Array<{
            code: string;
            description: string;
        }>>;
        examples?: Record<string, Array<{
            input: Record<string, unknown>;
            output?: Record<string, unknown>;
        }>>;
        testVectors?: unknown[];
        documentation?: string;
        intentFilters?: unknown[];
        skills?: string[];
        skillsSchema?: Record<string, unknown>;
        stateSchema?: Record<string, unknown>;
        stateScope?: string;
        persistState?: boolean;
    };
    /**
     * Update observable state and emit change events.
     * Emits $stateChanged with full state, and $propertyChanged per changed key.
     */
    setState(patch: Partial<Record<string, unknown>>): void;
    /**
     * Emit an event from this actor.
     *
     * Publishes to:
     *   1. $events topic (MxEnvelope) — new canonical path
     *   2. Per-op emits topic (legacy enriched payload) — backward compat until 20b-6
     *   3. Replica mounts (both formats)
     */
    protected emit(event: string, payload?: unknown): void;
    /**
     * Send a command to another actor by mount path (internal).
     *
     * Publishes MxEnvelope to target's $inbox.
     */
    protected sendTo(targetMount: string, command: string, payload?: unknown): void;
    /**
     * Send a command with three calling conventions:
     *
     * 1. Direct child: sendCommand('tree', 'ExpandDir', { path: '/src' })
     * 2. Relative path: sendCommand('./split.tree', 'ExpandDir', { path: '/src' })
     * 3. Tracked domain (2-arg): sendCommand('ExpandDir', { path: '/src' })
     *    — only supported in MatrixActorHtmlElement (view → tracked domain actor)
     *
     * Publishes MxEnvelope to target's $inbox.
     */
    sendCommand(toOrCmd: string, cmdOrData?: string | unknown, data?: unknown): void;
    /**
     * Cross-root RPC. Delegates to FederationPeer via transport adapter.
     */
    invoke(rootPath: string, op: string, data?: unknown): Promise<unknown>;
    /**
     * Publish a fact into the shared blackboard plane.
     *
     * Requires an emit-capable token in `_factCapability`.
     * Throws synchronously when capability is missing.
     */
    private _isFactDomainLiteralSegment;
    private _isFactDomainVariableSegment;
    private _splitFactDomainSegments;
    private _matchesFactCapabilitySubject;
    private _canEmitFactDomain;
    publishFact(domain: string, data: Record<string, unknown>): Promise<number>;
    /**
     * Read the latest fact for a domain from the shared fact plane.
     */
    readFact(domain: string): Promise<{
        data: unknown;
        revision: number;
    } | null>;
    /**
     * Subscribe to fact updates.
     *
     * Uses context-native subscription when available; otherwise falls back to
     * polling via readFact() to support transport layers without push hooks.
     */
    subscribeFact(domain: string, handler: (data: unknown) => void): () => void;
    /**
     * Add a child actor.
     * Lazy-initializes ChildManager, SupervisorBehavior, SecurityRealm on first call.
     *
     * @param id - Unique child identifier
     * @param ActorClass - Actor class to instantiate
     * @param options - Slot, position, props, bindings
     * @returns Mount path of the created child
     */
    addChild<T extends MatrixActor>(id: string, ActorClass: new () => T, options?: IAddChildOptions): Promise<string>;
    /**
     * Remove a child actor by id.
     */
    removeChild(id: string): Promise<void>;
    /**
     * Get mount path of a child by id.
     */
    getChildMount(id: string): string | undefined;
    /**
     * Get all child mount paths in a slot, in order.
     */
    getChildMountsInSlot(slot?: string): string[];
    /**
     * Get child ids in order.
     */
    childIds(slot?: string): string[];
    /**
     * Alias for childIds().
     */
    getChildIds(slot?: string): string[];
    /**
     * Move a child to a new position within its slot.
     */
    moveChild(id: string, position: Position): Promise<void>;
    /**
     * Send a command to a child by id (internal convenience).
     */
    protected sendToChild(childId: string, command: string, payload?: unknown): void;
    /**
     * Configure supervision policy.
     */
    setSupervisionPolicy(policy: ISupervisionPolicy): void;
    /**
     * Configure security policy.
     */
    setSecurityPolicy(policy: ISupervisorSecurityPolicy): void;
    /**
     * Configure both supervision and security policies.
     */
    setSecurityRealm(supervisionPolicy: ISupervisionPolicy, securityPolicy: ISupervisorSecurityPolicy): void;
    /**
     * Handle an exit signal from a child actor.
     * Applies supervision policy: restart, stop, escalate, or ignore.
     */
    handleChildExit(signal: IExitSignal): Promise<void>;
    /**
     * Wire bindings from the template to ANY descendant's events.
     * Used by the DSL compiler to connect template-level event bindings
     * to handler methods on the template author's actor.
     *
     * Unlike _subscribeToChildEvents() (direct children, handler cascade),
     * deep bindings use EXPLICIT handler mapping only — no cascade.
     */
    _wireDeepBindings(bindings: DeepBindingDescriptor[]): void;
    /**
     * Protocol handler for addDynamicChild command.
     */
    onAddDynamicChild(params: IDynamicComponentDefinition): Promise<{
        mount: string;
        adapterId: string;
        shellTag: string;
    }>;
    /**
     * Protocol handler for listDynamicChildren command.
     */
    onListDynamicChildren(): Array<{
        id: string;
        mount: string;
        shellTag?: string;
        codeHash?: string;
        createdAt?: number;
    }>;
    /**
     * Protocol handler for removeDynamicChild command.
     */
    onRemoveDynamicChild(params: {
        id: string;
    }): Promise<{
        success: boolean;
    }>;
    /**
     * Add a dynamic child from code at runtime.
     */
    addDynamicChild(params: IDynamicComponentDefinition): Promise<{
        mount: string;
        adapterId: string;
        shellTag: string;
    }>;
    /**
     * List all dynamic children.
     */
    listDynamicChildren(): Array<{
        id: string;
        mount: string;
        shellTag?: string;
        codeHash?: string;
        createdAt?: number;
    }>;
    /**
     * Serialize the component tree to a descriptor.
     */
    toDescriptor(): IComponentTreeDescriptor;
    /**
     * Enable actor mode — serialized message processing via mailbox.
     */
    protected enableActorMode(): void;
    /**
     * Add a replica binding for state replication.
     */
    addReplicaBind(remoteMount: string): Promise<void>;
    /**
     * Remove a replica binding.
     */
    removeReplicaBind(remoteMount: string): void;
    /** Override for initialization logic. */
    protected onBootstrap(): Promise<void>;
    /** Override for cleanup logic. */
    protected onDispose(): void;
    /** Hook called when context changes (remount). */
    protected _onContextChanged(): Promise<void>;
    /**
     * Dispose the actor and clean up all resources.
     */
    dispose(): void;
    private _bootstrap;
    /**
     * Subscribe to inbound messages via $inbox topic.
     *
     * Builds a dispatch table from static accepts + system commands.
     * Routes all inbound MxEnvelopes through a unified dispatch function.
     *
     * Single subscription: mount/$inbox — receives MxEnvelope format.
     */
    private _subscribeToInbox;
    /**
     * Subscribe to events from a child actor.
     * Uses ComponentClass.emits to know what topics to subscribe to.
     *
     * Handler resolution order:
     * 1. Declarative binding from options.bindings (highest priority)
     * 2. Specific: onEventFromChildId
     * 3. Generic: onEvent
     */
    private _subscribeToChildEvents;
    /**
     * Subscribe to child events using stored metadata (for remount).
     */
    private _subscribeToChildEventsFromMeta;
    /**
     * Subscribe to exit signals from a child actor.
     */
    private _monitorChild;
    /**
     * Remount all children with new derived contexts.
     */
    protected _remountChildren(): Promise<void>;
    private _unbindAll;
    private _toSerializable;
    private _pushBoundedHistory;
    private _attachLamportClock;
    private _receiveLamportClock;
    private _compileDynamicComponent;
    private _hashCode;
}
//# sourceMappingURL=MatrixActor.d.ts.map