UNPKG

mcard-js

Version:

MCard - Content-addressable storage with cryptographic hashing, handle resolution, and vector search for Node.js and browsers

1,050 lines (1,019 loc) 35.7 kB
import { M as MCard } from './StorageAdapter-Dw1BeOam.js'; export { P as Page, S as StorageEngine } from './StorageAdapter-Dw1BeOam.js'; import { CardCollection, Either, IO, Maybe } from './index.browser.js'; export { ALGORITHM_HIERARCHY, ContentHandle, ContentTypeInterpreter, EVENT_CONSTANTS, ErrorCodes, ExecutionResult, FaroSidecar, FaroSidecarConfig, GTime, HandleValidationError, HashValidator, IndexedDBEngine, JsonRpcRequest, JsonRpcResponse, LensProtocol, LivenessMetric, MCardStore, PolynomialTerm, PrimeHash, Reader, SafetyViolation, ServiceWorkerPTR, State, ValidationRegistry, VerificationStatus, Writer, computeHash, validateHandle, validationRegistry } from './index.browser.js'; export { SqliteWasmEngine } from './storage/SqliteWasmEngine.js'; export { SqliteNodeEngine } from './storage/SqliteNodeEngine.js'; import '@grafana/faro-web-sdk'; /** * SandboxWorker - Execute code in isolated Web Worker * * Provides safe execution environment for PCard logic. * Supports multiple runtimes: * - JavaScript: Native execution via Function() * - Python: Execution via Pyodide (WebAssembly Python) * * @see https://pyodide.org/en/stable/ */ /** Supported runtime types */ type RuntimeType = 'javascript' | 'python' | 'js' | 'py'; /** * SandboxWorker - Manages Web Worker for isolated execution * * Supports multiple runtimes: * - javascript/js: Native JS execution * - python/py: Python via Pyodide (WebAssembly) */ declare class SandboxWorker { private worker; private pythonLoaded; private pendingRequests; private defaultTimeout; /** * Initialize the sandbox worker */ init(): Promise<void>; private requestCounter; /** * Execute code in sandbox * @param code - Code to execute * @param input - Input data for the code * @param context - Optional execution context * @param runtime - Runtime to use: 'javascript' (default) or 'python' */ execute(code: string, input: unknown, context?: Record<string, unknown>, runtime?: RuntimeType): Promise<unknown>; /** * Preload a runtime for faster first execution * Useful for Python which requires loading Pyodide (~10MB) * @param runtime - Runtime to preload: 'python' or 'javascript' */ preloadRuntime(runtime?: RuntimeType): Promise<{ loaded: boolean; runtime: string; }>; /** * Check if Python runtime is loaded */ isPythonLoaded(): boolean; /** * Verify output matches expected * Note: Uses internal JSON-RPC format with direct values */ verify(hash: string, expectedOutput: unknown, actualOutput: unknown): Promise<{ verified: boolean; }>; /** * Send request and wait for response */ private sendRequest; /** * Handle worker message */ private handleMessage; /** * Handle worker error */ private handleError; /** * Terminate the worker */ terminate(): void; /** * Set timeout for requests */ setTimeout(ms: number): void; } interface NormalizedReadResult { text: string; originalSize: number; originalSha256Prefix: string; } /** * Stream-read bytes up to byte_cap, decode, and soft wrap. */ declare function streamReadNormalizedText(filePath: string, options: { byteCap: number; wrapWidth: number; }): Promise<NormalizedReadResult>; interface FileProcessingResult$1 { content: Uint8Array | string; filename: string; mimeType: string; extension: string; isBinary: boolean; size: number; } /** * Check if a file is likely to cause processing issues. */ declare function isProblematicFile(filePath: string): Promise<boolean>; /** * Safely read a file with limits and timeouts. */ declare function readFileSafely(filePath: string, options?: { allowPathological?: boolean; maxBytes?: number; }): Promise<Uint8Array>; /** * List files in directory, filtering out problematic ones. */ declare function listFiles(dirPath: string, recursive?: boolean): Promise<string[]>; /** * Process a file and return metadata and content. */ declare function processFileContent(filePath: string, options?: { forceBinary?: boolean; allowPathological?: boolean; maxBytes?: number; }): Promise<FileProcessingResult$1>; type FileIO_NormalizedReadResult = NormalizedReadResult; declare const FileIO_isProblematicFile: typeof isProblematicFile; declare const FileIO_listFiles: typeof listFiles; declare const FileIO_processFileContent: typeof processFileContent; declare const FileIO_readFileSafely: typeof readFileSafely; declare const FileIO_streamReadNormalizedText: typeof streamReadNormalizedText; declare namespace FileIO { export { type FileProcessingResult$1 as FileProcessingResult, type FileIO_NormalizedReadResult as NormalizedReadResult, FileIO_isProblematicFile as isProblematicFile, FileIO_listFiles as listFiles, FileIO_processFileContent as processFileContent, FileIO_readFileSafely as readFileSafely, FileIO_streamReadNormalizedText as streamReadNormalizedText }; } interface FileProcessingResult { hash: string; contentType?: string; isBinary?: boolean; filename?: string; size?: number; filePath: string; originalSize?: number; originalSha256Prefix?: string; metadataOnly?: boolean; } declare function processAndStoreFile(filePath: string, collection: CardCollection, options?: { allowProblematic?: boolean; maxBytesOnProblem?: number; metadataOnly?: boolean; rootPath?: string; }): Promise<FileProcessingResult | null>; interface LoaderMetrics { filesCount: number; directoriesCount: number; directoryLevels: number; } interface LoaderResponse { metrics: LoaderMetrics; results: FileProcessingResult[]; } declare function loadFileToCollection(targetPath: string, collection: CardCollection, options?: { recursive?: boolean; includeProblematic?: boolean; maxBytesOnProblem?: number; metadataOnly?: boolean; }): Promise<LoaderResponse>; type Loader_FileProcessingResult = FileProcessingResult; type Loader_LoaderMetrics = LoaderMetrics; type Loader_LoaderResponse = LoaderResponse; declare const Loader_loadFileToCollection: typeof loadFileToCollection; declare const Loader_processAndStoreFile: typeof processAndStoreFile; declare namespace Loader { export { type Loader_FileProcessingResult as FileProcessingResult, type Loader_LoaderMetrics as LoaderMetrics, type Loader_LoaderResponse as LoaderResponse, Loader_loadFileToCollection as loadFileToCollection, Loader_processAndStoreFile as processAndStoreFile }; } interface Runtime { execute(codeOrPath: string, context: unknown, config: any, chapterDir: string): Promise<unknown>; } declare class LLMConfig { provider: string; model: string | null; endpoint_url: string | null; api_key: string | null; system_prompt: string; assistant_instruction: string; temperature: number; max_tokens: number; top_p: number; top_k: number | null; frequency_penalty: number; presence_penalty: number; stop_sequences: string[]; response_format: string; json_schema: Record<string, any> | null; timeout: number; retry_count: number; retry_delay: number; stream: boolean; constructor(data?: Partial<LLMConfig>); validate(): void; get effective_model(): string; get effective_base_url(): string; to_provider_params(): Record<string, any>; static from_concrete(concrete: any, context?: any): LLMConfig; } /** * LLM Provider Interface * * Abstract interface for LLM providers. * Replicates mcard.ptr.core.llm.providers.base.LLMProvider */ interface ChatMessage { role: string; content: string; } interface LLMProvider { provider_name: string; /** * Generate text completion for a prompt. */ complete(prompt: string, params: Record<string, any>): Promise<Either<string, string>>; /** * Generate chat completion from messages. */ chat(messages: ChatMessage[], params: Record<string, any>): Promise<Either<string, Record<string, any>>>; /** * Check if the provider service is available. */ validate_connection(): Promise<boolean>; /** * List available models from the provider. */ list_models(): Promise<Either<string, string[]>>; /** * Get provider status information. */ get_status(): Promise<Record<string, any>>; } /** * LLM Runtime Module * * Provides LLMRuntime for executing LLM prompts as part of the PTR polyglot runtime system. * Replicates mcard.ptr.core.llm.runtime.LLMRuntime */ declare class LLMRuntime implements Runtime { provider_name: string; private _provider; constructor(provider_name?: string); get provider(): LLMProvider; execute(codeOrPath: string, context: unknown, config: any, chapterDir: string): Promise<unknown>; private _execute_completion; private _execute_chat; private _format_response; } /** * Create a monadic LLM completion execution. * * Returns IO<Either<string, any>> for functional composition. */ declare function promptMonad(prompt: string, config?: Partial<LLMConfig>): IO<Either<string, any>>; /** * Create a monadic LLM chat execution. * * Returns IO<Either<string, any>> for functional composition. */ declare function chatMonad(messages?: any[] | null, prompt?: string | null, system_prompt?: string, config?: Partial<LLMConfig>): IO<Either<string, any>>; /** * Lambda Term - Algebraic Data Type for Lambda Calculus * * Represents Lambda Calculus terms as content-addressable MCards. * Each term variant is stored as JSON in MCard content, with sub-terms * referenced by their SHA-256 hashes for structural sharing. * * The three term constructors mirror the BNF grammar: * M, N ::= x | λx.M | M N * * @module mcard-js/ptr/lambda/LambdaTerm */ /** * Variable term: x */ interface VarTerm { readonly tag: 'Var'; readonly name: string; } /** * Abstraction term: λx.M * Body is stored as MCard hash for structural sharing */ interface AbsTerm { readonly tag: 'Abs'; readonly param: string; readonly body: string; } /** * Application term: M N * Both function and argument are MCard hashes */ interface AppTerm { readonly tag: 'App'; readonly func: string; readonly arg: string; } /** * Union type for all Lambda terms */ type LambdaTerm = VarTerm | AbsTerm | AppTerm; /** * Create a variable term */ declare function mkVar(name: string): VarTerm; /** * Create an abstraction term */ declare function mkAbs(param: string, bodyHash: string): AbsTerm; /** * Create an application term */ declare function mkApp(funcHash: string, argHash: string): AppTerm; /** * Serialize a Lambda term to MCard content (JSON string) */ declare function serializeTerm(term: LambdaTerm): string; /** * Deserialize MCard content to Lambda term */ declare function deserializeTerm(content: string): LambdaTerm; /** * Create an MCard from a Lambda term */ declare function termToMCard(term: LambdaTerm): Promise<MCard>; /** * Extract Lambda term from MCard */ declare function mcardToTerm(mcard: MCard): LambdaTerm; /** * Store a Lambda term in the collection and return its hash */ declare function storeTerm(collection: CardCollection, term: LambdaTerm): Promise<string>; /** * Retrieve a Lambda term from the collection by hash */ declare function loadTerm(collection: CardCollection, hash: string): Promise<LambdaTerm | null>; /** * Check if a term exists in the collection */ declare function termExists(collection: CardCollection, hash: string): Promise<boolean>; /** * Pretty-print a Lambda term (shallow - shows hashes for subterms) */ declare function prettyPrintShallow(term: LambdaTerm): string; /** * Pretty-print a Lambda term (deep - resolves all subterms from collection) */ declare function prettyPrintDeep(collection: CardCollection, hash: string): Promise<string>; declare function isVar(term: LambdaTerm): term is VarTerm; declare function isAbs(term: LambdaTerm): term is AbsTerm; declare function isApp(term: LambdaTerm): term is AppTerm; /** * Free Variables Analysis * * Computes the set of free variables in a Lambda term. * Free variables are those not bound by any enclosing λ. * * FV(x) = {x} * FV(λx.M) = FV(M) \ {x} * FV(M N) = FV(M) ∪ FV(N) * * @module mcard-js/ptr/lambda/FreeVariables */ /** * Compute free variables of a term (by hash) * Returns IO<Maybe<Set<string>>> - Nothing if term not found */ declare function freeVariables(collection: CardCollection, termHash: string): IO<Maybe<Set<string>>>; /** * Compute bound variables of a term (by hash) * Bound variables are those occurring in binding positions (λx) */ declare function boundVariables(collection: CardCollection, termHash: string): IO<Maybe<Set<string>>>; /** * Check if a variable is free in a term */ declare function isFreeIn(collection: CardCollection, variable: string, termHash: string): IO<boolean>; /** * Check if a term is closed (has no free variables) */ declare function isClosed(collection: CardCollection, termHash: string): IO<boolean>; /** * Generate a fresh variable name that is not in the given set. * Uses primes (x, x', x'', ...) to match Python implementation. */ declare function generateFresh(base: string, avoid: Set<string>): string; /** * Generate a fresh variable avoiding all variables in a term */ declare function generateFreshFor(collection: CardCollection, base: string, termHash: string): Promise<string>; declare function difference<T>(a: Set<T>, b: Set<T>): Set<T>; declare function intersection<T>(a: Set<T>, b: Set<T>): Set<T>; /** * Alpha Conversion (α-conversion) * * Renames bound variables in Lambda terms while preserving meaning. * * Rule: λx.M ≡α λy.M[x:=y] (where y is fresh) * * Alpha conversion is the basis of variable renaming and is essential * for avoiding variable capture during beta reduction. * * @module mcard-js/ptr/lambda/AlphaConversion */ /** * Alpha-rename: Rename the bound variable of an abstraction * * λx.M → λy.M[x:=y] * * @param collection - Card collection for term storage * @param absHash - Hash of the abstraction term * @param newParam - New name for the bound variable * @returns IO<Either<error, newHash>> */ declare function alphaRename(collection: CardCollection, absHash: string, newParam: string): IO<Either<string, string>>; /** * Check if two terms are alpha-equivalent * * Two terms are α-equivalent if they differ only in the names of bound variables. * * Note: If hashes are equal, terms are definitionally identical (stronger than α-equiv). */ declare function alphaEquivalent(collection: CardCollection, hash1: string, hash2: string): IO<Either<string, boolean>>; /** * Alpha-normalize a term using canonical variable names * * All bound variables are renamed to a₀, a₁, a₂... based on binding depth. * This produces a canonical representative of the α-equivalence class. */ declare function alphaNormalize(collection: CardCollection, termHash: string): IO<Either<string, string>>; /** * Beta Reduction (β-reduction) * * The computational heart of Lambda Calculus - function application. * * Rule: (λx.M) N →β M[x:=N] * * A term of the form (λx.M) N is called a "beta-redex" (reducible expression). * Beta reduction substitutes the argument N for all free occurrences of x in M. * * IMPORTANT: Must handle capture avoidance - if N contains free variables * that would become bound in M, we must α-rename first. * * @module mcard-js/ptr/lambda/BetaReduction */ /** * Check if a term is a beta-redex: (λx.M) N */ declare function isRedex(collection: CardCollection, termHash: string): IO<boolean>; /** * Find the leftmost-outermost redex (normal order reduction) * Returns Maybe<hash of redex> */ declare function findLeftmostRedex(collection: CardCollection, termHash: string): IO<Maybe<string>>; /** * Find the leftmost-innermost redex (applicative order reduction) */ declare function findInnermostRedex(collection: CardCollection, termHash: string): IO<Maybe<string>>; /** * Perform a single beta reduction step on a redex * * (λx.M) N →β M[x:=N] * * @param collection - Card collection * @param redexHash - Hash of the application term (λx.M) N * @returns Either<error, resultHash> */ declare function betaReduce(collection: CardCollection, redexHash: string): IO<Either<string, string>>; type ReductionStrategy = 'normal' | 'applicative' | 'lazy'; /** * Perform one reduction step using the specified strategy */ declare function reduceStep(collection: CardCollection, termHash: string, strategy?: ReductionStrategy): IO<Maybe<string>>; interface NormalizationResult { normalForm: string; steps: number; reductionPath: string[]; } /** * Normalize a term to its normal form (no more redexes) * * @param collection - Card collection * @param termHash - Starting term * @param strategy - Reduction strategy * @param maxSteps - Maximum reduction steps (prevent infinite loops) * @returns Either<error, NormalizationResult> */ declare function normalize(collection: CardCollection, termHash: string, strategy?: ReductionStrategy, maxSteps?: number, maxTimeMs?: number, onStep?: (step: number, hash: string) => Promise<void>): IO<Either<string, NormalizationResult>>; /** * Check if a term is in normal form (has no redexes) */ declare function isNormalForm(collection: CardCollection, termHash: string): IO<boolean>; /** * Check if a term has a normal form (is normalizing) * * Note: This is undecidable in general, so we use a bounded check */ declare function hasNormalForm(collection: CardCollection, termHash: string, maxSteps?: number): IO<boolean>; /** * Eta Conversion (η-conversion) * * Captures extensional equality of functions. * * η-reduction: λx.(f x) →η f (if x ∉ FV(f)) * η-expansion: f →η λx.(f x) (where x is fresh) * * Two functions are η-equivalent if they produce the same output for all inputs. * This is the principle of extensionality: functions are determined by their behavior. * * @module mcard-js/ptr/lambda/EtaConversion */ /** * Check if a term is an η-redex: λx.(f x) where x ∉ FV(f) */ declare function isEtaRedex(collection: CardCollection, termHash: string): IO<boolean>; /** * Eta reduction: λx.(f x) →η f * * Only valid if x does not occur free in f. * * @param collection - Card collection * @param termHash - Hash of the abstraction λx.(f x) * @returns Maybe<resultHash> - Nothing if not an η-redex */ declare function etaReduce(collection: CardCollection, termHash: string): IO<Maybe<string>>; /** * Try eta reduction, returning Either for error handling */ declare function etaReduceE(collection: CardCollection, termHash: string): IO<Either<string, string>>; /** * Eta expansion: f →η λx.(f x) * * Wraps a function in a lambda that immediately applies it. * The new variable must be fresh (not occurring in f). * * @param collection - Card collection * @param termHash - Hash of the term to expand * @param baseName - Base name for the fresh variable (default: 'x') * @returns Hash of the expanded term λx.(f x) */ declare function etaExpand(collection: CardCollection, termHash: string, baseName?: string): IO<string>; /** * Check if two terms are η-equivalent * * Two terms f and g are η-equivalent if: * - They are the same, or * - One η-reduces to the other, or * - They both η-expand to equivalent terms */ declare function etaEquivalent(collection: CardCollection, hash1: string, hash2: string): IO<boolean>; /** * Eta-normalize a term by reducing all η-redexes */ declare function etaNormalize(collection: CardCollection, termHash: string): IO<string>; /** * Find all η-redexes in a term */ declare function findEtaRedexes(collection: CardCollection, termHash: string): IO<string[]>; /** * IO Effects - Observable side-effects for Lambda Calculus computations * * Implements the IO Monad pattern for CLM: * IO a = World → (a, World') * * In our context: * Reduction = TermHash → (TermHash', IOEffects) * * IO effects are purely observational - they do not affect computation results. * The same input will always produce the same output regardless of IO configuration. * * @module mcard-js/ptr/lambda/IOEffects */ type IOFormat = 'minimal' | 'verbose' | 'json'; interface NetworkConfig { enabled: boolean; endpoint?: string; method?: 'POST' | 'PUT'; headers?: Record<string, string>; } interface IOEffectsConfig { enabled: boolean; console?: boolean; network?: NetworkConfig; onStep?: boolean; onComplete?: boolean; onError?: boolean; format?: IOFormat; } /** * Lambda Runtime - PTR Runtime for Lambda Calculus * * Implements α-β-η conversions as a PTR runtime, treating MCard hashes * as Lambda terms and performing computations that produce new MCards. * * This runtime can be used via CLM specifications to define and verify * Lambda Calculus reductions. * * @module mcard-js/ptr/lambda/LambdaRuntime */ type LambdaOperation = 'alpha' | 'beta' | 'eta-reduce' | 'eta-expand' | 'normalize' | 'step' | 'alpha-equiv' | 'eta-equiv' | 'alpha-norm' | 'eta-norm' | 'free-vars' | 'is-closed' | 'is-normal' | 'parse' | 'pretty' | 'build' | 'check-readiness' | 'num-add' | 'num-sub' | 'num-mul' | 'num-div' | 'http-request' | 'church-to-int'; interface LambdaConfig { operation?: LambdaOperation; process?: LambdaOperation; action?: LambdaOperation; strategy?: ReductionStrategy; maxSteps?: number; maxTimeMs?: number; newName?: string; freshVar?: string; compareWith?: string; io_effects?: Partial<IOEffectsConfig>; } interface LambdaRuntimeResult { success: boolean; result?: unknown; error?: string; termHash?: string; prettyPrint?: string; } /** * Lambda Calculus Runtime for PTR * * Executes Lambda Calculus operations on MCard-stored terms. */ declare class LambdaRuntime implements Runtime { private collection; constructor(collection: CardCollection); /** * Execute a Lambda operation * * @param codeOrPath - For Lambda runtime, this is the term hash to operate on * @param context - Additional context (varies by operation) * @param config - Lambda configuration with operation type * @param chapterDir - Chapter directory (used for relative paths if needed) */ execute(codeOrPath: string, context: unknown, config: any, chapterDir: string): Promise<LambdaRuntimeResult>; private doAlphaRename; private doBetaReduce; private doEtaReduce; private doEtaExpand; private doNormalize; private doStep; private doAlphaEquiv; private doEtaEquiv; private doAlphaNormalize; private doEtaNormalize; private doFreeVars; private doIsClosed; private doIsNormal; private doParse; private doPretty; private doBuild; /** * Decode a Church numeral to a regular integer. * Church numeral n = λf.λx.f^n(x) where f is applied n times. * * Algorithm: * 1. Normalize the term first * 2. Expect form: Abs(f, Abs(x, body)) * 3. Count how many times 'f' appears in application position in body */ private doChurchToInt; /** * Count applications in a Church numeral body. * Church numeral n has the form: λf.λx.f(f(f(...f(x)...))) * where f appears n times. */ private countChurchApplications; private doCheckReadiness; private doNumericOp; private doHttpRequest; } /** * Parse a simple Lambda expression string into MCards * * Syntax: * x, y, z - Variables * \x.M or λx.M - Abstraction * (M N) - Application * M N - Application (left-associative) * * Examples: * \x.x - Identity function * \f.\x.f x - Application combinator * (\x.x) y - Identity applied to y */ declare function parseLambdaExpression(collection: CardCollection, expression: string): Promise<string>; /** * Lambda Calculus Module for PTR * * Implements α-β-η conversions on MCard-stored Lambda terms. * * This module provides: * - LambdaTerm ADT: Var, Abs, App stored as MCard content * - Alpha Conversion: Variable renaming * - Beta Reduction: Function application * - Eta Conversion: Extensional equivalence * - LambdaRuntime: PTR-compatible runtime for CLM execution * * @module mcard-js/ptr/lambda */ type index_AbsTerm = AbsTerm; type index_AppTerm = AppTerm; type index_LambdaConfig = LambdaConfig; type index_LambdaOperation = LambdaOperation; type index_LambdaRuntime = LambdaRuntime; declare const index_LambdaRuntime: typeof LambdaRuntime; type index_LambdaRuntimeResult = LambdaRuntimeResult; type index_LambdaTerm = LambdaTerm; type index_NormalizationResult = NormalizationResult; type index_ReductionStrategy = ReductionStrategy; type index_VarTerm = VarTerm; declare const index_alphaEquivalent: typeof alphaEquivalent; declare const index_alphaNormalize: typeof alphaNormalize; declare const index_alphaRename: typeof alphaRename; declare const index_betaReduce: typeof betaReduce; declare const index_boundVariables: typeof boundVariables; declare const index_deserializeTerm: typeof deserializeTerm; declare const index_difference: typeof difference; declare const index_etaEquivalent: typeof etaEquivalent; declare const index_etaExpand: typeof etaExpand; declare const index_etaNormalize: typeof etaNormalize; declare const index_etaReduce: typeof etaReduce; declare const index_etaReduceE: typeof etaReduceE; declare const index_findEtaRedexes: typeof findEtaRedexes; declare const index_findInnermostRedex: typeof findInnermostRedex; declare const index_findLeftmostRedex: typeof findLeftmostRedex; declare const index_freeVariables: typeof freeVariables; declare const index_generateFresh: typeof generateFresh; declare const index_generateFreshFor: typeof generateFreshFor; declare const index_hasNormalForm: typeof hasNormalForm; declare const index_intersection: typeof intersection; declare const index_isAbs: typeof isAbs; declare const index_isApp: typeof isApp; declare const index_isClosed: typeof isClosed; declare const index_isEtaRedex: typeof isEtaRedex; declare const index_isFreeIn: typeof isFreeIn; declare const index_isNormalForm: typeof isNormalForm; declare const index_isRedex: typeof isRedex; declare const index_isVar: typeof isVar; declare const index_loadTerm: typeof loadTerm; declare const index_mcardToTerm: typeof mcardToTerm; declare const index_mkAbs: typeof mkAbs; declare const index_mkApp: typeof mkApp; declare const index_mkVar: typeof mkVar; declare const index_normalize: typeof normalize; declare const index_parseLambdaExpression: typeof parseLambdaExpression; declare const index_prettyPrintDeep: typeof prettyPrintDeep; declare const index_prettyPrintShallow: typeof prettyPrintShallow; declare const index_reduceStep: typeof reduceStep; declare const index_serializeTerm: typeof serializeTerm; declare const index_storeTerm: typeof storeTerm; declare const index_termExists: typeof termExists; declare const index_termToMCard: typeof termToMCard; declare namespace index { export { type index_AbsTerm as AbsTerm, type index_AppTerm as AppTerm, type index_LambdaConfig as LambdaConfig, type index_LambdaOperation as LambdaOperation, index_LambdaRuntime as LambdaRuntime, type index_LambdaRuntimeResult as LambdaRuntimeResult, type index_LambdaTerm as LambdaTerm, type index_NormalizationResult as NormalizationResult, type index_ReductionStrategy as ReductionStrategy, type index_VarTerm as VarTerm, index_alphaEquivalent as alphaEquivalent, index_alphaNormalize as alphaNormalize, index_alphaRename as alphaRename, index_betaReduce as betaReduce, index_boundVariables as boundVariables, index_deserializeTerm as deserializeTerm, index_difference as difference, index_etaEquivalent as etaEquivalent, index_etaExpand as etaExpand, index_etaNormalize as etaNormalize, index_etaReduce as etaReduce, index_etaReduceE as etaReduceE, index_findEtaRedexes as findEtaRedexes, index_findInnermostRedex as findInnermostRedex, index_findLeftmostRedex as findLeftmostRedex, index_freeVariables as freeVariables, index_generateFresh as generateFresh, index_generateFreshFor as generateFreshFor, index_hasNormalForm as hasNormalForm, index_intersection as intersection, index_isAbs as isAbs, index_isApp as isApp, index_isClosed as isClosed, index_isEtaRedex as isEtaRedex, index_isFreeIn as isFreeIn, index_isNormalForm as isNormalForm, index_isRedex as isRedex, index_isVar as isVar, index_loadTerm as loadTerm, index_mcardToTerm as mcardToTerm, index_mkAbs as mkAbs, index_mkApp as mkApp, index_mkVar as mkVar, index_normalize as normalize, index_parseLambdaExpression as parseLambdaExpression, index_prettyPrintDeep as prettyPrintDeep, index_prettyPrintShallow as prettyPrintShallow, index_reduceStep as reduceStep, index_serializeTerm as serializeTerm, index_storeTerm as storeTerm, index_termExists as termExists, index_termToMCard as termToMCard }; } /** * Type definitions for CLM (Cubical Logic Model) execution. */ /** * CLM specification structure (parsed from YAML). */ interface CLMSpec { version: string; chapter: { id: number; title: string; mvp_card?: string; pkc_task?: string; }; clm: { abstract?: { concept?: string; purpose?: string; description?: string; goal?: string; context?: string; success_criteria?: string; [key: string]: unknown; }; abstract_spec?: CLMSpec['clm']['abstract']; concrete?: { manifestation?: string; description?: string; logic_source?: string; runtime?: string; builtin?: boolean; code_file?: string; entry_point?: string; inputs?: string[]; process?: string; outputs?: string[]; action?: string; boundary?: 'intrinsic' | 'extrinsic'; runtimes_config?: RuntimeConfig[]; [key: string]: unknown; }; concrete_impl?: CLMSpec['clm']['concrete']; balanced?: { expectation?: string; description?: string; test_cases?: unknown[]; examples?: unknown[]; [key: string]: unknown; }; balanced_exp?: CLMSpec['clm']['balanced']; }; examples?: CLMExample[]; } /** * Runtime configuration for multi-runtime CLMs. */ interface RuntimeConfig { name: string; file?: string; binary?: string; module?: string; entry?: string; } /** * CLM example definition. */ interface CLMExample { name: string; input?: unknown; expected_output?: unknown; result_contains?: string; [key: string]: unknown; } /** * Result of executing a single CLM. */ interface ExecutionResult { success: boolean; result?: unknown; error?: string; executionTime: number; clm: { chapter: string; concept: string; manifestation: string; boundary?: string; }; } /** * Result of executing on a single runtime (for multi-runtime). */ interface RuntimeResult { runtime: string; success: boolean; result?: unknown; error?: string; executionTime: number; } /** * Result of multi-runtime consensus execution. */ interface MultiRuntimeResult { success: boolean; consensus: boolean; results: RuntimeResult[]; consensusValue?: unknown; error?: string; executionTime: number; clm: { chapter: string; concept: string; manifestation: string; boundary?: string; }; } /** * Verification result (comparing actual vs expected). */ interface VerificationResult { verified: boolean; expected: unknown; actual: unknown; executionResult: ExecutionResult; } /** * Summary of running all examples in a CLM. */ interface RunExamplesSummary { total: number; passed: number; results: ExampleRunResult[]; } /** * Result of running a single example. */ interface ExampleRunResult { case: number; name: string; input: unknown; result: unknown; error?: string; expected: unknown; match: boolean; } /** * Execution report for external reporting. */ interface ExecutionReport { status: 'success' | 'failure'; result?: unknown; error?: string; chapter_id: number; chapter_title: string; } /** * Summary report for external reporting. */ interface SummaryReport { status: 'success' | 'failure'; result: { success: boolean; total: number; results: Array<{ case: number; name: string; result: unknown; error?: string; }>; }; chapter_id: number; chapter_title: string; } /** * CLM banner lines for display. */ interface CLMBannerLines { header: string[]; } /** * CLMRunner - Execute JavaScript logic from CLM specifications * * Node.js PTR runtime for interpreting Cubical Logic Models. * * Refactored to use modular components from ./clm/ */ declare class CLMRunner { private loader; private timeout; private collection?; constructor(basePath?: string, timeout?: number, collection?: CardCollection); /** * Run a CLM directly from a file path. */ runFile(clmPath: string, input?: unknown): Promise<ExecutionResult>; /** * Execute a CLM specification with given input. * * Implements Petri Net Transition Semantics: * 1. Constructs PCard (Transition) * 2. Checks Pre-conditions (Firing Rule) * 3. Executes Logic * 4. Produces VerificationVCard (Token) * 5. Persists to Collection (Place) */ executeCLM(clm: CLMSpec, chapterDir: string, input: unknown): Promise<ExecutionResult>; /** * Execute a CLM across multiple runtimes and verify consensus. */ executeMultiRuntime(clm: CLMSpec, chapterDir: string, input: unknown): Promise<MultiRuntimeResult>; /** * Check if a CLM is a multi-runtime CLM. */ isMultiRuntime(clm: CLMSpec): boolean; /** * Verify CLM output against expected result. */ verifyCLM(clm: CLMSpec, chapterDir: string, input: unknown, expected: unknown): Promise<VerificationResult>; /** * Run all examples from a CLM specification. */ runExamples(clm: CLMSpec, chapterDir: string): Promise<Array<{ name: string; result: ExecutionResult; }>>; /** * Summarize example runs. */ summarizeExampleRuns(clm: CLMSpec, results: Array<{ name: string; result: ExecutionResult; }>): RunExamplesSummary; /** * Build CLM banner for display. */ buildCLMBanner(clm: CLMSpec): CLMBannerLines; /** * Build execution report. */ buildExecutionReport(clm: CLMSpec, execution: ExecutionResult): ExecutionReport; /** * Build summary report. */ buildSummaryReport(clm: CLMSpec, summary: RunExamplesSummary): SummaryReport; private executeLoader; private executeNetwork; private executeStandard; private executeRecursive; private resolveCodeOrPath; private buildNetworkContext; private buildJavaScriptContext; private buildRunCLM; } export { CLMRunner, CardCollection, Either, FileIO, IO, LLMConfig, LLMRuntime, index as Lambda, LambdaRuntime, Loader, MCard, Maybe, SandboxWorker, chatMonad, promptMonad };