/** * Shared generic type aliases used across core interfaces. * These are intentionally minimal so adapters can override with domain types. */ type State = unknown; type Action = unknown; type Feedback = unknown; type ProbeData = unknown; interface ProbeResult { pass: boolean; reason?: string; data?: D; } /** * AggregateProbeResult - Result of combining multiple probe tests * Framework guarantees the base structure, users can extend with additional fields */ interface AggregateProbeResult = ProbeResult> { pass: boolean; reason?: string; /** Array of individual probe results */ results: R[]; } type Cost = number | Record; /** Failure categories for StrategySelector / FailureClassifier */ type FailureType = 'Unknown' | 'NoData' | 'TooNarrow' | 'TooBroad' | 'AuthDenied' | 'RateLimited' | 'ToolMissing' | 'Infeasible'; /** Optional meta signal passed between modules (entropy, drift, coverage, etc.) */ type Signal = Record; /** * Logger interface compatible with pino and other structured loggers. * Supports both simple string messages and structured logging with objects. */ interface Logger { /** * Log at 'trace' level (most verbose) */ trace: LogFn; /** * Log at 'debug' level */ debug: LogFn; /** * Log at 'info' level */ info: LogFn; /** * Log at 'warn' level */ warn: LogFn; /** * Log at 'error' level */ error: LogFn; /** * Log at 'fatal' level (most severe) */ fatal: LogFn; /** * Create a child logger with additional bindings */ child?(bindings: Record): Logger; } /** * Log function signature compatible with pino. * Supports multiple call patterns: * - log(msg) * - log(obj, msg) * - log(msg, ...args) for formatting * - log(obj, msg, ...args) */ interface LogFn { (msg: string): void; >(obj: T, msg?: string): void; (msg: string, ...args: unknown[]): void; >(obj: T, msg: string, ...args: unknown[]): void; } /** * Typed metadata channels shared across middleware within a single step. * * Each control layer writes to its own channel. The index signature * preserves backward compatibility — user middleware can still write * arbitrary keys. */ interface MetadataChannels { /** v2.1 Semantic Kinematics snapshot (EKF/PID). */ kinematics?: unknown; /** v2.1 Correction info when drift is detected. */ kinematicsCorrection?: unknown; /** v3.0 Riemannian manifold snapshot (reserved). */ manifold?: unknown; /** v4.0 Grassmannian subspace snapshot (reserved). */ grassmannian?: unknown; /** Policy action taken by policyMiddleware. */ policyAction?: unknown; /** Extensible — user middleware can write arbitrary keys. */ [key: string]: unknown; } /** * Context passed to middleware before each agent step. */ interface StepContext { /** Current step number (0-indexed) */ step: number; /** Current state */ state: S; /** Previous state (undefined on first step) */ prevState?: S; /** Budget snapshot */ budget: { used: number; remaining: number; }; /** Typed metadata shared across middleware in a single step */ metadata: MetadataChannels; } /** * Result produced after an agent step. */ interface StepResult { /** State after the step */ state: S; /** Action taken (if any) */ action?: unknown; /** Feedback signal (if any) */ feedback?: unknown; /** Cost incurred by this step */ cost?: number; } /** * A composable unit of logic that hooks into the agent control loop. * * Middleware can intercept before/after each step, and participate in * setup/teardown lifecycle events. All hooks are optional — implement * only what you need. * * `beforeStep` runs in registration order. * `afterStep` runs in reverse registration order (Koa-style onion). */ interface Middleware { /** Human-readable name for logging/debugging */ name: string; /** * Run before each agent step. * - Return a (possibly modified) `StepContext` to continue. * - Return `'halt'` to stop the loop immediately. */ beforeStep?(ctx: StepContext): Promise | 'halt'>; /** * Run after each agent step. * Receives the context and the step result. */ afterStep?(ctx: StepContext, result: StepResult): Promise; /** * Called once when the loop starts, before the first step. */ setup?(ctx: { input: unknown; }): Promise; /** * Called once when the loop ends (normal completion or halt). */ teardown?(ctx: { reason: string; }): Promise; } /** An N-dimensional embedding vector. */ type VectorN = number[]; /** * Grassmannian manifold operations for CyberLoop v4.0. * * This module provides the math for tracking and comparing **subspaces** * on the Grassmannian manifold Gr(k, d) — the space of all k-dimensional * subspaces of ℝ^d. * * A "subspace" is represented as an orthonormal basis matrix (d × k), * stored column-major as `VectorN[]` where each vector is a basis column. * This is the same convention used by `localPCA` in `manifold.ts`. * * **Key operations:** * - `extractSubspace` — SVD on a window of vectors → orthonormal basis * - `principalAngles` — canonical angles between two subspaces * - `geodesicDistance` — Riemannian distance on Gr(k, d) * - `logMap` — tangent vector pointing from one subspace toward another * - `incrementalSubspaceUpdate` — O(d·k) rank-1 update (avoids full SVD) * - `subspaceProjectionError` — how much of a vector lies outside a subspace * * @module geometry/grassmannian */ /** * An orthonormal basis representing a point on the Grassmannian Gr(k, d). * * Each element is a d-dimensional column vector. The array has k elements, * so the subspace is k-dimensional within ℝ^d. */ type SubspaceBasis = VectorN[]; /** * Result of extracting a subspace from a window of vectors. */ interface SubspaceExtraction { /** Orthonormal basis vectors (top-k left singular vectors). */ basis: SubspaceBasis; /** Singular values (descending order). */ singularValues: number[]; /** Explained variance ratio of the top-k components (0–1). */ explainedVariance: number; /** Dimension of the ambient space (d). */ ambientDim: number; /** Dimension of the subspace (k). */ subspaceDim: number; } /** * Result of comparing two subspaces on the Grassmannian. */ interface SubspaceComparison { /** Principal angles between the two subspaces (in radians, ascending). */ principalAngles: number[]; /** Geodesic distance on Gr(k, d): sqrt(Σ θ_i²). */ geodesicDistance: number; /** Mean principal angle (average structural alignment). */ meanAngle: number; /** Maximum principal angle (worst-case dimensional divergence). */ maxAngle: number; } interface StateEmbedder { embed(state: S): Promise; } interface ManifoldProvider { /** Find k nearest neighbors to a point in the corpus. */ knn(point: VectorN, k: number): Promise; } interface ManifoldSnapshot { /** Tangential component of the agent's velocity (on-manifold motion). */ velocityTangent: VectorN; /** Normal component of the agent's velocity (off-manifold drift). */ velocityNormal: VectorN; /** Magnitude of normal velocity (scalar measure of drift). */ normalDriftMagnitude: number; /** Local curvature κ (0 = flat, 1 = maximally curved). */ curvature: number; /** Explained variance ratio of the tangent space. */ explainedVariance: number; /** Distance from current position to manifold centroid. */ distanceToCentroid: number; /** Distance from current position to the nearest neighbor. */ distanceToNearestNeighbor: number; /** Number of neighbors found (sparse = fewer neighbors). */ neighborCount: number; /** Whether the agent has drifted beyond the configured threshold. */ isDrifting: boolean; } interface SubspaceTrajectory { /** Get the reference subspace basis at time t (step index or normalized [0,1]). */ referenceAt(t: number): SubspaceBasis; /** Total number of reference points in the trajectory. */ length: number; } interface GrassmannianSnapshot { /** Current subspace basis (top-k principal directions of the sliding window). */ currentBasis: SubspaceBasis; /** Principal angles between current subspace and reference (ascending, radians). */ principalAngles: number[]; /** Geodesic distance on Gr(k, d) to the reference subspace. */ geodesicDistance: number; /** Mean principal angle (average structural alignment). */ meanAngle: number; /** Maximum principal angle (worst-case dimensional divergence). */ maxAngle: number; /** Explained variance ratio of the current subspace extraction (0–1). */ explainedVariance: number; /** Number of vectors currently in the sliding window. */ windowSize: number; /** Dimension of the extracted subspace (k). */ subspaceDim: number; /** Whether the agent has drifted beyond the configured threshold. */ isDrifting: boolean; /** Log map tangent vector (direction to rotate toward reference). Null if no reference. */ steeringDirection: VectorN[] | null; } export type { Action as A, Cost as C, Feedback as F, GrassmannianSnapshot as G, Logger as L, Middleware as M, ProbeData as P, State as S, VectorN as V, FailureType as a, ProbeResult as b, Signal as c, StepContext as d, StepResult as e, AggregateProbeResult as f, SubspaceBasis as g, SubspaceComparison as h, SubspaceExtraction as i, ManifoldProvider as j, ManifoldSnapshot as k, SubspaceTrajectory as l, MetadataChannels as m, StateEmbedder as n };