/** * FeltDB State-First Database API * * High-level, application-facing API that treats FeltDB as application state. * Persistence, indexing, and reactivity are completely transparent. */ import type { JsDb } from './feltdb.js'; import { type FreshnessCapability, type Revision } from './freshness.js'; import { Collection, Relationship } from './collection.js'; import { type AtomicTransactionDocument, type AtomicTransactionOptions, type AtomicTransactionResult, type AtomicTransactionScope } from './transaction.js'; import { type Cell } from './cell.js'; import type { AgentRef, AgentDefinition, AgentExecution } from './agent.js'; import { AgentRegistry } from './agent-registry.js'; import { AgentRuntime } from './agent-runtime.js'; import type { AuthorityQueryPage, AuthorityQueryRequest } from './http-db.js'; import type { EmbeddedQueryExplanation } from './embedded-query.js'; import { type FeltDBArchitectureInvariantService } from './architecture-invariant.js'; import type { FlowSpec } from './flowspec.js'; import { SyncController, type SyncConfig } from './sync-contract.js'; import { type FeltDBDeploymentConfig, type FeltDBDeploymentMode, type FeltDBDeploymentResolution } from './deployment.js'; import { WorkloadClient } from './workload.js'; import { MeshClient, WorkerClient, WorkerPoolClient } from './worker.js'; import { ArtifactClient } from './artifact.js'; import { BundleClient } from './bundle.js'; import { ReleaseClient } from './release.js'; import { ObserveClient } from './observe.js'; import { ProviderClient } from './provider.js'; import { type DevelopmentObservationSink } from './development-runtime-bridge.js'; import { type AuthorityScope } from './authority-scope.js'; import type { OperationAdmissionInput, OperationAdmissionResult, OperationTransitionInput, OperationTransitionResult } from './operation-admission.js'; import { FeltDBPublicContract } from './public-contract.js'; import type { DecisionTransportExecutionRequest, DecisionTransportExecutionResponse } from './semantic-decision.js'; export interface FeltDBOptions extends FeltDBDeploymentConfig { server?: { url: string; token?: string; applicationId?: string; environment?: string; requestTimeoutMs?: number; }; memory?: true; browser?: true; /** Explicit durable authority. Omitted only for legacy unscoped clients. */ authorityScope?: AuthorityScope; } export declare function createFeltDB(options?: FeltDBOptions): StateFirstDB; /** * Runtime information about the FeltDB instance */ export interface RuntimeInfo { /** The runtime environment (e.g., 'wasm', 'node', 'browser') */ runtime: 'wasm' | 'node' | 'browser' | 'remote'; /** The storage backend being used (e.g., 'memory', 'file', 'opfs', 'indexeddb') */ storage: string; /** Whether the database is persistent (durable across restarts) */ persistent: boolean; /** Whether mutations are reactive (subscribers notified automatically) */ reactive: boolean; /** Whether mutations are durable (persisted before returning) */ durable: boolean; /** FeltDB version */ version: string; /** Whether checkpointing/compaction is supported */ supportsCheckpointing: boolean; /** Whether lifecycle events are supported (open/close/reload) */ supportsLifecycle: boolean; } export interface FeltDBRuntimeCapabilities { deployment: FeltDBDeploymentMode; storage: string; durability: 'volatile' | 'browser-indexeddb' | 'node-file' | 'remote-authority'; subscriptions: boolean; transactions: boolean; cas: boolean; putIfAbsent: boolean; replication: boolean; remoteAuthority: boolean; offline: boolean; } export interface FeltDBCapabilitySurface { (): FeltDBRuntimeCapabilities; run: (name: string, input?: unknown, options?: { idempotencyKey?: string; }) => Promise; } /** * Sync state information */ export interface SyncInfo { /** This instance's ID */ instance_id: string; /** Current sequence number for this instance */ sequence: number; /** Connected peers */ connected_peers: string[]; /** Pending operations waiting to be synced */ pending_operations: number; /** Operations sent to peers */ operations_sent: number; /** Operations received from peers */ operations_received: number; /** Conflicts detected */ conflicts_detected: number; /** Last sync timestamp */ last_sync_ms: number; /** Is currently connected to network */ is_connected: boolean; } /** * A durable operation for synchronization */ export interface Operation { /** Unique operation ID (monotonically increasing) */ op_id: number; /** Instance ID - unique identifier for the FeltDB instance that created this operation */ instance_id: string; /** Sequence number - monotonically increasing sequence per instance */ sequence: number; /** Type of operation (Insert, Update, Delete) */ op_type: 'Insert' | 'Update' | 'Delete'; /** The key being operated on (e.g., "users:123") */ key: string; /** The value (for insert/update operations) */ value?: any; /** Timestamp in milliseconds since UNIX epoch */ timestamp_ms: number; /** The data type being operated on */ rust_type: string; /** Capability/namespace */ capability: string; } export interface AuditEvent { sequence: number; collection: string; key: string; type: 'put' | 'delete'; timestamp: number; } export interface EmbeddedOperation { id: string; origin: string; sequence: number; collection: string; key: string; type: 'put' | 'delete'; value?: unknown; timestamp: number; authorityScope?: AuthorityScope; } /** * Provenance edge types describing relationships in the causal graph */ export type ProvenanceEdgeType = 'CreatedBy' | 'InputTo' | 'ProducedBy' | 'ExecutedBy' | 'DerivedFrom' | 'TriggeredBy' | 'ResolvedFrom' | 'AcquiredFrom'; /** * A node in the provenance graph */ export interface ProvenanceNode { /** Unique identifier for this node */ id: string; /** Type of node (Record, Workflow, Execution, Capability, Agent, etc.) */ type: string; /** Human-readable label */ label: string; /** Additional metadata about this node */ metadata?: Record; /** Timestamp when this node was created */ created_ms: number; } /** * An edge in the provenance graph connecting two nodes */ export interface ProvenanceEdge { /** Source node ID */ from: string; /** Target node ID */ to: string; /** Type of relationship */ edgeType: ProvenanceEdgeType; /** Additional metadata about the edge */ metadata?: Record; } /** * A causal graph representing the provenance of a record/flow */ export interface ProvenanceGraph { /** The root node (the record/flow being inspected) */ root: ProvenanceNode; /** All nodes in the graph */ nodes: ProvenanceNode[]; /** All edges in the graph */ edges: ProvenanceEdge[]; } /** * Runtime diagnostics and health status */ export interface RuntimeDiagnostics { /** Runtime component status */ runtime: { status: 'healthy' | 'degraded' | 'unhealthy'; wasm: boolean; reactive: boolean; }; /** Storage component status */ storage: { status: 'healthy' | 'degraded' | 'unhealthy'; backend: string; persistent: boolean; durable: boolean; }; /** Synchronization status */ sync: { status: 'healthy' | 'degraded' | 'unhealthy'; connected: boolean; peers: number; pendingOperations: number; }; /** Distributed fabric status */ fabric: { status: 'healthy' | 'degraded' | 'unhealthy'; references: number; peers: number; }; /** Capability router status */ capabilities: { status: 'healthy' | 'degraded' | 'unhealthy'; count: number; available: number; }; /** Execution runtime status */ execution: { status: 'healthy' | 'degraded' | 'unhealthy'; pending: number; running: number; failed: number; }; /** Workflow status */ workflow: { status: 'healthy' | 'degraded' | 'unhealthy'; total: number; active: number; }; /** Overall system health status */ status: 'healthy' | 'degraded' | 'unhealthy'; /** Issues detected (warnings or errors) */ issues: Array<{ severity: 'info' | 'warning' | 'error'; component: string; message: string; }>; } /** * State-first database interface. * Applications use this to treat FeltDB collections as live application state. */ export declare class StateFirstDB { private jsDb; private collections; private cells; private runtimeInfo; private agentRegistry; private agentRuntime; private capabilityWorkers; private observation?; private closeDevelopmentBridge?; private deployment; /** Scope bound once when this authority session is created. */ readonly authorityScope?: AuthorityScope; private tenantFactory?; private localActorSession?; readonly workloads: WorkloadClient; readonly artifacts: ArtifactClient; readonly bundle: BundleClient; readonly releases: ReleaseClient; readonly observe: ObserveClient; readonly providers: ProviderClient; readonly workers: WorkerClient; readonly workerPools: WorkerPoolClient; readonly mesh: MeshClient; /** Durable, versioned architecture declarations and conformance evidence. */ readonly architecture: FeltDBArchitectureInvariantService; /** Stable 0.10B adapter; owns no durable state of its own. */ readonly substrate: FeltDBPublicContract; readonly workflows: { run: (name: string, input?: unknown, options?: { idempotencyKey?: string; }) => Promise; }; readonly agents: { run: (name: string, input?: unknown, options?: { idempotencyKey?: string; goal?: string; }) => Promise; }; readonly capabilities: FeltDBCapabilitySurface; readonly semanticDecisions: { execute: (request: DecisionTransportExecutionRequest) => Promise; }; readonly application: { get: () => Promise | { application_id: any; environment: string; version: any; contract_hash: string; dsl_version: number; snapshot: import("./application-development.js").FeltDBContractSnapshot; }>; }; readonly schema: { get: () => Promise>; }; readonly auth: { signUp: (input: { email: string; password: string; display_name?: string; }) => Promise; signIn: (input: { email: string; password: string; }) => Promise; signOut: () => Promise; session: () => Promise; }; constructor(jsDb: JsDb, observation?: DevelopmentObservationSink, closeDevelopmentBridge?: () => Promise, deployment?: FeltDBDeploymentResolution, authorityScope?: AuthorityScope, tenantFactory?: (tenantId: string) => StateFirstDB); private applicationRequest; private authRequest; private localAuthRequest; /** * Detect runtime environment and storage characteristics */ private detectRuntime; /** * Get runtime information about this FeltDB instance. * * Useful for testing and debugging without contaminating the normal API. * * @example * const runtime = db.runtime(); * console.log(`Using ${runtime.storage} storage in ${runtime.runtime}`); */ runtime(): RuntimeInfo; private runtimeCapabilities; /** * Get or create a collection. * * Collections are live application state - they automatically update * whenever underlying data changes. No manual refresh() or invalidate() needed. * * @example * const tasks = db.collection("tasks"); * const task = await tasks.get(123); * const allActive = await tasks.where(t => t.status === "active").all(); */ collection(name: string): Collection; /** Filter, order, and page records at the runtime's storage boundary. */ query>(query: AuthorityQueryRequest): Promise>; /** Explain which access path a bounded query would use. */ explain(query: AuthorityQueryRequest): Promise; /** Deterministically rebuild all derived embedded indexes. */ rebuildIndexes(): Promise; /** Canonical durable, concurrency-safe operation admission API. */ admitOperation(input: OperationAdmissionInput): Promise; /** Select one declared tenant from an explicit platform authority. */ forTenant(tenantId: string): StateFirstDB; /** Canonical durable operation lifecycle transition. */ transitionOperation(input: OperationTransitionInput): Promise; /** * Commit several operations as one atomic, durable transaction. * * Either every operation commits or none do — including across a crash. * * @example * const result = await db.transaction(async tx => { * tx.collection('users').set('u1', user); * tx.collection('orders').set('o1', order); * tx.collection('audit').set('a1', event); * }); * result.transactionId; // durable identity, stable across restart * * The callback stages operations; it does not write them. Nothing reaches * the authority until the callback returns, so there is no window in which * part of the transaction is durable and the rest is not. * * Throwing from the callback abandons the transaction without sending * anything. * * Requires a runtime backed by an authority that provides atomic * transactions. Runtimes that cannot refuse rather than silently degrading * the transaction into a sequence of independent writes. */ transaction(build: ((tx: AtomicTransactionScope) => void | Promise) | AtomicTransactionDocument, options?: AtomicTransactionOptions): Promise; /** * Get or create a durable cell. * * A Cell is an independently-versioned authority boundary for stateful entities. * Each cell owns its own version, state, and serialized mutation stream. * * @example * const agent = db.cell("agent:123"); * await agent.update(state => ({ * ...state, * status: "running" * })); */ cell(id: string): Cell; /** Resolve local state, causally acquiring it from configured peers when absent. */ acquire(collection: string, id: string): Promise; /** Search canonical collection state locally or through the remote capability surface. */ search(collection: string, query: string, limit?: number): Promise; /** Install a resource-bounded declarative capability program. */ defineCapability(name: string, steps: Array>): Promise; /** Attach executable behavior to a capability in an embedded runtime. */ registerCapabilityWorker(name: string, handler: (input: I) => Promise): () => void; executeCapability(name: string, input: unknown): Promise; /** Joint-consensus membership change. `members` contains every voting node, including this node. */ changeClusterMembership(expectedEpoch: number, members: string[]): Promise; /** Version and deploy one canonical application model into FeltDB primitives. */ deployFlowSpec(spec: FlowSpec, expectedVersion?: number, allowDestructive?: boolean): Promise<{ app: string; version: number; status: 'active'; }>; /** Read the runtime's durable local mutation log for inspection and audit. */ auditEvents(): Promise; /** Export durable embedded operations for transport over any application channel. */ exportOperations(sinceSequence?: number): Promise; /** Merge operations from another embedded replica and notify live collections. */ applyOperations(operations: EmbeddedOperation[]): Promise<{ applied: number; ignored: number; }>; /** Exchange durable operations with another embedded replica in both directions. */ synchronizeWith(peer: StateFirstDB): Promise<{ sent: number; received: number; applied: number; ignored: number; }>; /** Route a capability to the first available embedded provider and audit failover attempts. */ executeCapabilityWithFailover(name: string, input: unknown, providers?: StateFirstDB[]): Promise<{ output: T; provider: string; attempts: number; }>; /** Inspect the causal operation that currently materializes a remote record. */ recordProvenance(collection: string, id: string): Promise; /** Persist immutable content by hash; repeated bytes deduplicate automatically. */ storeContent(content: Uint8Array): Promise<{ hash: string; bytes: number; ref: string; }>; /** Resolve verified immutable content locally or from configured peers. */ acquireContent(hash: string): Promise; /** Define a durable workflow whose lifecycle is ordinary replicated state. */ defineWorkflow(name: string, steps: string[]): Promise; startWorkflow(name: string, input?: unknown): Promise; claimWorkflowStep(runId: string, step: string, worker: string, leaseMs?: number): Promise; completeWorkflowStep(runId: string, step: string, claimId: string, result?: unknown): Promise; /** Define and start state-first agents; workers observe and advance these records externally. */ defineStateAgent(name: string, capabilities?: string[], constraints?: unknown): Promise; startStateAgent(name: string, goal: string, input?: unknown): Promise; /** * Define an agent with declarative configuration. * * Agents are durable, addressable participants in the FeltDB fabric. * * @example * const researcher = db.defineAgent({ * name: "researcher", * version: 1, * capabilities: ["vector-search", "document-read", "report-write"], * constraints: { maxLatency: 5000 } * }); */ defineAgent(definition: AgentDefinition): AgentRef; /** * Get an agent by name. * * Returns the latest version of the agent if it exists. * * @example * const researcher = db.agent("researcher"); */ agent(name: string): AgentRef | undefined; /** * Get the agent registry */ getAgentRegistry(): AgentRegistry; /** * Get the agent runtime */ getAgentRuntime(): AgentRuntime; /** * Create an agent execution */ createAgentExecution(agentRef: AgentRef, goal: string, inputs: string[]): Promise; private agentExecutionRecord; /** Claim and durably materialize an embedded agent execution. */ startAgentExecution(execution: AgentExecution, peerId?: string): Promise; /** Advance an agent lifecycle and expose the transition as ordinary state. */ transitionAgentExecution(execution: AgentExecution, status: import('./agent.js').AgentExecutionStatus): Promise; completeAgentExecution(execution: AgentExecution, resultRef: string): Promise; failAgentExecution(execution: AgentExecution, error: string): Promise; /** * Close the database and clean up resources. */ close(): Promise; /** * Get current sync state information. * * @example * const syncState = db.sync(); * console.log(`Connected to ${syncState.connected_peers.length} peers`); */ sync(): SyncInfo; sync(config: SyncConfig): SyncController; /** * Add a peer for synchronization. * * @example * await db.addSyncPeer('peer-123'); */ addSyncPeer(peerId: string): Promise; /** * Remove a peer from synchronization. * * @example * await db.removeSyncPeer('peer-123'); */ removeSyncPeer(peerId: string): Promise; /** * Get pending operations for a peer. * * @example * const ops = await db.getPendingForPeer('peer-123', 5); */ getPendingForPeer(peerId: string, sinceSequence: number): Promise; /** * Acknowledge receipt of operations from a peer. * * @example * await db.acknowledgePeerOperations('peer-123', 10); */ acknowledgePeerOperations(peerId: string, sequence: number): Promise; /** * Get the instance ID for this FeltDB instance. * * @example * const id = db.instanceId(); */ instanceId(): string; /** * Get the current sequence number for this instance. * * **Not a freshness signal.** It means a different thing in each runtime and * never reflects a write made by another process, tab, or node. Use * {@link StateFirstDB.freshness} to find out whether cached state can be validated, * and {@link StateFirstDB.revision} to validate it. * * @example * const seq = db.getSequence(); */ getSequence(): number; /** * What freshness validation this runtime can honestly support. * * Runtimes differ because their consistency domains differ, not because some * are unfinished. A runtime with no serialization authority over its writers * reports `validation: 'refresh'`, and that is the correct answer for it. * * @example * const capability = await db.freshness(); * if (capability.validation === 'revision') { * const revision = await db.revision(); * } */ freshness(): Promise; /** * The current committed-state revision. * * Throws unless {@link StateFirstDB.freshness} advertises revision validation, and * throws if the runtime returns a revision from a scope it did not advertise. * A revision is comparable only against one carrying the same scope. * * @example * const before = await db.revision(); * // ... work ... * const stillCurrent = isCacheCurrent(before, await db.revision()); */ revision(): Promise; /** * Register a trigger that maps operations to executions * * @example * await db.registerTrigger({ * triggerId: "order-created", * capability: "process_order", * eventType: "OrderCreated", * collection: "orders" * }); */ registerTrigger(trigger: any): Promise; /** * Register a cron schedule * * @example * await db.scheduleCron({ * cronId: "daily-reports", * name: "Daily Reports", * cronExpr: "0 0 * * *", * capability: "generate_reports" * }); */ scheduleCron(schedule: any): Promise; /** * Get pending executions * * @example * const pending = await db.getPendingExecutions(); */ getPendingExecutions(): Promise; /** * Mark an execution as complete * * @example * await db.completeExecution("exec-1", { success: true }); */ completeExecution(executionId: string, result: any): Promise; /** * Read canonical durable provenance for a flow reference. * * Shows how a record was created, what operations it depended on, * which workflows/capabilities produced it, etc. * * @example * const provenance = await db.provenance('flow://documents/report-123'); */ provenance(flowRef: string): Promise; /** * Get runtime health and diagnostics information. * * Provides a comprehensive view of system health across all components. * Useful for debugging distributed issues and monitoring system status. * * @example * const health = db.health(); * if (health.status === 'unhealthy') { * for (const issue of health.issues) { * console.warn(`${issue.component}: ${issue.message}`); * } * } */ health(): RuntimeDiagnostics; /** * F1: Atomic Scoped Sequence Allocation * * Allocates monotonically increasing integers within a named scope. * Guarantees: * - No collisions even under concurrent calls * - Monotonic ordering (no gaps) * - Durability (survives restarts and crashes) * * Supported by: FileJsDb (Node.js) * * @example * const sequence = await db.allocateSequence({ * scope: "conversation", * scopeId: "conv-123" * }); * // sequence is guaranteed unique within "conversation:conv-123" scope */ allocateSequence(params: { scope: string; scopeId: string; }): Promise; /** * F2: Durable Idempotent Mutation * * Atomically inserts a value only if the key doesn't already exist. * On replay/retry with the same key, returns the original value unchanged. * * Guarantees: * - Exactly one write per unique key * - Original value is never overwritten by competing writes * - Idempotency is durable (survives restarts) * * Supported by the file runtime and by any authority-backed runtime, which * carries the same condition through its atomic transaction. * * @example * const result = await db.putIfAbsent("message:msg-123", JSON.stringify(message)); * if (result.inserted) { * // First successful write * } else { * // Retry/replay - same key was already present * } */ putIfAbsent(key: string, value: string): Promise<{ inserted: boolean; value: string; }>; /** * F3: Compare-And-Set with Version Detection * * Atomically updates a value only if the current version matches the expected version. * On version mismatch, returns the current version instead of silently overwriting. * * Guarantees: * - Exactly one concurrent writer succeeds (others detect conflict) * - Final state is always one of the N submitted updates (never partial/mixed) * - Version information is durable (survives restarts) * * Supported by the file runtime and by any authority-backed runtime, which * carries the same fence through its atomic transaction. * * @example * const result = await db.cas({ * key: "task:task-123", * expectedVersion: 1, * value: JSON.stringify({ ...task, __version: 2, status: "approved" }) * }); * * if (result.updated) { * // Update succeeded * } else { * // Version conflict - caller detects currentVersion and retries if needed * } */ cas(params: { key: string; expectedVersion: number; value: string; }): Promise<{ updated: boolean; currentVersion: number; }>; } /** * Open a state-first database instance. * * The database automatically handles: * - Persistence (transparent to application) * - Reactive updates (live queries by default) * - Relationship loading * - Differential updates (single record mutations don't re-emit entire collection) * * @example * const db = await open(jsDbInstance); * const users = db.collection("users"); * users.subscribe((users) => render(users)); * * @param jsDb The underlying JsDb WASM instance * @returns A new StateFirstDB instance */ export declare function open(jsDb: JsDb): Promise; /** * Helper to create a relationship between two collections. * * @example * const projectTasks = new Relationship( * db.collection("tasks"), * (task) => task.projectId * ); * * const tasks = await projectTasks.load(projectId); */ export declare function createRelationship(childCollection: Collection, foreignKey: (child: Child) => string | number): Relationship; //# sourceMappingURL=db.d.ts.map