MCard: Local-first Content Addressable Storage with Content Type Detection
Project description
MCard and PKC: An Agentic OS for The PKM Paradigm Shift
MCard is the foundational storage layer of the Personal Knowledge Container (PKC) — an Agentic Operating System designed to facilitate a paradigm shift in Knowledge Management. Moving beyond centralized, passive data stores, PKC empowers local communities to operationally own their data asset infrastructures.
Through a local-first, content-addressable storage platform with cryptographic integrity, it provides a verifiable data backbone. Governed by a polynomial runtime (PTR) and guided by universally shared gamified scripts like the ABC curriculum, it removes learning barriers so anyone can utilize robust, polyglot execution without sacrificing developer ergonomics or observability.
Highlights
- 🔐 Hash-verifiable storage: Unified network of relationships via SHA-256 hashing across content, handles, and history.
- 🆔 Kenotic Identity Primitives: Decentralized Identifiers (DIDs) and Soul Bound Tokens (SBTs) bound to a Sovereign Tri-Database, scaling seamlessly from local SQLite files into Browser PWA IndexedDB partitions.
- ♾️ Universal Substrate: Emulates the Turing Machine "Infinitely Long Tape" via relational queries for computable DSLs.
- 🤖 Continuous Autonomous Optimization: Integrates local OpenClaw agents operating on configurable heartbeat intervals to continuously refine logic, types, and architecture autonomously.
- ♻️ Deterministic execution: PTR mediates 8 polyglot runtimes (Python, JavaScript, Rust, C, WASM, Lean, R, Julia).
- 🧩 Meta-Circular Type System: Purely native type-checking via a Minimum Preloaded Type Set (Propositions-as-Types), integrating Dependent Type Theory and Type Universes to safely parse dynamic constraints and remove reliance on language-specific type primitives.
- 🌳 Content Addressable Function-Number Duality Namespace: The hash of the Root Type CLM (
type.yaml) serves as the universal namespace anchor — the ground truth for uniqueness of content. All primitive types are recursively derived dependencies of this root, ensuring functional and content consistency across all Functions (causal relations) and Numbers (static content images). - 🔧 CLM as Dependency Orchestrator: CLM operates like
Make— it primarily manages dependencies and runs on top of any executable kernel, including kernels explicitly implemented to run CLM itself (meta-circular evaluation). - 🐚 Meta-Circular Shell Evaluator: Developed a pure shell-based evaluator (
clmEval) that leveragesyqandshasumto execute the CLM prep → exec → post pipeline entirely via CLI, enabling the script to evaluate its own CLM specification in a closed meta-circular loop. - 📊 Enterprise ready: Structured logging, CI/CD pipeline, security auditing, 99%+ automated test coverage. Continuous static analysis using
vulturefor Python andts-prunefor TypeScript dead code elimination. - 🧠 AI-native extensions: GraphRAG engine, optional LLM runtime, and optimized multimodal vision (
moondream). - ⚛️ Quantum NLP: Optional
lambeq+ PyTorch integration for pregroup grammar and quantum circuit compilation. - 📐 Visual Architecture: Interactive Mermaid diagrams bridging conceptual OS theory directly to Sovereign Tri-Database CI/CD implementation.
- 🏗️ Implementation Clarity: Systematic 7-document implementation suite (
docs/implementation/00_INDEX.md) follows a logical dependency chain — from Data-Function Duality (§01 foundational theory) through architecture-to-code mapping (§02), PocketFlow integration (§03), component specs (§04), testing strategy (§05), to the definitive implementation roadmap (§06). All content organized with Four-Database Topology alignment and Token Arithmetics governance telemetry. - 🧰 Developer friendly: Rich Python API, TypeScript SDK, BMAD-driven TDD workflow, numerous examples.
- 📐 Algorithm Benchmarks: Sine comparison (Taylor vs Chebyshev) across Python, C, and Rust.
- ⚡ High Performance: Optimized test suite (~37s) with runtime caching, Python AST
lru_cachememory bounds, and static Node.js runner scripts resolving without dynamic I/O overhead. - ⚙️ Meta-Circular Evaluator: The core PTR engine is distilled into a strict
eval/applyfunctional pipeline, stripping away bloated Category Theory abstractions to ensure the simplest possible mathematical verification loop. - 🧽 Tabula Rasa Distillation: The core engine completely eschews redundant Python Object-Oriented wrappers (like hardcoded Flow Builders, Polyglot Bridgelets, and Lens RPC protocols) in favor of defining architectures exclusively via mathematical PetriNet topologies evaluated directly by the isolated sandbox.
- 🛡️ Robust Validation Stability: Dynamic Model Fallbacks seamlessly locate available locally-hosted AI inference APIs (
Ollama) resolving test disparities out of the box, bound by strictly defined mathematical payload types across Python constraints and TypeScript TS2322 invariant coercions. - 🦆 DuckDB Engine: Optional columnar OLAP storage backend — same
StorageEngineinterface, ideal for analytical workloads and Parquet I/O. - 📋 Single Source of Truth Schema: Both SQLite and DuckDB engines load schema exclusively from canonical SQL files (
mcard_schema.sql,mcard_vector_schema.sql) — zero hardcoded CREATE TABLE statements. - 🔄 Bi-Directional Topological Sync: Pure Handle Space parity mapping recursively natively across Rust and Python runtimes perfectly maintaining SSOT bounds.
- 🔄 Shared MIME Registry: A single
mime_extensions.jsondrives content-type detection across both Python and TypeScript — edit one file to update both runtimes, no recompilation needed. - ⏱️ Centralized Operational Constants: All timing literals (PTR timeouts, LLM defaults, RAG embedding delays, signaling server intervals) unified in
config_constants.pywith full TypeScript parity — zero hard-coded timeouts remain in runtime code. - 🔗 Explicit VCard Wrapping: Fully formalized VCard-PCard binding via
wrapped_pcard_hashparameter injection. VCard instantiation now leverages a PCard-based Factory Pattern (PCard.create_vcard()), strictly coupling Subscriber (Pre) and Dispatcher (Post) witnesses to their origin PCards globally.
For the long-form narrative, gamified learning paths (the ABC curriculum), and chapter roadmap, see docs/theory/04_curriculum/Narrative_Roadmap.md. For the overarching OS metaphor and foundational principles of agentic infrastructure ownership, see docs/theory/02_architecture/PKC_Operating_System.md and docs/architecture/00_Architecture_Overview.md.
Quick Start (Python)
git clone https://github.com/xlp0/MCard_TDD.git
cd MCard_TDD
make setup-dev # creates .venv with uv, installs all deps + pre-commit
make project-check # validates Python, mcard-js, and mcard-studio
uv run pytest -q -m "not slow" # run the fast Python test suite
uv run python scripts/clm/run_clms.py chapters/chapter_01_arithmetic/addition.yaml
Development Setup
This project uses uv as the sole Python dependency manager. All dependencies are defined in pyproject.toml and locked in uv.lock.
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create venv and install all dependencies (including dev)
make setup-dev
# Or manually:
uv venv --prompt MCard_TDD
uv sync --all-extras --dev
# Run commands via uv
uv run pytest # run tests
uv run ruff check mcard/ # lint
uv run python script.py # run any script
Configuration
- Copy
example.envto.envfor local development. example.envis the canonical template;.env.exampleremains as a legacy-compatible copy.- The studio app uses
mcard-studio/example.envfor its own local.envseed. - Environment precedence is: CLI overrides → process environment →
.env→example.envdefaults. - Shared config defaults are defined in
config/app_config.jsonand consumed by Python, TypeScript, and studio runtime helpers.
Create and retrieve a card:
from mcard import MCard, default_collection
card = MCard("Hello MCard")
hash_value = default_collection.add(card)
retrieved = default_collection.get(hash_value)
print(retrieved.get_content(as_text=True))
Quick Start (JavaScript / WASM)
See mcard-js/README.md for build, testing, and npm publishing instructions for the TypeScript implementation.
- mcard-studio: The interactive PWA IDE — see mcard-studio/README.md for setup and architecture.
Quick Start (Quantum NLP)
MCard optionally integrates with lambeq for quantum natural language processing using pregroup grammar:
# Install with Quantum NLP support (requires Python 3.10+)
uv pip install -e ".[qnlp]"
# Parse a sentence into a pregroup grammar diagram
uv run python scripts/lambeq_web.py "John gave Mary a flower"
Example output (pregroup types):
John: n gave: n.r @ s @ n.l @ n.l Mary: n a flower: n
Result: s (grammatically valid sentence)
The pregroup diagrams can be compiled to quantum circuits for QNLP experiments.
Polyglot Runtime Matrix
| Runtime | Status | Notes |
|---|---|---|
| Python | ✅ | Reference implementation, CLM runner |
| JavaScript | ✅ | Node + browser (WASM) + Full RAG Support + Pyodide |
| Rust | ✅ | High-performance adapter & WASM target |
| C | ✅ | Low-level runtime integration |
| WASM | ✅ | Edge and sandbox execution |
| Lean | ⚙️ | Formal verification pipeline (requires lean-toolchain) |
| R | ✅ | Statistical computing runtime |
| Julia | ✅ | High-performance scientific computing |
⚠️ Lean Configuration: A
lean-toolchainfile in the project root is critical. Without it,elanwill attempt to resolve/download toolchain metadata on every invocation, causing CLM execution to hang or become unbearably slow.
Compiling Native Binaries
For detailed instructions on compiling the required C, Rust, and WASM binaries for the polyglot tests, please see the Compiling Native Binaries Guide.
Project Structure (abridged)
MCard_TDD/
├── mcard/ # Python package (engines, models, PTR)
├── mcard-js/ # TypeScript SDK — 3 interchangeable storage engines, PTR, RAG
├── mcard-studio/ # [Submodule] Astro + React PWA — artifact IDE with VCard events
├── LandingPage/ # [Submodule] Static-first P2P Documentation & Landing Portal
├── chapters/ # CLM specifications (polyglot demos)
├── docs/ # Architecture, PRD, guides, reports
├── scripts/ # Automation & demo scripts
├── tests/ # 923+ automated tests (Python)
├── Makefile # Unified dev commands (lint, test, clm-run, build)
├── mime_extensions.json # Shared MIME-type registry (Python + TypeScript)
└── pyproject.toml # uv-managed dependencies (uv.lock)
Submodule Organization
This repository orchestrates two key frontend applications as submodules, each serving a distinct role in the MCard ecosystem:
1. mcard-studio (/mcard-studio)
The Interactive IDE for Eventual Consistency & Eventual Correctness. A Progressive Web App (PWA) built with Astro and React. It serves as the primary interface for creating, editing, and executing MCards and CLMs.
- Tech Stack: Astro, React, Zustand, Monaco Editor, Anime.js/GSAP, Mermaid.
- Key Features: Four-store persistence (
servermemory.db,browsermemory.db,execution_logs.db, filesystem), dual-mode CLM execution (browser-first JS → server fallback), VCard event pipeline with result sealing, inline rename/upload/create, version history with time-travel, native AI assistant (Ollama), 30+ file type renderers. - Role: The "Editor" & "Runtime" environment for developers and power users.
- Test Results: 372 tests passed (37 test files).
2. LandingPage (/LandingPage)
The Public Portal & Knowledge Container. A static-first modular web application designed for decentralized distribution. It focuses on P2P communication, documentation rendering, and interactive 3D visualizations.
- Tech Stack: Vanilla JS Modules, WebRTC (No signaling server), Three.js, KaTeX, Mermaid, ZITADEL (OIDC Authentication).
- Key Features: Serverless P2P mesh networking, zero-dependency architecture (runs locally without build steps), rich markdown/media rendering, and interactive authenticated pedagogical games (Monopoly, Chess, Go) with ZITADEL SSO integration.
- Role: The "Viewer" & "distributable container" for the Personal Knowledge Container (PKC) concept.
Documentation
- 📖 Master Index: docs/index.md — AI-optimized documentation entry point (BMAD
document-projectoutput) - 📋 Project Overview: docs/project-overview.md — Executive summary, tech stack, multi-part structure
- 🌳 Source Tree Analysis: docs/source-tree-analysis.md — Annotated directory structure
- Product requirements: docs/specifications/01_product_requirements.md
- Architecture overview: docs/architecture/README.md — Three Pillars (CLM, PTR, VCard) + Function-Number Duality
- Theory canon: docs/theory/README.md — Foundations, architecture, runtime, curriculum (14 articles)
- Schema principles: schema/README.md — Empty Schema grounding, verification-first storage, and the core/extension split.
mcard-jsschema reference: mcard-js/schema/README.md — Practical explanation ofmcard_schema.sqlandmcard_vector_schema.sql.- DOTS vocabulary: docs/WorkingNotes/Hub/Theory/Integration/DOTS Vocabulary as Efficient Representation for ABC Curriculum.md
- Narrative roadmap & chapters: docs/theory/04_curriculum/Narrative_Roadmap.md
- Logging system: docs/guides/LOGGING_GUIDE.md
- PTR & CLM reference: docs/specifications/02_clm_language_specification.md, docs/archive/PCard Architecture.md
- Implementation roadmap: docs/implementation/06_Implementation_Phases.md
- Reports & execution summaries: docs/reports/
- WebSocket Performance Debugging
- Petri Net Implementation — Physical implementation mapping
Platform Vision & Architecture
The historical foundations and architecture of MCard_TDD center structurally around the Data-Function Duality—where passive data and active software functions resolve completely symmetrically within the exact same conditionally upgradable geometric memory space.
By mechanically evaluating operations across the 4-step prep → exec → post → await Petri Net schedule, the execution pipeline explicitly enacts Euler's Four-Square Identity, maintaining perfect geometric norm conservation between inputs, functional transformations, and resulting output topologies.
This mathematically restricts memory and side-effects from tearing out of scope via perfect Algebraic Closure, fundamentally grounding MCard_TDD analytically as a strict Purely Functional Operating System.
These operational structures are detailed extensively inside the Architecture Overview and the PTR Meta-Circular Runtime suites.
- Euler's Four-Square Closure — Demonstrable Proof of Algebraic Integrity.
- DOTS → PTR Meta-Language — Theoretical framework
Recent Updates
Full changelog: CHANGELOG.md
Current versions: Python mcard 0.1.71 · TypeScript mcard-js 2.1.54
BMAD Documentation Refactor: The Kenotic Kernel & CRDT Integration (April 27, 2026): Executed a targeted surgical audit of the documentation suite to formalize the Tri-Tier PTR Architecture. Elevated the shell-native clmEval to its rightful place as the Zeroth Tier (Shell-Native) Kenotic Kernel, proving that the Symmetric Monoidal Category (SMC) transitions hold mathematically true down to the lowest POSIX OS level. Additionally, wove the Content Addressable Schema into the architecture docs as the fundamental mechanism for maintaining data consistency and enabling Conflict-Free Replicable Data Types (CRDTs) across distributed multi-agent meshes.
Meta-Circular Augment Refactoring & Petri Net Flow Formalization (April 22, 2026): Decoupled the monolithic "augment" operation into a strict two-step Petri Net sequence (load_file and insert), mathematically ensuring pure state-passing boundaries between operations. Formalized load_file and insert as built-in native operations registered directly in the PythonRuntime DEFAULT_OPERATIONS dictionary, removing arbitrary inline Python code, and synced clm_reserved_words.yaml to include the new operators under the Kenotic grammar dictionary. The load_file operation was also upgraded to natively ingest binary file byte-streams. Also, developed scripts/flowCubed.py, a new execution harness that natively evaluates Petri Net structures via the PTREngine, and patched the URI resolver (mcard/ptr/core/resolver.py) to correctly parse relative file: schemas to safely resolve local structures without URI path truncation.
Governance Analytics & Bootstrap Synchronization (April 22, 2026): Replaced legacy "5-E Measurement" framework traces across all 9 clm/bootstrap_phases/ YAML definitions traversing 00 through 07. Synced all five_e_metrics natively into our mathematical bounds tracked by Token Arithmetics: possibility_magnitude ($\mathcal{M}$), governance_narrowing ($\mathcal{N}$), epiplexity_yield ($\mathcal{E}$), and product_dependency_count ($\Pi$). Scoured lifecycle bounds identifying loose terminology (PREP -> EXEC -> POST, T_prep), refactoring identical strict topological bounds Stage 1 (PREP), Stage 2 (EXEC), Stage 3 (POST). Lastly, deleted 07_phase_h_five_e_measurement.yaml, replacing it with 07_phase_h_governance_analytics.yaml natively bridging Phase H directly into tracking topologies in docs/implementation/06_Implementation_Phases.md. Ran the entire 42-level identity and execution sequence verification natively via tests/bootstrap/ ensuring identical Python/YAML pipeline resolution.
Legacy Core Deprecation: CLMRunner & Kenotic Networking (April 22, 2026): Successfully deprecated and purged the legacy mcard/ptr/runner.py in favor of the strict PTREngine lifecycle boundaries, reducing the underlying code volume and strictly enforcing the "Zero-State" Tabula Rasa assumption. Deleted the intrinsic networking stack (mcard/ptr/network/) enforcing the Kenotic architectural principle that all I/O boundary executions must be strictly handled through explicit User-Space PCards rather than buried kernel integrations. Completely refactored testing borders (rewriting gatekeeper assertions directly via PCard.can_fire) mitigating legacy test noise and optimizing the codebase layout.
Implementation Documentation Harmonization & Phase A.1/B Native Code (April 22, 2026): Authored the 08_Phase_B_Schema_Injection.md defining the multi-modal injection pipeline, handle registry population, and T01–T03 integration bounds. Exhaustively sanitized the 10-document implementation suite by enforcing strict terminological boundaries—specifically renaming generic “Phase” execution wrappers into "Stage 1 (PREP)", "Stage 2 (EXEC)", and "Stage 3 (POST)" to eliminate namespace collision with the macro A-H roadmaps. Synchronized testing bounds by explicitly mapping the T00.1–T00.4 Genesis Identity tests into the core validation sequence. Furthermore, completed the native Phase A.1 code (mcard/bootstrap/clm_hooks.py) by generating rigorous Ed25519 CSPRNG keys natively enforcing geometric parity with did:key:z6Mk... multi-codec prefixes via the base58 package. Bound these identical logic bounds aggressively to testing architecture under test_t0_1_identity_genesis.py, verifying Tabula Rasa isolation patterns safely executing to 100% specification parity.
Genesis Identity Bootstrap & API Stabilization (April 21, 2026): Formalized the bootstrapping procedure for the Agentic OS, establishing the transition from a Tabula Rasa state to a provisioned sovereign identity layer via a new 10-step bootstrap lifecycle (00a_phase_a_genesis_identity.yaml). Implemented the corresponding 07_Genesis_Identity_Bootstrap.md implementation guide to document identity bounds and boot certification limits. Additionally, fortified the native FastAPI boundary layer (mcard/api.py) by isolating synchronous storage engine calls safely inside asyncio.to_thread execution wrappers, structurally resolving latent asynchronous 500 runtime TypeErrors during concurrent HTTP invocations.
Polyglot Type Parity & Asynchronous Stabilization (April 21, 2026): Integrated ts-rs into mcard-core to establish a mathematically sound, self-generating type contract across the Rust workspace and the TypeScript boundaries autonomously. Authored common_data_types.rs in mcard-core, equipping graphical components (e.g. Vector3, MeshDescriptor) with unified schema definitions exported as canonical .ts structures. Additionally introduced zod as the central validation layer across mcard-js and mcard-studio to block structurally compromised data upstream. Addressed core memory/blocking bottlenecks during payload parsing by migrating Loader.ts to memory-conserving Async Generators (loadFileToCollectionStream()) for backpressure ingest, and leveraging Comlink WebWorkers in mcard-studio to push heavy schema validation entirely off the React main thread.
Prologue Chapter Systematic Renumbering & Canonical CLM Sequence (April 21, 2026): Completed the comprehensive reorganization of chapters/chapter_00_prologue/ into a logically sequenced 18-CLM canonical curriculum (01–18). Established a pedagogical progression from meta-circular foundations (01) through Turing-tape semantics (02–09) to sovereign identity workflows (10–18). Renamed files for lexical sortability: 01_meta_circular_ptr.yaml, 02_turing_tape_tri_database.yaml through 09_petri_net_workflow.yaml, then identity suite 10_kenotic_identity_issuance.yaml through 18_identity_bootstrap.yaml. Updated README.md and created _VCARD_MANIFEST_SCHEMA.md establishing canonical envelope and DID test vector specifications for all identity CLMs. All cross-references synchronized across documentation suites.
Clojure Convergence Documentation Propagation (April 20, 2026): Propagated the new Clojure/Datomic integration research from the WorkingNotes theory hub into the canonical documentation layers. Added a new 0.2 Prior Art: The Clojure Convergence section to docs/architecture/02_Theoretical_Foundations.md, connecting Hickey's value/identity/time separation, HAMT structural sharing, and Datomic's immutable-fact model directly to the MCard tri-database. Extended docs/specifications/03_data_architecture.md with 1.5 Lineage: From Datomic to MCard, mapping Datomic concepts to MCard storage semantics, contrasting Datomic Cloud / XTDB / MCard, and outlining migration paths for existing immutable-fact deployments. Updated docs/implementation/00_INDEX.md with a new lineage section linking implementers to the four companion articles on De-Complecting Knowledge, Transducers, spec/Malli/CLM, and Datomic/XTDB/MCard.
Two-Tier Application Architecture & OS Boundary Formalization (April 20, 2026): Formalized the core MCard storage model around the UNIX Privilege Boundary metaphor, structurally isolating the pure system engine from scale-free application logic. Explicitly categorized the Four-Database topology (Kenotic Root + Tri-Database) as the Privileged Kernel Space, mapping generative operations and PWA logic to execute securely inside Restricted App Space via VCard syscalls. Integrated external Application Package Distribution via app_store.db, allowing natively shared CLM PCards without bloating individual agent Tri-Databases. Connected PCard resolution to UNIX resource optimization logic — executing a shared MCard acts as an infinitely scalable Copy-on-Write fork() operation bridging external registry boundaries.
React and ESM Module Resolution Fixes (April 20, 2026): Resolved critical vite build errors and ESM import regressions inside the mcard-studio PWA. Migrated away from deprecated default exports in animejs v4, refactoring useGovernanceTelemetry.ts and AnimeJsEngine to use direct animate(targets, {...}) parameters. Handled duplicate React module imports within NavigationSidebar.tsx resolving frontend rendering crash loops.
Implementation Documentation Reorganization & Status Update (April 20, 2026): Reorganized the 7-document docs/implementation/ suite to follow a logical dependency chain: Theory (§01 Data-Function Duality) → Mapping (§02 Architecture-to-Code) → Patterns (§03 PocketFlow Integration) → Specs (§04 Component Specs) → Testing (§05 Testing & Validation) → Roadmap (§06 Implementation Phases). Updated 06_Implementation_Phases.md with comprehensive evidence-based status dashboard (923 Python tests, 131 CLM files, Rust SDK status) — Phases A–D complete, Phase E ~70%, Phase F ~55%, Phase H ~40%. All internal cross-references across 9 files and external references in CHANGELOG.md updated to new numbering.
Agentic OS Governance Formalization & Token Arithmetics (April 20, 2026): Completed a comprehensive documentation propagation establishing governance as a structural consequence of the MCard architecture — not an add-on feature. Formalized the Token Arithmetics framework synthesizing Petri Net tokens (state-enabling markers) and Cryptoeconomic proofs (causal evidence) through algebraic type theory: Sum Types ($A + B$, branching entropy), Product Types ($A \times B$, topological dependencies), and Exponent Types ($B^A$, combinatorial possibility spaces). Defined four quantitative governance metrics — Possibility Magnitude ($\mathcal{M} = |B|^{|A|}$), Governance Narrowing ($\mathcal{N}$), Epiplexity Yield ($\mathcal{E}$), and Product Dependency Count ($\Pi$) — integrated across 12 documents spanning architecture (§1.7 Inherent Governance, §03 Token Arithmetics), specifications (§04 §2.5 Formal Vocabulary, §05 §1.1.1 ABC Governance Vocabulary), and implementation (Phase H: Governance Analytics, PTRSharedStore governance fields, Governance Plane Tests, PCard Sandwich as Governance Pipeline).
Multi-Modal Viewers & Generative Synthesis (April 19, 2026): Completed Phase F.2 integration, establishing rich multi-modal artifact rendering and strictly offline Generative Synthesis. Implemented native AudioViewer, VideoViewer, and Model3DViewer inside the Studio PWA using HTML5 APIs and @react-three/fiber. Developed purely algorithmic Generative Interceptors within ChatbotPanel—bypassing heavy external API-keys by deterministically synthesizing authentic .png diffusion mockups and 44.1kHz .wav PCM oscillator payloads entirely inside the browser. This mathematically proves the end-to-end multi-modal data pipeline (Prompt → Algorithm Generation → Data Blob → VCard Registry → Viewer Engine Render) without compromising MCard's strict offline, Local-First Sovereign constraints.
TypeScript Runtime Kenotic Decoupling & OPN Parity (April 19, 2026): Completed the architectural parity between the mcard-js TypeScript implementation and the mcard Python runtime by formalizing the OPN-based PTREngine execution flow. By cleanly extracting the Sandbox, Certifier, and Gatekeeper verification boundaries, the TS runtime completely mirrors the formally verified Petri Net constraints. Mathematical Evaluation traces (witnessPrecondition, witnessPostcondition, sandwich) are formally preserved in a VCardSandwich.ts builder to correctly map proofs across both boundaries identically.
MCard Kernel Modularization & Data-Driven Ecosystem (April 19, 2026): Finalized the transition of the MCard kernel computing engine toward a purely modular, schema strict execution boundary. Formally expunged all hardcoded networking logic (p2p_session.py, signaling_server.py, discovery.py), honoring the Kenotic Principle by deferring P2P orchestration dynamically out to user-space network topology CLMs. Stabilized the polyglot integration suite through a globally shared dynamic registry parsing runtime mappings natively from schema/runtime_types.json and strict validation fallbacks via schema/mcard_system_config.yaml—safely centralizing timeouts, allowed sandbox globals, and engine extensions completely independently of Python logic files. Finally, eradicated arbitrary SQLite loop-trigger application crashes across the framework natively merging CREATE TRIGGER bounds centrally into the explicit schema/mcard_schema.sql definitions ensuring flawless DuckDB and SQLite polyglot loading synchronicity. All 836+ local unit tests uniformly pass under rigorous Data-Function parity architectures safely bounding execution state completely inside the declarative space.
Petri Net PTR Execution Engine (April 19, 2026): Implemented first-class Petri Net composition for concurrent PCard execution, realizing the specification's "Concurrent Function Scheduler" (04_execution_engine §2). New modules: petri_net.py (Place/Transition/Marking/PetriNet dataclasses with sink-aware deadlock detection and Coloured Petri Net typed places), net_engine.py (ThreadPoolExecutor-based concurrent firing with compensating actions), and resolver.py (recursive PCard resolution via content hash, CLM handle, file URI, and trust-gated URL). CategoryCombinators now produces PetriNet topologies via compose_net()/split_net()/augment_net(), PCardFlow.to_petri_net() bridges action-routing DAGs to formal nets, and PTREngine.execute_net() auto-detects composite PCards for graph-based execution. 876 tests (+47), 0 regressions.
Architecture Formalization & CHL Temporal Integration (April 19, 2026): Conducted a profound unification of the underlying Operational OS logic, firmly rooting "Vibe Coding" and Edge CI/CD within the Curry-Howard-Lambek (CHL) Isomorphism. By mechanically mapping Design Time (Lambek/Future), Compile Time (Howard/Present), and Execution Time (Curry/Past) to deterministic Cubical Logic semantics, the architecture ensures complete, fine-grained control over how new LLM-driven knowledge evolves. Fully integrated Mathematical Galois Connections ($\alpha \dashv \gamma$) and Operadic Calculus across the architecture documentation suite, guaranteeing eventual consistency computationally bounded by pure CRDT properties.
Dynamic Library Function Invocation (April 24, 2026): Introduced the invoke_library operation to the PTREngine across Python and JavaScript. This enables CLMs to specify and execute external library functions purely by declaring module and function signatures, packing variables dynamically from context, natively evaluating test execution boundaries (balanced_expc), and removing the need for explicit logic implementations in YAML payloads.
CLM Syntax Standardisation (April 24, 2026): Formally standardized the CLM YAML schema across all specification documents and test files. The schema now strictly mandates abstract_spec (with context, goal, success_criteria), concrete_impl (with inputs, process, outputs), and balanced_expc (with test_cases containing given, when, then). Baseline polyglot execution tests for Python and JavaScript were implemented to perfectly mirror this schema requirement.
Phase E.2.a PTR Engine Formalization & VCard Sandwich Parity (April 19, 2026): Finalized the Python Phase E.2.a implementation mapping the PTR Execution Engine natively to the Three-Plane Sovereign Architecture markers (_prep, _exec, _post). Enforced the VCard Sandwich data patterns ensuring strict execution telemetry nesting and correctness bounds evaluation. Restructured PTRSharedStore enforcing the pure Four-Database Topology, aligning topological CRDT lattice-join limits matching Strong Eventual Consistency (SEC) validations smoothly across polyglot operations natively without dependency bleed. Resolved legacy regression unit tests and stabilized isolated local inference dependencies (qwen3:0.6b).
Unified Categorical Hierarchy: MCard → PCard → VCard (April 19, 2026): Refactored the class hierarchy from a flat fork to the architecturally mandated linear chain (MCard → PCard → VCard), aligning the Python model with the Monad → Functor → Applicative categorical hierarchy and the Currying Formula VCard(PCard(MCard)) = Result. VCard now overrides PCard's _validate_and_parse() as the canonical guard (precondition) layer, gracefully accepting JSON VCard Sandwich, YAML, and non-dict content. VCard instances inherit PCard's CLM triad accessors, SMC algebraic combinators (.then(), .and_also(), .swap()), and Petri Net boundary specs — eliminating code duplication while preserving full backward compatibility (829 tests, 0 regressions).
Phase D Orchestration & Pure Functional OS Formalization (April 17, 2026): Completed Phase D of the execution roadmap. Established robust dependencies mapping AuditVerifier inside Python and JS engines natively tracking mathematical Hoare logic sandwich execution boundaries. Formally proved system architecture complies strictly with Pure Functional Operating System paradigms via docs/theory/Euler_Four_Square_Closure.md dictating algebraic preservation across the 4-phase computation geometry.
Native Rust Adaptive Intelligence Routing — Phase E.3 (April 17, 2026): Successfully mapped the Local-First Sovereign Fallback limits directly into the native Rust Executor (rsCubed). Implemented the IntelligenceRouter natively relying exclusively on synchronous ureq execution constraints, structurally dodging Async ecosystem bloat. Bound exact execution trace spans directly from the Rust engine into execution_log.db, successfully capturing [EXECUTION_WARNINGS] during offline edge node (qwen3:0.6b via Ollama) fallback logic executions natively mapping the Python/JS architectures gracefully.
Deterministic LLM Executions & Token Exhaustion Fixes (April 16, 2026): Stabilized Live LLM inference test suites across both the Node (mcard-js) and Python (mcard) environments, protecting deterministic assertions against both token exhaustion and entropic hallucination constraints. Fixed AdaptiveFallback.test.ts failure by bumping logic fallbacks to max_tokens: 4096 bypassing qwen3:0.6b early termination bugs. Resolved test_clm_execution non-determinism in Python by explicitly suppressing evaluation randomness (temperature: 0.1 inside question_answer.clm) satisfying mathematical validations.
WASM & ESM Studio Integration Parity (April 16, 2026): Resolved fatal Astro buildEnd hooking issues targeting detect_content_type Rust endpoints natively. Repackaged local mcard-wasm workspaces natively with wasm-pack build --target bundler replacing outdated Node-specific limits. Fixed missing workspace linkage bounds in mcard-studio's configuration pipeline to correctly ingest file-level native dependencies natively testing Vitest compatibility accurately.
Automated Tests Execution & Loader Enhancements (April 16, 2026): Drastically enhanced the execution performance and stability of the filesystem loader and the test CI/CD pipelines. Implemented heuristic optimizations to the file_io directory scanner, programmatically excluding extreme-scale dependency repositories (node_modules, venv, build) from recursively exhausting validation operations. Resolved fatal SQLite disk I/O error failures triggered during heavy test concurrency by safely purging lingering .db-wal / .db-journal sidecars. Hardened the cli.py polyglot suite discoverer, enforcing parity with the Makefiles to ensure offline experimental fixtures prefixed with underscores (_) remain correctly excluded from test builds.
Native Qwen3 (0.6B) LLM Integration (April 16, 2026): Executed a comprehensive workspace migration transitioning the foundational local-first offline Inference models from Gemma4 over to Qwen3 (0.6B). Synthetically updated all structural binding pointers natively hardcoded into the Python architecture (ollama.py, runtime.py), the JavaScript GraphRAG validation pipeline (Config.ts), and explicitly across all central Cubical Logic Model specifications. Local machine testing suites and auto-fallback routing workflows now seamlessly invoke qwen3:0.6b via Ollama orchestration.
Pristine Repository Cleanup & Test Stability (April 16, 2026): Maintained rigorous project working directory hygiene by establishing a pristine root state, safely removing stale AI/IDE metadata directories and leftover cache artifacts. Resolved integration test flakiness in Q_A.yaml by enforcing explicit formatting instructions in the prompt, successfully verifying that qwen3:0.6b mathematical output parsing reliably aligns with deterministic result_contains assertions. Enforced data volume purity by removing stray triadic_small.db databases and wiring Chapter 04 Triadic loaders strictly into the primary content_memory.db matrix. Patched the cross-runtime continuous integration Makefile to aggressively exclude nested /test_data/ payload directories from executing as phantom test scripts, whilst officially shifting dependent network interaction test harnesses (sync_client.yaml, sync_server.yaml) entirely to manual suite integration via logical file prefixing.
Local-First Sovereign AI & Adaptive Intelligence Routing (April 16, 2026): Formalized the architecture ensuring MCard_TDD relies upon local-first, native inference loops to secure absolute cognitive autonomy. The execution suite was overhauled to weave an IntelligenceRouter dynamically routing LLM workflow states across three environments depending on active availability: Online APIs, Overlay VPN community instances, or complete offline Local-First inference engines (e.g. Gemma4). Episodic planning memory logs are mathematically isolated and trapped locally within data/execution_log.db, entirely circumventing logic leakage to the cloud. PocketFlow's resilience handling natively triggers this automatic offline edge-model failover when external APIs become unreachable. The foundational topological map (seed_clm_playbook.yaml) and operational fallback validators (like tell_a_joke.yaml) were migrated into the strict central clm/ directory — bridging cross-runtime verification cleanly between the polyglot JS (jsCubed) and Python (pyCubed) execution environments.
Tri-Database Directory Configurability & Portability (April 15, 2026): Explicitly documented the configurable nature of the Tri-Database directory (agent_identities.db, content_memory.db, execution_log.db) across all four core specification documents. While the default path is ./data/ for development and testing convenience, the directory is fully configurable via config_constants.DEFAULT_DB_PATH (Python) or runtime configuration (JavaScript/TypeScript). This enables portable deployments across diverse environments—production servers (/var/lib/mcard/data/), containerized deployments (/app/data/), user home directories ($HOME/.mcard/data/), or ephemeral storage—without architectural changes. The Kenotic Root (meta_functionality.db) maintains the reference to the active Tri-Database path.
Polyglot Runtime Executor Specification (April 15, 2026): Explicitly documented the CLM runtime triggering mechanism across all four core specification documents (Product Requirements, CLM Language, Data Architecture, Execution Engine). Established that scripts/pyCubed.py (Python PTR) and scripts/jsCubed (JavaScript PTR)—plus future {lang}Cubed executors—trigger CLM execution by reading the shared meta_functionality.db from the project root and resolving database paths relative to the same directory. This architecture enables a single MCard_TDD project to seamlessly host Python, JavaScript, Rust, Go, Lean, and future language runtimes under unified Four-Database Topology configuration.
Specification Suite Architectural Review & Four-Database Topology Formalization (April 15, 2026): Completed comprehensive system architect review of the entire MCard product specification suite (7 documents + seed CLM YAML), identifying and resolving logical conflicts and conceptual holes. Key fixes: (1) Formalized Four-Database Topology terminology—Kenotic Root (./meta_functionality.db) + Tri-Database (data/*)—resolving the "3 databases vs 4 databases" inconsistency; (2) Clarified VCard dual roles—as data (MCard with cryptographic proofs) and as execution boundary (Precondition/Postcondition wrappers); (3) Added REPL execution pattern section to execution engine spec with Head Reduction (→h) and Head Expansion (↝); (4) Distinguished ABC Curriculum (temporal workflow: Assumption→Behavior→Confirmation) from CLM A×C×B triad (structural dimensions); (5) Enhanced cross-references between architecture and specification docs; (6) Updated seed CLM YAML with four_database_topology stanza. All 7 specification documents now maintain rigorous architectural consistency.
CLM Test Suite Stabilization & Model Migration (April 14, 2026): Standardized the CLM test vocabulary by canonicalizing balanced.scenarios → balanced.test_cases across all 5 identity CLMs in chapter_00_prologue, fixing silent test skipping. Migrated the default Ollama model from gemma3:latest to qwen3:0.6b across entire codebase (Python + TypeScript). Hardened both CLI directory scanners to exclude test_data/, __pycache__/, and node_modules/ from recursive CLM discovery, preventing fixture data from being parsed as CLM specs. Fixed LLM runtime JSON serialization crashes and prompt pollution. Increased max_tokens to 4096 for thinking-model compatibility.
Decoupling Bootstrap Native Logic Executions (April 14, 2026): Completed the architectural transition of the PKC ecosystem's bootstrap and topological schemas by securely migrating dynamic Python procedural logic out of inline YAML structures into mcard/bootstrap/clm_hooks.py. Hardened dependency proxying native injection, bypassing import restrictions and isolating topological logic declaratively. Abstracted mcard-cli system generation data-structures by substituting hard-coded databases with global integration via BootstrapSettings subclass topology instantiation dynamically routed.
PKC Bootstrapper Formalization & Inception Constraint (April 11, 2026): Established the Inception Constraint within the PKC ecosystem, ensuring code execution strictly requires topology validation (meta_functionality.db) upon PTREngine initialization. Standardized the topological graph parsing to target seed_clm_playbook.yaml by default via the newly decoupled KernelBootstrapper. Automated full T0-T5 boot certification flows.
Async-First Architecture & Flow Composition (April 04, 2026): Brought native async execution paths and composable flows to the PTR.
- Python
- Async wrappers:
AsyncPTREnginewith async DB prefetch (CardCollection.aget/aadd), sandbox (aexecute), and verifier (averify_clm_consistency). - CLI:
--asyncflag to run CLM files viaAsyncPTREngine.run_file_async(). - Flow composition:
FlowNode,flow_from_spec(),PTREngine.run_flow()andrun_flow_file(). - CLI: New
flowsubcommand to execute declarative flow YAMLs.
- Async wrappers:
- TypeScript
- Shared Store:
src/ptr/core/SharedStore.tsfor parity with PythonPTRSharedStore. - PTREngine: Added retry helper (
executeWithRetry), batch APIs (executeBatch,executeBatchParallel). - Flow composition:
src/ptr/core/Flow.tswithPCardFlow,FlowNode,flowFromSpec, and helpers. - Tests: Adjusted real-HTTP integration test timeout; all JS tests pass locally (56 files, 883 tests).
- Shared Store:
Docs: docs/implementation/06_Implementation_Phases.md updated — Async-First (Task 10) and Flow Composition (Task 11) marked complete.
PTREngine Arrow Interface & VCard Sandwich Parity (April 03, 2026): Completed the formal PTR refactoring across both Python and JavaScript, achieving exact API parity. Introduced PTREngine as the canonical Arrow execution primitive with runWithSandwich(), arr(), compose(), first(). Added VCard Sandwich static methods (witnessPrecondition, witnessPostcondition, sandwich) for boundary verification proofs. Enforced the Kenotic Principle by deprecating kernel-level networking modules (NetworkRuntime, SignalingServer, P2PChatSession) in favor of user-space PCard workloads (chapters/networking/). Added make clm-run targets for executing all CLM chapters across both runtimes. Python: 407 tests, JS: 884 tests, 0 failures.
Autonomous Mesh Discovery & Identity Validation (April 02, 2026): Fully implemented mDNS "Friendly Network" peer discovery in both the Python and JavaScript runtimes. The single-boot launch command now natively spins up the node, API, Studio, and zero-conf sniffer all in one process. GTime triplet execution traces now correctly extract and cryptographically bind the authentic user identity (did:key:xxxx) pulled dynamically from the Studio UI's native IdentityStore rather than using environment variables. All parity tasks completed.
PTR Security Hardening — Bandit Remediation (March 31, 2026): Systematic remediation of all Medium and High severity findings from Bandit static analysis across 19 files. Introduced mcard/utils/url_safety.py — a centralized safe_urlopen() helper that validates URL schemes (http/https only) before opening, replacing raw urllib.request.urlopen calls in 7 modules. Migrated XML parsing to defusedxml.ElementTree (with stdlib fallback) to prevent XXE/billion-laughs attacks. Eliminated shell=True subprocess calls in the signaling server by converting to safe array-based invocations. Fixed weak MD5 usage in network cache key generation with usedforsecurity=False. All 770 Python tests pass with 0 High / 0 Medium Bandit findings.
Config Unification, Canonical Env Templates, and Smoke Cleanup (March 28, 2026): Centralized shared configuration defaults in config/app_config.json with parity across Python, TypeScript, and studio runtime helpers; standardized the root example.env / legacy .env.example contract plus mcard-studio/example.env; documented environment precedence and CI seeding; and quieted boot-time ingest warnings during smoke runs while preserving the startup summary and the standalone websocket server path.
Binary File Size Limit Increase (v0.1.64 / v2.1.47): Raised the maximum binary file size from 50 MB to 150 MB across all runtimes (Python, TypeScript, Studio), enabling ingestion and preview of larger PDF, video, and other binary assets. Updated MAX_FILE_SIZE, MAX_ARTIFACT_SAVE_BYTES, MAX_BINARY_PREVIEW_BYTES, and problematic-file thresholds in 7 files.
Polyglot Runtime Stabilization & CLM Pipeline (v0.1.63 / v2.1.46): Stabilized the cross-environment execution pipeline for Cubical Logic Models (CLMs) across Python, Node.js, and Rust/WASM. Improved Python interpreter resolution in the JS SDK, added first-class Node.js runtime support, and implemented automatic server-side delegation for Node-dependent browser CLMs. Fixed gatekeeper evaluations and test assertions across all 13 prologue CLMs, achieving 100% test pass rates in both the CLI and Studio environments.
Pedagogical Game Integration via ZITADEL SSO: Added authenticated views for Chess, Go, and Monopoly to LandingPage, using ZITADEL OIDC to protect game state boundaries and user identity mapping as part of the broader ethnographic scaling research implementations.
Identity System Authentication Update (v0.1.62 / v2.1.45): Implemented a complete credential-based identity authentication system in mcard-studio, replacing the previous passwordless registration flow with server-side PBKDF2 password hashing and timing-safe login verification.
Polyglot Runtime & WASM Integration Fixes (v0.1.60 / v2.1.43): Fixed critical missing --experimental-wasm-modules environment flags in Python subprocess integration, rectified module:// protocol resolution for cross-environment testing, and enforced importlib dynamic module bootstrapping in NodeJS. Patched Rust/TypeScript content-type string detection parity bugs and Python 3.9 __future__ typing incompatibilities.
Python Build & Syntax Corrections (v0.1.59 / v2.1.42): Fixed mcard syntax, namespace, and import dependency compilation errors across improved_logging.py, card_collection.py, and logging_config.py. Restored 100% test build health.
Storage Layer Deduplication (v0.1.58 / v2.1.42): Comprehensive refactoring to centralize card operations into AbstractSqlEngine (TypeScript) and simplify connection paths via resolve_db_path() (Python). Eliminated over 250 lines of duplicate code across the 4 TypeScript SQL engines, standardized dialect handling (SQLite TEXT vs DuckDB VARCHAR), and fixed a latent foreign key bug in handle renaming. All functionality remains fully backward compatible.
🏗️ Major Project Restructuring (v0.1.56 / v2.1.38): Four-phase structural overhaul — root files relocated to proper directories, documentation reorganized (32 flat files → 7 subdirectories), scripts reorganized (19 files → 6 subdirectories), Python tests restructured (28 files → 5 subdirectories), TypeScript engine implementations moved to storage/engines/ with barrel re-exports, factory pattern migration (SqliteNodeEngine.create()), test database cleanup, and .gitignore hardening. Runtime behavior is unchanged; all 849 TS tests and 767 Python tests pass.
Recent milestones also include DuckDB as an alternative storage engine, shared MIME registry (mime_extensions.json), PTR exception narrowing (109 broad catches → specific types), SqlJs vector adapter for browser-based vector search, and ContentTypeInterpreter event-loop starvation fix. See CHANGELOG.md for full details.
Testing
Note: All commands below should be run from the project root (
MCard_TDD/).
Unit Tests
# Python
uv run pytest -q # Run all tests
uv run pytest -q -m "not slow" # Fast tests only
uv run pytest -m "not network" # Skip LLM/Ollama tests
# JavaScript
npm --prefix mcard-js test -- --run
# Browser (MCard Studio)
npm --prefix mcard-studio run test:unit -- --run
CLM Verification
Both Python and JavaScript CLM runners support three modes: all, directory, and single file.
Unified (Makefile)
make clm-list # List all available CLM chapter files
make clm-run-py # Run all chapters through Python PTR
make clm-run-js # Run all chapters through JavaScript PTR
make clm-run # Run both runtimes sequentially
Python
# Run single file
uv run python -m mcard.ptr.cli run chapters/chapter_01_arithmetic/addition.yaml
# Run single file in test mode (human-readable output)
uv run python -m mcard.ptr.cli run chapters/chapter_01_arithmetic/addition.yaml --test
# Run all CLMs in a directory
uv run python -m mcard.ptr.cli run chapters/chapter_01_arithmetic --test
# Run with custom context
uv run python -m mcard.ptr.cli run chapters/chapter_08_P2P/generic_session.yaml \
--context '{"sessionId": "my-session"}'
# List available CLMs
uv run python -m mcard.ptr.cli list
# Check runtime status
uv run python -m mcard.ptr.cli status --verbose
Flow Execution (Python)
# Execute a declarative flow YAML against a target
uv run python -m mcard.ptr.cli flow sample_pcards/flows/sample_flow_js.yaml \
--target sha256:my_target --inputs '{"param": 1}'
# Async execution path (delegates sync code via thread pool)
uv run python -m mcard.ptr.cli flow sample_pcards/flows/sample_flow_js.yaml \
--target sha256:my_target --inputs '{"param": 1}' --async
JavaScript
# Run all CLMs
npm --prefix mcard-js run clm:all
# Run single file
npx tsx mcard-js/src/ptr/node/cli.ts run chapters/chapter_01_arithmetic/addition_js.yaml --test
# Run all CLMs in a directory
npx tsx mcard-js/src/ptr/node/cli.ts run chapters/chapter_01_arithmetic --test
# List available CLMs
npx tsx mcard-js/src/ptr/node/cli.ts list
# Check runtime status
npx tsx mcard-js/src/ptr/node/cli.ts status
Chapter Directories
| Directory | Description |
|---|---|
chapter_00_prologue |
Hello World, Lambda calculus, identity basics, and Church encoding — 13 CLMs |
chapter_01_arithmetic |
Arithmetic operations (Python, JS, Lean) — 27 CLMs |
chapter_02_handle |
Handle operations and dual retrieval |
chapter_03_llm |
LLM integration (requires Ollama) |
chapter_04_load_dir |
Filesystem and collection loading |
chapter_05_reflection |
Meta-programming and recursive CLMs |
chapter_06_lambda |
Lambda calculus runtime |
chapter_07_network |
HTTP requests, MCard sync, network I/O — 5 CLMs |
chapter_08_P2P |
P2P networking and WebRTC — 16 CLMs (3 VCard) |
chapter_09_DSL |
Meta-circular language definition and combinators — 10 CLMs |
chapter_10_service |
Static server builtin and service management — 3 CLMs |
chapter_11_cicd |
Quality checks (Python, JS, Studio, unified) — 4 CLMs |
networking |
Kenotic PCard workloads (mDNS, signaling) — 2 CLMs |
Contributing
- Fork the repository and create a feature branch.
- Read CONTRIBUTING.md for the normalized workflow and project-wide validation commands.
- Submit a pull request describing your change and tests.
Future Roadmap
Road to VCard (Design & Implementation)
Based on the MVP Cards Design Thesis (LandingPage/pkc-docs/MVP Cards — Design Thesis for Sovereign Knowledge Networks.md), a VCard (Value Card) represents a boundary-enforced value exchange unit that often contains sensitive privacy data (identities, private keys, financial claims). Unlike standard MCards which are designed for public distribution and reproducibility, VCards require strict confidentiality.
Design Requirements & Rationale:
- Privacy & Encryption: VCards cannot be stored in the standard
mcard.db(which is often shared or public) without encryption. They must be stored in a "physically separate" container or be encrypted at rest. - Authentication Primitive: A VCard serves as a specialized "Certificate of Authority" — a precondition for executing sensitive PTR actions.
- Audit Certificates: Execution of a VCard-authorized action must produce a VerificationVCard (Certificate of Execution), which proves the action occurred under authorization. This certificate is also sensitive.
- Unified Schema: While the storage location differs, the data schema should remain identical to MCard (content addressable, hash-linked) to reuse the rigorous polynomial logic.
Proposed Architecture:
- Dual-Database Storage:
mcard.db(Public/Shared): Stores standard MCards, Logic (PCards), and Public Keys.vcard.db(Private/Local): Stores VCards, Encrypted Private Keys, and Verification Certificates.
- Execution Flow:
execute(pcard_hash, input, vcard_authorization_hash)- Gatekeeper: PTR checks if
vcard_authorization_hashexists in the Private Store (vcard.db). - Zero-Trust Verify: Runtime validates the VCard's cryptographic integrity and permissions (Security Polynomial).
- Execute: If valid, the PCard logic runs.
- Certify: A new
VerificationVCardis generated, signed, and stored invcard.db, linking the Input, Output, and Authority.
- Gatekeeper: PTR checks if
TODOs:
- Infrastructure: Implement
PrivateCollection(wrapper aroundvcard.db) in Python and JavaScript factories. - Encryption Middleware: Add a transparent encryption layer (e.g., AES-GCM) for the Private Collection to ensure Encryption-at-Rest.
- CLI Auth: Update
run_clms.pyto accept--auth <vcard_hash>and mount the private keystore. - Certificate Generation: Implement the
VerificationVCardschema and generation logic (VCard.sandwich()in both runtimes).
Logical Model Certification & Functional Deployment
Use of the Cubical Logic Model (CLM) as a "Qualified Logical Model" is strictly governed by principles derived from Eelco Dolstra's The Purely Functional Software Deployment Model (the theoretical basis of Nix).
A CLM is not merely source code; it is a candidate for certification. It only becomes a Qualified Logical Model when it possesses a valid Certification, which is a cryptographic proof of successful execution by a specific version of the Polynomial Type Runtime (PTR).
The Functional Certification Equation:
$$ Observation = PTR_{vX.Y.Z}(CLM_{Source}) $$
$$ Certification = Sign_{Authority}(Hash(CLM_{Source}) + Hash(PTR_{vX.Y.Z}) + Hash(Observation)) $$
Parallels to the Nix Model:
- Hermetic Inputs: Just as a Nix derivation hashes all inputs (compiler, libs, source), a CLM Certification depends on the exact PTR Runtime Version and CLM Content Hash. Changing the runtime version invalidates the certificate, requiring re-qualification (re-execution).
- Deterministic Derivation: The "build" step is the execution of the CLM's verification logic. If the PTR (the builder) is deterministic, the output (VerificationVCard) is reproducible.
- The "Store": The
mcard.dbacts as the Nix Store, holding immutable, content-addressed CLMs. Thevcard.dbacts as the binary cache, holding signed Certifications (outputs) that prove a CLM works for a given runtime configuration.
This ensures that a "Qualified CLM" is not just "code that looks right," but "code that has logically proven itself" within a specific, physically identifiable execution environment.
License
This project is licensed under the MIT License – see LICENSE.
For release notes, check CHANGELOG.md.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcard-0.1.68.tar.gz.
File metadata
- Download URL: mcard-0.1.68.tar.gz
- Upload date:
- Size: 335.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0a0903be5f5f898ff817384a5e2651fb354cda7259ca56615c2876aee75badb6
|
|
| MD5 |
ee94b4c78267febc75182a449417a8d6
|
|
| BLAKE2b-256 |
cc25e8d86f1d5d26e9ed8c9d36664275781a37705898b85e0dc205c79a4ef57f
|
File details
Details for the file mcard-0.1.68-py3-none-any.whl.
File metadata
- Download URL: mcard-0.1.68-py3-none-any.whl
- Upload date:
- Size: 332.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
625a99a7ac636f4f6152ed676f4fb70dd7965b886ca8d51f78b0217fa0b429a2
|
|
| MD5 |
2d1c6266364a406929259b1bf321c8a6
|
|
| BLAKE2b-256 |
d2299a546343fa5f21805b2ec08924e52a04f2a7625e4895336bbc638fbef51b
|