mcard-js
Version:
MCard - Content-addressable storage with cryptographic hashing, handle resolution, and vector search for Node.js and browsers
381 lines (377 loc) • 14 kB
TypeScript
/**
* DOTS Vocabulary Types
*
* From the Double Operadic Theory of Systems (DOTS), this module provides
* a minimal, domain-independent vocabulary for describing compositional systems.
*
* The MVP Cards architecture maps directly to DOTS:
* - MCard → Carrier (the actual data/systems)
* - PCard → Lens (tight) + Chart (loose)
* - VCard → Arena + Action
*
* Reference: docs/WorkingNotes/Hub/Theory/Integration/DOTS Vocabulary as Efficient Representation for ABC Curriculum.md
*/
/**
* DOTS Role enumeration
*
* These nine terms (seven structural + Action + Unit) form a complete,
* compositional language for describing any system, interface, or interaction.
*/
declare enum DOTSRole {
/**
* CARRIER - Category Car(S) of all actual data/systems
*
* MCard is the Carrier. Each MCard is an Object in the Carrier category;
* each hash-link is a Morphism in Car(S).
*
* Polynomial Form: Objects = MCards, Morphisms = hash references
*/
CARRIER = "Carrier",
/**
* LENS - Tight morphism (structure-preserving interface map)
*
* PCard's abstract_spec ↔ concrete_impl relationship is a Lens.
* Ensures type safety: Abstract types match Concrete types.
*
* Lens = (get, put) pair with coherence laws
*/
LENS = "Lens",
/**
* CHART - Loose morphism (behavioral interaction pattern)
*
* PCard's balanced_expectations (tests) describe the wiring.
* Enables flexibility: same Abstract spec via different Concrete implementations.
*
* Chart = horizontal morphism in Target double category
*/
CHART = "Chart",
/**
* ARENA - Interface type (what can interact)
*
* VCard is the Arena. It defines the subject_did, capabilities[],
* and ExternalRef[]. An Arena is a pair of sets (Inputs, Outputs).
*
* Arena = (I, O) → Polynomial functor P(X) = Σ_{i∈I} X^{O(i)}
*/
ARENA = "Arena",
/**
* ACTION - Module structure where interactions act on systems
*
* VCard enables Action: interactions (Charts/PCards) act on
* systems (MCards/Carrier) to produce new systems.
* The VCard authorization gate is the mechanism of this action.
*
* Action = Loose(I) ⊛ Car(S) → Car(S)
*/
ACTION = "Action",
/**
* TARGET - Double category I of all interfaces and interactions
*
* The CLM design space. Contains all possible Arenas (objects),
* Lenses (tight morphisms), and Charts (loose morphisms).
*/
TARGET = "Target",
/**
* TIGHT - Vertical composition direction (strict)
*
* Prerequisites chains. Cannot skip foundational concepts.
* Ensures type safety across compositions.
*
* Vertical = mandatory sequential dependency
*/
TIGHT = "Tight",
/**
* LOOSE - Horizontal composition direction (flexible)
*
* Same concept via different interaction patterns.
* Enables behavioral flexibility while preserving semantics.
*
* Horizontal = parallel/interchangeable alternatives
*/
LOOSE = "Loose",
/**
* UNIT - Identity object for parallel composition
*
* Empty MCard / Root Namespace. The neutral element.
* For any system S: Unit ⊗ S ≅ S
*/
UNIT = "Unit"
}
/**
* EOS (Experimental-Operational Symmetry) Role
*
* Each MVP Card type enforces a specific dimension of symmetry
* to ensure environment-invariant correctness.
*/
declare enum EOSRole {
/**
* INVARIANT_CONTENT - The Galois Root
*
* MCard: Hash(Content) is a pure function.
* Same content in Dev = Same hash in Prod.
* Environment-invariant identity.
*/
INVARIANT_CONTENT = "InvariantContent",
/**
* GENERATIVE_LENS - Controlled Symmetry Breaking 1
*
* PCard: Pure function f(x)=y.
* Invariant in definition, variant only in input.
* The logic is environment-invariant.
*/
GENERATIVE_LENS = "GenerativeLens",
/**
* SOVEREIGN_DECISION - Controlled Symmetry Breaking 2
*
* VCard: The Gap Junction.
* Breaks symmetry by introducing Authority.
* Decisional reality creation.
*/
SOVEREIGN_DECISION = "SovereignDecision"
}
/**
* Card Plane in the MVP Cards architecture
*
* Maps to SDN (Software-Defined Networking) plane separation:
* Data Plane → Control Plane → Application Plane
*/
declare enum CardPlane {
/**
* DATA_PLANE - MCard
*
* Immutable, content-addressable storage.
* The monadic foundation that wraps effects.
* CRD-only operations (Create, Retrieve, Delete).
*/
DATA = "Data",
/**
* CONTROL_PLANE - PCard
*
* Polynomial functor composition.
* Monadic execution via PTR.
* Policy and logic gating.
*/
CONTROL = "Control",
/**
* APPLICATION_PLANE - VCard
*
* Value exchange and authentication.
* Side effect management (IO Monad).
* Sovereign memory and authorization.
*/
APPLICATION = "Application"
}
/**
* Polynomial Functor Type
*
* The mathematical foundation for DOTS.
* Every DOTS component is a polynomial functor of the form:
* P(X) = Σ_{i∈I} X^{O(i)}
*/
interface PolynomialFunctor {
/** Positions (I) - input types, system states */
positions: string[];
/** Directions O(i) - output types per position */
directions: Record<string, string[]>;
}
/**
* DOTS metadata that can be attached to any card type
*/
interface DOTSMetadata {
/** Primary DOTS role (Carrier, Lens, Chart, Arena, Action) */
role: DOTSRole;
/** EOS symmetry role */
eosRole?: EOSRole;
/** Card plane (Data, Control, Application) */
plane: CardPlane;
/** Polynomial functor representation (optional) */
polynomial?: PolynomialFunctor;
/** Tight morphism references (prerequisite hashes) */
tightRefs?: string[];
/** Loose morphism references (alternative implementation hashes) */
looseRefs?: string[];
}
/**
* MCard - Content-addressable data container (The Monad)
*
* ## Category Theory Role: MONAD
*
* MCard is the **Monad** in the MVP Cards categorical hierarchy:
* - **MCard (Monad)**: Data container with `unit` (create) and `bind` (chain)
* - **PCard (Functor)**: Pure transformation, `fmap` over MCard content
* - **VCard (Applicative)**: Context-aware application with pre-conditions
*
* ## Scale-Free Monadic Infrastructure: Spinoza-Leibniz Synthesis
*
* MCard implements the dual philosophical foundation:
*
* | Philosopher | Contribution | MCard Implementation |
* |-------------|--------------|---------------------|
* | **Spinoza** | One Substance (Deus sive Natura) | Fixed 3-field schema (Terminal Object) |
* | **Leibniz** | Infinite Monads (Pre-Established Harmony) | Infinite content-addressed entries |
* | **Both** | No windows / Internal causation | Content-addressing (same hash = same truth) |
*
* This enables **Experimental-Operational Symmetry (EOS)**: same behavior from
* a single user's PKC (100MB) to a planetary LLM registry (1PB).
*
* ## DOTS Vocabulary Role: CARRIER
*
* MCard is the **Carrier** in the Double Operadic Theory of Systems (DOTS).
* - Each MCard is an **Object** in the Carrier category Car(S)
* - Hash-links between MCards are **Morphisms** in Car(S)
* - The Carrier is the category of all actual data/systems
*
* ## Petri Net Role: TOKEN CONTENT
*
* In the Categorical Petri Net model:
* - **MCard content** is what tokens carry
* - **VCard** is the token type (Applicative wrapper)
* - **PCard** is the transition that transforms tokens
*
* ## MVP Cards Architecture: Data Plane
*
* ```
* ┌───────────────────────────────────────────────────────┐
* │ APPLICATION PLANE (VCard) │
* │ Petri Net Token / AuthN/AuthZ / Side Effects │
* └─────────────────────────┬─────────────────────────────┘
* │ (Pre-Condition Check)
* ┌─────────────────────────▼─────────────────────────────┐
* │ CONTROL PLANE (PCard) │
* │ Petri Net Transition / CLM Logic / Pure Function │
* └─────────────────────────┬─────────────────────────────┘
* │ (Content Transformation)
* ┌─────────────────────────▼─────────────────────────────┐
* │ DATA PLANE (MCard) ◀── YOU ARE HERE │
* │ Monad / Content-Addressable / Scale-Free Substrate │
* └───────────────────────────────────────────────────────┘
* ```
*
* ## The Empty Schema Principle (Kenosis)
*
* MCard embodies the Empty Schema Principle:
* - Schema contains NO domain-specific terms (only hash, content, g_time)
* - Domain customization happens via data (INSERT), not schema changes
* - Universal applicability: same structure for ANY domain
* - This emptiness enables universality (Kenosis in code)
*
* ## Three Tables as Irreducible Semiotic Triad
*
* The MCard infrastructure uses three tables (Peirce's semiotics):
* - `card` (Object/Referent): what the content means
* - `handle_registry` (Representamen/Sign): which concept is named
* - `handle_history` (Interpretant): how understanding evolved
*
* ## Functional Requirements
*
* | ID | Requirement | Implementation |
* |----|-------------|----------------|
* | M-1 | Content-addressable via hash | `this.hash = SHA-256(content)` |
* | M-2 | CRD-only (no UPDATE) | Immutable class, `readonly` fields |
* | M-3 | Include g_time for ordering | `this.g_time` field |
* | M-4 | Human-readable content | `getContentAsText()` method |
* | MONAD-1 | Unit (pure) operation | `MCard.create(content)` |
* | MONAD-2 | Bind (chain) operation | `MCard.bind(f)` via hash reference |
* | EOS-M1 | Hash is pure function | No side effects in hash computation |
* | EOS-M2 | Content is immutable | All fields are `readonly` |
*
* @see {@link DOTSRole.CARRIER} for DOTS vocabulary definition
* @see {@link EOSRole.INVARIANT_CONTENT} for EOS role definition
* @see docs/MCard_Impl.md for full implementation specification
*/
declare class MCard {
readonly content: Uint8Array;
readonly hash: string;
readonly g_time: string;
readonly contentType: string;
readonly hashFunction: string;
protected constructor(content: Uint8Array, hash: string, g_time: string, contentType: string, hashFunction: string);
/**
* Create a new MCard from content
*/
static create(content: string | Uint8Array, hashAlgorithm?: string): Promise<MCard>;
/**
* Create an MCard from existing data (e.g., from database)
*/
static fromData(content: Uint8Array, hash: string, g_time: string): MCard;
/**
* Get content as text (UTF-8 decoded)
*/
getContentAsText(): string;
/**
* Get content as raw bytes
*/
getContent(): Uint8Array;
/**
* Convert to plain object
*/
toObject(): {
hash: string;
content: string;
g_time: string;
contentType: string;
hashFunction: string;
};
/**
* Get DOTS vocabulary metadata for this MCard
*
* Returns the DOTS role information that positions this MCard
* in the Double Operadic Theory of Systems framework.
*
* MCard is always a CARRIER object in the Data Plane.
*
* @param tightRefs - Optional array of prerequisite MCard hashes (vertical composition)
* @param looseRefs - Optional array of alternative MCard hashes (horizontal composition)
* @returns DOTSMetadata describing this card's role in the compositional system
*
* @example
* ```typescript
* const card = await MCard.create('Hello World');
* const meta = card.getDOTSMetadata();
* console.log(meta.role); // 'Carrier'
* console.log(meta.plane); // 'Data'
* ```
*/
getDOTSMetadata(tightRefs?: string[], looseRefs?: string[]): DOTSMetadata;
}
/**
* Page - Pagination container for query results
*/
interface Page<T> {
items: T[];
totalItems: number;
pageNumber: number;
pageSize: number;
totalPages: number;
hasNext: boolean;
hasPrevious: boolean;
}
/**
* StorageEngine - Abstract interface for storage backends
*
* Implementations: IndexedDBEngine, SqliteWasmEngine
*/
interface StorageEngine {
add(card: MCard): Promise<string>;
get(hash: string): Promise<MCard | null>;
delete(hash: string): Promise<void>;
searchByHash(hashPrefix: string): Promise<MCard[]>;
getPage(pageNumber: number, pageSize: number): Promise<Page<MCard>>;
search(query: string, pageNumber: number, pageSize: number): Promise<Page<MCard>>;
getAll(): Promise<MCard[]>;
count(): Promise<number>;
clear(): Promise<void>;
registerHandle(handle: string, hash: string): Promise<void>;
resolveHandle(handle: string): Promise<string | null>;
getByHandle(handle: string): Promise<MCard | null>;
updateHandle(handle: string, newHash: string): Promise<string>;
getHandleHistory(handle: string): Promise<{
previousHash: string;
changedAt: string;
}[]>;
pruneHandleHistory?(handle: string, options: {
olderThan?: string;
deleteAll?: boolean;
}): Promise<number>;
}
export { MCard as M, type Page as P, type StorageEngine as S };