Skip to content

Architecture Overview

NON-NORMATIVE. Describes the current module layout, data flow, and contracts. Normative rules live in AGENTS.md, SSOT.md, and docs/governance/morphism-kernel.md.

System Overview

Morphism is a categorical governance framework split into:

  • Python core (src/morphism/) — governance engine, metrics, drift detection, healing
  • TypeScript packages (packages/) — CLI, MCP servers, math library, design tokens
  • Next.js app (apps/morphism/) — dashboard, API routes, Clerk auth
  • Governance scripts (scripts/) — CI gates, validators, structural enforcement
User / CI / MCP client
        |
        v
  +-- CLI / MCP Server (TS) --+
  |                            |
  |  morphism validate         |
  |  morphism review --gate    |
  |  MCP: governance_validate  |
  |                            |
  +------- calls --------+----+
                          |
                          v
            Python core (src/morphism/)
            +---------------------------+
            |  review/engine.py         | <-- orchestrator
            |    -> governance_category | <-- categorical validation
            |    -> healing/scanner     | <-- drift scan
            |    -> convergence         | <-- kappa computation
            |  governance/kernel.py     | <-- SSOT for constants
            |  metrics/governance_metric| <-- formal metric
            |  healing/drift_healer     | <-- auto-repair
            +---------------------------+
                     |
                     v
            .morphism/ (artifacts)
            +---------------------------+
            |  proofs/*.json            | <-- proof witnesses
            |  config.yaml              | <-- agent config
            |  ARTIFACT_REGISTRY.json   | <-- tracked artifacts
            |  evidence_ledger.json     | <-- evidence entries
            +---------------------------+

Module Map

Python Core (src/morphism/)

Module Responsibility
governance/kernel.py SSOT for all enforcement constants: objects, weights, thresholds, invariants, constraint types, verdict logic
convergence.py Kappa computation (weighted L-inf metric), convergence checks, robustness delta
governance_category.py 7 governance objects, 8 morphisms, categorical validation, naturality, sheaf analysis
review/engine.py Orchestrates validation + drift scan into unified ReviewResult; computes verdict
review/models.py Pydantic models: Severity, Verdict (PASS/WARN/HEDGE/FAIL), EvidenceRef, ReviewIssue, ReviewResult, GateResult
review/formatters.py Output formatting for CLI (text, JSON, Mermaid)
healing/scanner.py DriftScanner: detects 5 drift types (frontmatter, stale dates, broken links, missing invariant refs, encoding)
healing/drift_healer.py DriftHealer: confidence-gated auto-repair with adaptive thresholds
healing/cech_complex.py Cech complex and H1 cohomology for sheaf drift analysis
metrics/governance_metric.py GovernanceState, GovernanceMetric, kappa, delta, entropy, maturity levels, convergence certificates
governance/extended_compliance_functor.py Formal functor F: Governance -> Verification with law verification
agents/classifier.py Maps files to owning agents via glob patterns from config.yaml
engine/naturality_bridge.py Checks naturality squares for governance morphisms
engine/functors.py Category theory primitives: Functor, Morphism
sheaf/cech_complex.py Sheaf cohomology computation
bridge/python_bridge.py JSON-RPC bridge for TS -> Python calls
cli/main.py Python-side CLI entry point

TypeScript Packages

Package Modules Purpose
@morphism-systems/cli validate, score, doctor, status, diff, scaffold, entropy, init User-facing CLI wrapping Python backend
@morphism-systems/mcp-server server, governance-loop, governance-tools, tools/{kappa,delta,entropy,score,ssot,validate} MCP server exposing governance tools to AI agents
@morphism-systems/agentic-math categorical-encoder, naturality-bridge, proof-artifact, engine/{convergence,functor,morphism,natural-transformation} Category theory math library + MCP math server
@morphism-systems/shared types, schemas, supabase, csrf, encryption, rate-limit, stripe, ai Shared utilities for Next.js app
@morphism-systems/design-tokens 10 themes, registry, types Design token system
@morphism-systems/plugin-bundle installers/{config,hooks,mcp} Plugin installer for IDE integration

Next.js App (apps/morphism/)

Layer Key files
Dashboard pages (dashboard)/dashboard/{page,governance/{page,drift/page,proofs/page},agents/page,assessments/page,policies/page,settings/page,billing/page}
API routes api/governance/{route,heal/route,proofs/route}, api/agents/route, api/assessments/route, api/keys/route, api/billing/{checkout,portal}/route
Auth Clerk middleware, @clerk/nextjs/server auth() guards on protected routes
Components governance-score.tsx, ui/{card,badge,button}

Data Flow: Governance Gate

A morphism review --gate call follows this path:

  1. CLI (packages/cli/src/commands/validate.ts) spawns Python subprocess
  2. Python ReviewEngine.gate() is invoked
  3. Engine calls full_categorical_validation(root) which:
  4. Enumerates 7 governance objects and 8 morphisms
  5. Runs runtime verification predicates per object
  6. Builds governance vector s in [0,1]^7
  7. Computes kappa = d_inf(s, ideal)
  8. Checks naturality squares
  9. Runs sheaf (Cech complex) H1 cohomology
  10. Returns {kappa, governance_vector, naturality, sheaf, categorical_errors, all_valid}
  11. Engine calls scan_repo(root) for drift detection
  12. All findings merged into list[ReviewIssue], each tagged with:
  13. source (drift/categorical/naturality/sheaf)
  14. severity (low/medium/high/critical)
  15. evidence (EvidenceRef with kind + location)
  16. agents (owning agents from classifier)
  17. _compute_verdict() applies kernel rules:
  18. FAIL if any critical issue OR kappa > ceiling
  19. HEDGE if confidence < 2.0 (low confidence)
  20. WARN if issues within bounds
  21. PASS if all_valid and no issues
  22. GateResult returned with exit_code (0=pass, 1=fail, 2=error)

Key Constants (from governance/kernel.py)

Constant Value Purpose
GOVERNANCE_OBJECTS 7 (Policy, GitHook, CIWorkflow, SSOTAtom, Document, SecurityGate, Runbook) Dimensions of governance vector
GOVERNANCE_WEIGHTS Policy=1.5, SecurityGate=1.5, GitHook=1.2, CIWorkflow=1.2, SSOTAtom=1.0, Runbook=0.9, Document=0.8 L-inf metric weights
THRESHOLD_KAPPA low=1.5, medium=1.0, high=0.5, critical=0.25 Gate thresholds
HEDGE_CONFIDENCE_THRESHOLD 2.0 Below this -> HEDGE verdict
KERNEL_INVARIANTS I-1..I-7 Seven kernel invariants

Verdict Semantics

Verdict Meaning Gate behavior
PASS Clean, all valid exit_code=0
WARN Issues found but within threshold exit_code=0
HEDGE Low confidence, needs additional verification exit_code=0
FAIL Critical issue or kappa ceiling breach exit_code=1

Constraint Classification

Type Examples Gate effect
HARD Critical severity, kappa ceiling, sheaf incompatibility Always FAIL
SOFT Issues within bounds, categorical invalid, low confidence WARN or HEDGE

External Services

Service Integration
Clerk Auth for API routes and dashboard
Supabase Agent, assessment, policy data storage
Sentry Error tracking and alerting
Vercel Hosting and deployment
Pinecone Governance vector index (142 vectors)