ITADN
GoToMarketNow/MarkMeDown
README.md

MarkMeDown — ContextCore

Context Drives Outcomes with AI.

Next.js 16 React 19 TypeScript 5 Prisma 7 Platform Status

MarkMeDown captures a company's docs, apps, people, and processes into a structured, governed context layer — the Company Context Graph — and delivers it, with enforceable governance contracts, to every AI that touches the business. AI without your business context is a language model guessing. This platform turns tribal knowledge into machine-readable context, wraps every autonomous agent in a contract you control, and gates every agent action through a 10-stage compliance pipeline before it executes.

Reading this as an LLM / pasting it into chat? This README is written to double as a platform context document. Sections 1–3 prime you on vocabulary and the mental model; the Platform Map (§13) is your lookup table for where features live; Repository Conventions (§15) are the rules any change must follow; and the closing Playbook (§19) explains how to turn this document + research into a deployable Claude Code feature spec.


Table of Contents

  1. TL;DR — What This Is
  2. Core Vocabulary
  3. The Mental Model — Context · Contracts · Confidence
  4. The Problem
  5. The Company Context Graph (CCG)
  6. Agent Governance
  7. The Unified Agent Builder (/build)
  8. Mark — AI Ops Guide
  9. Context Lifecycle Systems
  10. OpenClaw Ecosystem
  11. Developer Platform
  12. Pricing
  13. Platform Map
  14. Architecture & Tech Stack
  15. Repository Conventions
  16. Production Status & Metrics
  17. Getting Started
  18. The Playbook — Research + README → Claude Code Spec
  19. License

1. TL;DR — What This Is

MarkMeDown (codebase: ContextCore) is a multi-tenant SaaS platform that does three things, in order:

  1. Captures context — Ingests documents, connected SaaS apps, and human interviews; classifies everything into a 9-layer Company Context Graph (CCG) of machine-readable, versioned, confidence-scored knowledge files (CCGML).
  2. Governs agents — Every AI agent runs under an AgentContract (capabilities, boundaries, autonomy tier, escalation rules, kill switch). Every action passes a 10-gate CIE pipeline before executing, and every context change, ruling and run lands on a signed, hash-chained integrity ledger — governance you can cryptographically prove.
  3. Delivers context everywhere — Through a REST API, a per-org MCP server, an SDK, a CLI, webhooks, and OpenClaw workspace files — so any LLM, agent runtime, or commercial tool gets the same governed business context.

Concept-at-a-glance:

  • CCG — 9 semantic layers (L1_IDENTITY → L9_RELATIONSHIPS), CCGML markdown files with rich frontmatter, semantic relationship edges, decay-based freshness, 4D confidence.
  • Governance — 4 autonomy tiers, contract enforcement, 10-gate action pipeline (CIE), graduated trust earned from sandbox performance.
  • Unified Agent Builder — one /build flow with Journey (no-code) and Architect (governance) modes over a shared AgentSpecV3, with a deploy-time context-assessment gate that blocks deployment when critical context is missing.
  • Mark — an AI ops guide with a 13-segment system prompt, role personas, voice I/O, and a 42-module intelligence corpus.
  • Lifecycle engines — Atlas translation pipeline, Context Integrity Engine, Research Engine, App Connect, Feedback Bridge, Assessment Engine, Golden Path, Sandbox.
  • Stack — Next.js 16 · React 19 · TypeScript 5 · Prisma 7 (Postgres/SQLite dual-adapter) · Inngest · Vercel KV · Stripe · Supabase · pgvector · Anthropic Claude.

2. Core Vocabulary

The platform's load-bearing nouns. Learn these and the rest of the system reads cleanly. Canonical source files in parentheses.

TermDefinitionSource
CCGCompany Context Graph — the 9-layer graph of everything the business knowssrc/lib/ccg-context.ts
CCGMLThe file format for a CCG node — Markdown + structured frontmatter (authority, temporal, classification, security)src/lib/ccg-schema.ts
LayerOne of 9 semantic buckets: L1_IDENTITY … L9_RELATIONSHIPSsrc/lib/ccg-schema.ts
DomainA hierarchical topic path within layers (e.g. operations/dispatch); has a maturity score L0–L5src/lib/ccg-domain-maturity.ts
RelationshipA typed edge between nodes — constrains, requires, supersedes, owned_by, requires_approval_from, … (16 types)src/lib/ccg-schema.ts
Decay profileFreshness model: volatile_7d, standard_90d, stable_365d, immutable, customsrc/lib/ccg-decay.ts
Confidence (4D)Declared + observed confidence, drift velocity, drift direction per nodesrc/lib/ccg-learning.ts
Intent assemblyQuery-intent-driven, token-budgeted context retrieval across layers/domainssrc/lib/ccg-intent-patterns.ts
Hybrid retrievalpgvector semantic + tsvector fulltext + RRF fusion + graph-informed rerankingsrc/lib/retrieval/
AgentContractThe governance object bounding one agent: capabilities, access, constraints, prohibitions, escalation, kill switch, rate limits, lifecyclesrc/lib/contracts/, prisma/schema.prisma
Autonomy tierTrust level 1 (Autonomous) → 4 (Info-Only)src/lib/ccg-authority.ts
CIEContext Integrity Engine — evaluates graph health and runs the 10-gate action pipelinesrc/lib/cie-gates.ts
Gate (G1–G10)One of 10 pre-execution checks every agent action passessrc/lib/cie-gates.ts
CCSContext Confidence Score — weighted graph-quality score (completeness, consistency, recency, specificity)src/inngest/cie-compute-ccs
AgentSpecV3The single canonical builder state; intent (Journey) + contract overrides (Architect)src/lib/agent-spec/types.ts
Claw / OpenClaw / NemoClawGoverned workspace-file delivery; OpenClaw = workspace generator, NemoClaw = YAML policy runtimesrc/lib/openclaw/, src/lib/claw/
MarkThe in-app AI ops guidesrc/lib/mark/
AtlasTranslation pipeline + trust framework (doc → CCGML; multi-language; provenance)src/lib/atlas/
Golden PathIndustry-specific guided journey from zero to AI-readysrc/lib/golden-path.ts
HITLHuman-in-the-Loop — the unified review/approval queue/hitl, src/lib/contracts/
BYOKBring Your Own Key — customer-supplied LLM credentials, AES-256-GCM encryptedsrc/lib/byok.ts

3. The Mental Model — Context · Contracts · Confidence

graph LR
    A["Business Knowledge<br/>(docs · apps · people)"] --> B["Capture"]
    B --> C["Company Context Graph"]
    C --> D["Contract & Govern"]
    D --> E["10-Gate CIE Pipeline"]
    E --> F["AI Agents Act"]
    F --> G["Outcomes → Feedback"]
    G --> C

    style C fill:#0f172a,stroke:#10b981,color:#10b981
    style D fill:#1e293b,stroke:#f59e0b,color:#f59e0b
    style E fill:#1e293b,stroke:#ef4444,color:#ef4444

Three capabilities work together:

  • Your Context (CCG) — your actual operational logic, captured from three sources: people & tribal knowledge, applications & digital workflows, and documents & data. Three sources, one truth.
  • Your Contracts (Governance) — every agent operates under a contract that defines what it can see, what it can do, when it needs approval, and what happens when it's uncertain. Enforcement is structural — built in before anything runs, not monitored after the fact.
  • Your Confidence (CIE) — every action passes a 10-gate pipeline. Compliance isn't a feature you turn on; it's how the platform works. The pipeline short-circuits on first failure and logs every gate result.

4. The Problem

Every business adopting AI hits the same wall: agents are powerful, but they don't know your business.

ChallengeWhat Happens
Knowledge lives in people's headsWhen key staff leave, critical context walks out the door
Documents are unstructured chaosPDFs, wikis, Slack threads — none of it is machine-readable
AI hallucinates without contextAgents make confident decisions based on nothing
No governance for autonomous agentsNo contracts, no boundaries, no audit trail, no kill switch
OptionCostTimelineOutcome
Hire consultants$200K–$2M+6–18 monthsReport sits on a shelf
Build in-house$500K–$3M+/yr12–24+ monthsCustom but fragile
Buy generic AI tools$50K–$300K/yrMonthsDiscover it doesn't work
MarkMeDownStarts freeHoursContext live, agents governed, results today

5. The Company Context Graph (CCG)

A structured, interconnected, versioned graph of everything a business knows, organized by semantic purpose across 9 layers. Source of truth: src/lib/ccg-schema.ts, traversal in src/lib/ccg-context.ts, governance in src/lib/ccg-authority.ts.

graph TB
    subgraph CCG["Company Context Graph"]
        L1["L1 IDENTITY · who we are, structure, services"]
        L2["L2 STRATEGY · goals, positioning, growth"]
        L3["L3 OPERATIONS · workflows, procedures"]
        L4["L4 RULES · policies, compliance, limits"]
        L5["L5 MEMORY · past decisions, lessons"]
        L6["L6 AUTHORITY · decision rights, approvals"]
        L7["L7 INTEGRATIONS · stack, APIs, data flows"]
        L8["L8 BOUNDARIES · hard limits, prohibitions"]
        L9["L9 CONTACTS · teams, vendors, relationships"]
    end
    L1 --> L3
    L2 --> L3
    L4 --> L6
    L6 --> L8
    L3 --> L7
    L5 --> L3
    CCG --> CA["Intent-Based Context Assembly"]
    CA --> AG["AI Agents · LLMs · Tools"]

    style L6 fill:#0f172a,stroke:#f59e0b,color:#e2e8f0
    style L8 fill:#0f172a,stroke:#ef4444,color:#e2e8f0
    style CA fill:#1e293b,stroke:#10b981,color:#10b981

CCGML — the file format

Each node is a Markdown file with structured frontmatter:

  • authority — owner, approvers, decision level, autonomy tier, governance class, change_requires
  • temporal — effective date, review-due date, seasonal variants, business-hours-only, timezone
  • classificationtaxonomy · policy · procedure · decision_framework · entity_model · constraint · narrative · history
  • security_classificationpublic · internal · confidential · restricted (enforced at query time)
  • Node types — policy, procedure, role, product, service, metric, kpi, entity, integration, strategy, playbook, segment, taxonomy, constraint, narrative, decision_framework

Graph semantics

  • 16 relationship types — governance edges (constrains, informed_by, requires, triggers, supersedes, conflicts_with, inherits_from) and business edges (owned_by, requires_approval_from, governed_by, measured_by, depends_on, serves, escalates_to, integrates_with, priced_at) — with automatic conflict detection.
  • Decay profilesvolatile_7d, standard_90d, stable_365d, immutable, custom — stale content is flagged automatically.
  • 4D confidence — declared confidence, observed confidence, drift velocity, drift direction.
  • Domain maturity — L0 (empty) → L5 (comprehensive) scored per domain.

Context assembly & hybrid retrieval

Intent-based assembly delivers exactly the right context per query: query intent selects the layers/domains/depth to traverse, under a token budget allocated across primary files, related files, and relationships.

graph LR
    Q["Manifest-scoped query"] --> P["Retrieval profile"]
    P --> V["File + passage pgvector"]
    P --> T["File + passage tsvector"]
    V --> R["RRF fusion"]
    T --> R
    R --> G["Bounded graph expansion and reranking"]
    G --> O["Evidence-complete token packing"]
    O --> C["Coverage and retrieval diagnostics"]
    style G fill:#1e293b,stroke:#f59e0b,color:#f59e0b

Semantic search uses OpenAI text-embedding-3-small (1536 dims); fulltext uses Postgres tsvector; file and section-aware passage candidates merge via Reciprocal Rank Fusion, then bounded graph relationships rerank and expand the evidence. fast, balanced, complete, and integrity profiles set a manifest-enforced quality floor so agent requirements choose the retrieval cost/coverage posture without creating a custom pipeline per agent. Tenant, manifest, publication, and sensitivity filters are applied before candidate retrieval and graph traversal. (src/lib/retrieval/)


6. Agent Governance

Every agent runs under an AgentContract. Enforcement is structural and pre-execution. Models in prisma/schema.prisma; logic in src/lib/contracts/ and src/lib/cie-gates.ts.

Contract anatomy

ComponentWhat it controls
Access controlRead/write per CCG layer, path patterns, exclusions
CapabilitiesAllowed actions per domain, with conditions
Hard constraintsUnbreakable rules — never violated regardless of context
Soft constraintsWarnings that flag risky actions without blocking
ProhibitionsExplicit forbidden actions
Escalation rulesTarget role, channel, timeout, fallback behavior
Kill switchInstant contract revocation — agent stops immediately
Rate limitsActions/hour, decisions/day, CCG writes/run
Audit levelFull decision trail with reasoning, confidence, authority source
LifecycleEffective / expiration / review dates, version history

4 Autonomy Tiers — trust is earned

TierModeScope
Tier 1AutonomousActs independently within contract boundaries, full audit
Tier 2Supervised / GuidedActs within domains, human notified after
Tier 3Approval Required / ReportingProposes; human approves before execution
Tier 4Info-OnlyRead-only; observes, cannot act

The 10-Gate CIE Action Pipeline

Every action passes 10 gates before executing. Short-circuits on first failure; every result logged.

GatePurpose
G1IdentityVerify agent/user identity and org membership
G2ContractValidate active contract and appropriate autonomy tier
G3Kill SwitchImmediate deny if kill switch active
G4CCG RulesValidate against CCG governance rules and boundary constraints
G5Behavioral GovernanceEnforce hard/soft constraints and prohibitions
G6ConfidenceContext confidence must meet threshold for this action type
G7ComplianceIndustry framework verification (HIPAA, SOC 2, FINRA, GDPR, PCI-DSS, …)
G8Temporal / ResourceOperating-hours and resource-budget checks
G9Rate / CostRate-limit and cost-budget enforcement
G10ApprovalDetermine if human approval required → routes to HITL queue

CIE Wave 1 — Provable integrity (shipped)

Governance decisions are no longer just logged — they are provable. Models in prisma/schema.prisma (LedgerEntry, LedgerActor, LedgerKey, LedgerAnchor, LedgerVerification, IntegrityRuling, RulingApproval); logic in src/lib/ledger/ + src/lib/integrity/.

  • Hash-chained ledger — every context change, ruling, verification and run appends an Ed25519-signed entry (18 entry kinds, from genesis.open to history.imported) to a per-org monotonic chain; sensitive fields are erasable (AES-256-GCM) without breaking the chain.
  • Merkle anchoring + proof API — chains are anchored with Merkle roots (LedgerAnchor, chained via prevAnchorHash); GET /api/cie/integrity/proof returns entry, signature, lineage and the Merkle inclusion path with public keys — everything needed to re-verify offline.
  • Dual-control rulings — contested facts resolve via IntegrityRuling requiring a proposer + second approver (both Ed25519-signed); UI at /integrity/rulings with break-glass override.
  • Blast-radius simulationsrc/lib/integrity/blast-radius.ts reports affected files/contracts/assertions before a ruling lands; captured in IntegrityRuling.blastRadius.
  • Contested-context serving — disputed facts are flagged to every agent that reads them until ruled.
  • Calibrated confidence — isotonic calibration (src/lib/cie/calibration.ts) keeps CCS scores meaningful after rulings.
  • FlagsINTEGRITY_FEATURES env + per-org OrgSettings.integrityFlags (resolver: src/lib/integrity/flags.ts). Ledger + rulings shipped; the mediate cascade (automatic conflict adjudication with off/shadow/enforce modes) is in flight on feat/cie-mediate-cascade.

Lifecycle infrastructure

  • Provisioning — deployment yields a one-time provision token; exchanging it returns API key + contract + workspace files + compiled policies.
  • Heartbeat — agents ping; status tracked Healthy / Degraded / Stale / Unknown; webhooks fire on transitions; stale detection runs via cron.
  • Escalation → HITL — out-of-confidence decisions route to a priority review queue; human decision delivered async to the agent's clawEndpoint.
  • Graduated trust — sandbox score ≥90% → Tier 2, ≥75% → Tier 3, <75% → Tier 4. Upgrades require sustained confidence/drift/divergence data.
  • Decision audit trail — tier used, confidence, CCG files consulted, reasoning chain, authority source (L6 path), boundaries checked (L8 paths), escalation status.

7. The Unified Agent Builder (/build)

Recently unified. Three divergent builders — the old Agent Design Studio (/launch/build, 7-step), Journey v2 (/journey/[id], 10-stage), and the legacy /agents/builder — were collapsed into one flow at /build/[specId] with two modes over a single shared spec. The legacy routes now permanently redirect to /build (next.config.ts).

graph LR
    D["Describe"] --> I["Identity"] --> A["Access"] --> C["Context"]
    C --> G["Guardrails"] --> R["Review"] --> B["Battle Test"] --> Dep["Deploy"]
    style C fill:#1e293b,stroke:#f59e0b,color:#f59e0b
    style Dep fill:#1e293b,stroke:#10b981,color:#10b981

One spec, two modes

The single canonical state is AgentSpecV3 (src/lib/agent-spec/types.ts):

  • Journey mode (no-code, conversational) writes only spec.intent (JourneyV2State) — plain-English business intent.
  • Architect mode (granular governance) writes spec.contract overrides. The effective contract is always re-derived from intent via projectToContract (projection.ts), then overrides are layered on top. overriddenFields records hand-edits so intent re-derivation never clobbers them.

The two sections are orthogonal, so toggling modes mid-flow is lossless. migrate.ts (ensureAgentSpec) wraps legacy v2/journey blobs as spec.intent. State persists in JourneySession.wizardState + currentMode/currentStep columns (src/hooks/use-agent-spec.ts). The existing AgentDesignStudio step components render unchanged via an adapter (use-architect-studio.ts).

Deploy-time context-assessment gate (the headline feature)

Before an agent can deploy, the platform checks whether the CCG actually contains the context the agent needs:

  • inferContextRequirements (src/lib/launch/context-requirements.ts) composes computeAllDomainMaturities + getResearchTargets + DOMAIN_TO_CCG_LAYER.
  • assessDeployReadiness (deploy-assessment.ts) blocks deploy on critical/blocking gaps only; advisory gaps warn. Only 7 of 10 canonical domains are measurable; unmeasurable domains are advisory (never block).
  • Enforced both client-side (step-deploy.tsx, step-context.tsx via /api/v1/launch/assess-readiness) and server-side (422 in the deploy route).
  • Deterministic clarifying questions (clarifying-questions.ts) scan the description for gaps and surface on the Describe step.

One deploy path

POST /api/v1/build/[specId]/deploy handles both modes: projects the contract server-side, runs the context gate, then atomically creates the Agent + Contract + provision token. Journey users now receive an active contract and token (previously only a draft).

Battle test

Step 6 spins up a real sandbox and runs the agent through the CIE 10-gate pipeline against test scenarios — gate-by-gate pass/fail with reasoning — so you see exactly how the agent behaves before production.


8. Mark — AI Ops Guide

Not a chatbot — an operations guide that knows your context graph. (src/lib/mark/, 42 modules.)

CapabilityDetails
Role personasOwner/Admin (strategic), Builder (technical), Contributor (domain), Viewer, Guest
ChannelsSidebar, Fullpage, Voice, Tooltip, Docs
View modesCollapsed pill, Compact, Expanded, Fullscreen
Voice I/OPush-to-talk + continuous listening via ElevenLabs (TTS + STT)
Model routingOpus (compliance/governance), Sonnet (general), Haiku (nudges)
Confirmation protocol4 tiers — read-only / reversible / significant / irreversible

Intelligence: a 13-segment system prompt (identity, persona, screen context, org context, industry/compliance, CCG health, CCG context, golden path, product knowledge, docs, patterns, cross-channel, confirmation). 12 industry verticals with compliance frameworks. Pattern recognition, A/B testing, downstream-impact analysis for CCG changes, cross-channel continuity. Knowledge corpus: 13 domain modules backed by 62 cited references and a 27-scenario interaction matrix.


9. Context Lifecycle Systems

How context enters, stays healthy, and improves. Each system is independent and composable.

SystemWhat it doesSource
Atlas Translation Pipeline6 stages — Ingest → Classify → Extract → Reconcile → Generate → Validate — turns PDFs/DOCX into CCGMLsrc/lib/atlas/, document-parsing
Context Integrity Engine (CIE)5 analysis layers (Structural, Semantic, Operational, Temporal, Negative-Space) → CCS = Completeness 30% + Consistency 30% + Recency 20% + Specificity 20%; Wave 1 adds the provable-integrity ledger, rulings and calibration (see §6)src/lib/cie-gates.ts, src/lib/cie/, src/inngest/cie-*
Value Realization LedgerRealized + estimated value per agent, in dollars, attributed to the CCG files that produced it; surfaced at /manage/value and /api/v1/insights/valuesrc/lib/ai-ledger.ts, src/lib/value/auto-emit.ts
Activation PipelineFree-tier signup → gap map → first look over the customer's own files → estimated value emitted; Inngest-checkpointed (assessfirstLookvalue)src/inngest/activation-quickstart.ts, src/lib/activation/
Research EngineDeep research via Python microservice (FastAPI + GPT-Researcher); gap analysis, context-fill, credits (1/5/5/10 RC by type)src/lib/research/
App ConnectOAuth connections → schema discovery → logic-unit extraction → drift & conflict detection; 20+ providerssrc/lib/connect/, src/lib/connectors/
Feedback BridgeClosed loop — rate outcome → trace to CCG files → auto-refine → unified review queue → CCG updatedsrc/lib/feedback-bridge.ts
Context Assessment EngineFree 6-step readiness wizard; NorthStar graph (50+ verticals); dual CCG scoring vs industry mediansrc/lib/assessment/
Golden PathIndustry guided journeys — 30 use cases across 6 industries with seed templates + readiness scoringsrc/lib/golden-path.ts, industry-use-cases.ts
Agent SandboxIsolated test env with CCG snapshot; scenario scripts; graduated trust promotion/agents/sandbox, src/inngest/sandbox-test

Unified review queue has 4 source types: human edits, agent feedback, CIE findings, drift alerts. Edit provenance tracks the source of every CCG change.


10. OpenClaw Ecosystem

Governed context delivery for any AI runtime. OpenClaw compiles the CCG into portable workspace files that any agent consumes with governance intact. (src/lib/openclaw/, src/lib/claw/)

graph LR
    A["Company Context Graph"] --> B["Governance Bridge"]
    B --> C["Workspace Generator"]
    C --> D["SOUL · AGENTS · IDENTITY<br/>USER · TOOLS · HEARTBEAT (.md)"]
    D --> E["Any AI Runtime"]
    style A fill:#0f172a,stroke:#10b981,color:#10b981
  • Workspace files (6): SOUL.md (identity/mission, 2000-word budget), AGENTS.md (deployed agents + contracts), IDENTITY.md (org from L1), USER.md (roles/escalation from L2/L9), TOOLS.md (apps/APIs from L7), HEARTBEAT.md (health/freshness).
  • Governance → autonomy bridge: CCG completeness computes a readiness score that maps directly to OpenClaw tier assignment (Comprehensive → Tier 1 … Minimal → Tier 4). Trust is computed, not configured.
  • 5 industry templates with compliance baked in (Manufacturing/OSHA+ISO 9001, Healthcare/HIPAA, Professional Services/SOX, Technology/SOC 2, Retail/PCI DSS).
  • NemoClaw policy generation: the OpenShell compiler translates contracts + CCG rules into YAML policies with domain scoping, action permissions, escalation triggers.
  • Every channel: dashboard (/agents/[agentId] → Runtime), REST API, MCP tools (generate_workspace, generate_policy), SDK (client.claw), CLI (mmd claw …).

11. Developer Platform

Six integration channels deliver governed CCG context to any consumer.

ChannelDescription
REST APIOpenAPI 3.1; v1 (public) + v2 (agent runtime); granular scope auth; key rotation with grace periods
MCP ServerPer-org endpoint /api/mcp/{orgSlug}; 26 tools, 4 resources, 3 prompts; Streamable HTTP, SSE, JSON-RPC transports
TypeScript SDK@markmedown/sdk — typed client, 16 namespaces, auto-pagination, retry/backoff, webhook signature verification
CLI@markmedown/cli (mmd) — 18 commands: CCG management, context assembly, git sync/context-sync, CCGML generate, agent validation, sandbox testing; CI/CD-ready
WebhooksHMAC-SHA256 signed; 21 event types; exponential retry + dead-letter queue; field filtering
OpenClawWorkspace generation + NemoClaw policy compilation + governance bridge (see §10)

MCP server detail

Resources: ccg://org/{orgId}/files, …/file/{fileId}, …/layers/{layer}, …/health. Prompts: governance_check, context_briefing, drift_analysis. Tool families (25 total, defined in src/lib/mcp/tool-registry.ts):

  • Core CCGassemble_context, check_boundary, get_authority, search_context, get_confidence, list_layers, get_governance
  • CCG architectureccg_resolve, ccg_traverse, ccg_list_domains, ccg_freshness, ccg_intent_patterns
  • Governance / Clawcontract_check, product_catalog, escalation_check, context_refresh, policy_lookup, contract_status, contract_delegate, contract_report_violation
  • Workspace & deploymentgenerate_workspace, generate_policy, agent_provision, agent_status, search_answers

Auth, keys, BYOK

  • Scopesccg:read/write, agents:read/write, cie:read/write, audit:read, admin.
  • API keys — bcrypt-hashed, rotation with grace period, per-key usage in hourly buckets, plan-based rate limits via Vercel KV.
  • BYOK — bring your own OpenAI/Anthropic/Google/Azure key, AES-256-GCM encrypted; ~20% off paid tiers.
  • Interactive docs — Swagger UI at /api/v1/docs.

12. Pricing

Start free (permanent, not a trial). Every plan includes processing, quality checks, and full API access.

FreeStarterGrowthProEnterprise
Price$0$49/mo$149/mo$399/mo$799/mo
BYOK$39$119$319$639
TargetExploreSolo5–2525–100100+
CCG Files51550200Unlimited
AI Agents12510Unlimited
AI Credits/mo500K2M5M10M20M
Connectors135Unlimited
MCP Connections12310
Sandbox / CIE Auto-Correct
Voice / Dev Portal / SSO

Billing via Stripe — subscriptions, checkout, customer portal, webhook-driven lifecycle, AI credit packs.

Value realization is measured, not asserted: the value ledger tracks realized + estimated value per agent (AiActionLedger + auto-emitted value events, /manage/value), so "pay when agents create value" is auditable.


13. Platform Map

A reference lookup for where a feature touches the system. Use this when scoping a change.

Route map (App Router, by group)

  • (auth)/login, /signup, /setup, /onboarding, /org-select
  • (assess)/assess/{start,industry,apps,connect,review,results} (6-step readiness wizard)
  • (dashboard) — the app shell:
    • Build & agents/build/new, /build/[specId], /agents, /agents/[id]/{activity,approvals,performance,contract}, /agents/sandbox/[id]
    • Context/ccg, /ccg/[fileId], /context-graph, /context/{connections,documents,knowledge-map,research}, /context-hub
    • Connect/connect, /connect/catalog, /connect/wizard/[provider]
    • Research/research, /research/new, /research/context-fill
    • Manage & govern/manage/{approvals,audit,contracts,performance,value}, /hitl, /integrity, /integrity/{rulings,authority,queue}, /audit
    • OpenClaw — workspace generation lives on the agent detail page (/agents/[agentId] → Runtime); contracts at /manage/contracts; /golden-path/[useCaseId]
    • Settings/settings/{general,users,api-keys,api-mcp,billing,developers,webhooks,security}
    • Other/assistant (Mark), /goals, /interviews, /templates, /translate, /sla, /repository
  • (ops)/ops, /ops/{agents,cost,escalations,runs} (OpsCore fleet view)
  • (partner)/partner, /partner/{orgs,revenue,settings} (white-label; branding applied to app shell)
  • (public)/, /pricing, /how-it-works, /features, /security, /industries/[slug], /docs/*, /for-developers, /openclaw, /mark

API surface (grouped families under /api)

  • v1/ccg/* — files, context, search, traverse, resolve, health, versions, export
  • v1/agents/*, v1/build/[specId]/deploy, v1/launch/* — the five session-authed builder endpoints that survived the /launch retirement (suggest, preview, context-preview, assess-readiness, test-gates); v1/launch/{deploy,build-deploy} are deliberate 410 tombstones pointing at the governed v1/build/[specId]/deploy, not usable endpoints
  • v1/journey/* — builder session CRUD, compile, writeback, ask-mark, audit, templates (list)
  • v1/manage/contracts/*, v1/manage/approvals — contract lifecycle + HITL
  • v1/cie/* — analyze, gaps, assertions, contradictions, ccs, upg · cie/integrity/proof — proof-of-integrity (offline-verifiable)
  • v1/git-sync/* — repo connections, sync runs, PR-based outbound, change-request inbound · v1/insights/value — per-agent value
  • v1/connect/*, v1/connectors/* — app connections, sync jobs, logic units, daemon
  • v1/research/*, v1/convert/*, v1/sandbox/*, v1/claw/*, v1/openclaw/*
  • v1/partner, v1/translation, v1/developer, v1/goals, v1/use-cases, v1/insights
  • v2/agent/* — runtime gateway (decide, boundaries, context, contract, escalation, heartbeat, provision, report)
  • mcp/{orgSlug} — per-org MCP server · claw/* — workspace generation · webhooks, health, admin/ai-ledger

Data model (151 Prisma models, by group)

prisma/schema.prisma. Group → representative models:

  • Org / AuthUser, Organization, OrgMembership, ApiKey, ByokCredential, Webhook, PartnerOrg
  • CCGCcgFile, CcgRelationship, CcgSource, CcgBlueprint, DecayProfile, DomainRegistry, IntentPattern
  • Agents / ContractsAgent, AgentContract, AgentContractVersion, AgentContractExecution, AgentContractViolation, ContractDriftSnapshot, AgentDecision, AgentHeartbeat, AgentWorkflow, AgentHandoff, EscalationRequest
  • CIECieAnalysisRun, Assertion, Contradiction, Gap, UpgNode, UpgEdge, CcsSnapshot
  • Integrity ledgerLedgerEntry, LedgerActor, LedgerKey, LedgerAnchor, LedgerVerification, IntegrityRuling, RulingApproval
  • ConnectConnector, ConnectorSyncJob, ConnectorLogicUnit, EnrichmentSuggestion, IntelligenceSource
  • ResearchResearchRun, ResearchEnrichment, ResearchCredit, ResearchCache
  • BillingSubscription, BillingEvent, AiCreditBalance, AiActionLedger
  • MarkMarkConversation, MarkSessionState, MarkEngagementLog, MarkUserPattern, MarkExperiment, MarkSupportCase
  • Governance / AuditChangeRequest, AuditLog, ConfidenceHistory, DriftMetric, DivergencePattern, SlaMetric
  • Goals / Use casesGoal, GoalObjective, OrgUseCase, IndustryTemplate
  • Builder / OpsJourneySession, JourneyAuditEvent, JourneyCcgChange, ContractWorkflowSession, Sandbox, OpsAgentRun, ClawWorkspace, ActivationRun

14. Architecture & Tech Stack

graph TB
    subgraph FE["Frontend — Next.js 16 + React 19"]
        UI["Dashboard · TanStack Query"]
        BLD["Unified Agent Builder (/build)"]
        MK["Mark AI"]
    end
    subgraph API["API Layer"]
        V1["REST v1 (public)"]
        V2["REST v2 (agent runtime)"]
        MCP["MCP Server (per-org, 25 tools)"]
        WH["Webhooks (HMAC)"]
    end
    subgraph ENG["Core Engine"]
        CCG["CCG"]
        CIE["CIE 10-gate"]
        GOV["Governance / Contracts"]
        ATL["Atlas Pipeline"]
        AC["App Connect"]
        RES["Research Engine"]
        HYB["Hybrid Retrieval"]
        CLAW["OpenClaw"]
    end
    subgraph INF["Infrastructure"]
        DB["Prisma 7 + Supabase Postgres / SQLite"]
        INN["Inngest (58 handlers)"]
        KV["Vercel KV (cache + rate limit)"]
        STR["Stripe"]
        SEN["Sentry"]
        PGV["pgvector + tsvector"]
        GPT["GPT-Researcher (FastAPI)"]
    end
    FE --> API --> ENG --> INF
CategoryTechnology
FrameworkNext.js 16, React 19, TypeScript 5, Tailwind CSS 4
DatabasePrisma 7 — dual adapter: PostgreSQL (Supabase, pgbouncer) / SQLite (local)
AuthNextAuth v5 — Credentials, Google, GitHub
AIAnthropic Claude SDK (translation, classification, Mark, agent config); OpenAI embeddings
Searchpgvector (1536d) + tsvector + RRF + graph rerank
ResearchGPT-Researcher (FastAPI microservice)
VoiceElevenLabs (TTS eleven_turbo_v2_5 + STT scribe_v1)
MCP@modelcontextprotocol/sdk — 25 tools, 4 resources, 3 prompts
AsyncInngest — durable workflows, webhook delivery, embeddings, research, scheduled jobs
CachingVercel KV (Redis)
BillingStripe
ValidationZod 4 (zod/v4 import path)
StateTanStack Query v5
Monoreponpm workspaces — @markmedown/sdk, @markmedown/cli
  • Dual Prisma adapterDATABASE_URL scheme decides: postgresql:// → PG adapter (pool max=5, timeout=5s); else SQLite.
  • Inngest — 58 handler modules in src/inngest/ (CCG agents, governance, assessment, connectors, ingestion, research, engagement, scheduled).
  • Deployment — Vercel (region iad1), 7 cron jobs, Sentry (server/client/edge), GitHub Actions CI: lint + typecheck → test + e2e smoke → build.

15. Repository Conventions

Rules any change (human or agent) must follow. Full detail in CLAUDE.md and .claude/rules/.

Security & multi-tenancy

  • All API routes use withAuth(handler) or withAdminAuth(handler) from src/lib/api-utils.ts. Never roll custom auth.
  • Every Prisma query scopes by orgId — this is multi-tenant. Child models lacking their own orgId scope through the relation (e.g. AgentContractVersion via contract: { orgId }).
  • Validate request bodies with parseBody(req, schema) using zod/v4. Return safe errors via apiError(message, status) — never leak internals.
  • Validate URL inputs against SSRF; never log secrets or decrypted BYOK values.

Patterns to reuse (don't reinvent)

  • withCache(key, ttl, fetcher), invalidateCache, CacheKeys, CacheTTLsrc/lib/cache.ts.
  • rate-limit.ts — plan-based sliding windows on public endpoints.
  • Inngest step.run() for idempotent checkpointing; long ops belong in handlers, not routes.
  • emit() in ccg-events is async (writes to DB) — callers must await.
  • Prefer UI primitives in src/components/ui/ and the semantic design tokens in globals.css.

Coding style — strict TS (no any except the documented zod-to-json-schema cast); const arrow components; early returns; path alias @/*; max ~50 lines/function; one exported component/file.

Testing — every new src/lib/*.ts gets a colocated .test.ts; every new API route gets an E2E test in e2e/tests/ (Page Object Model + data-testid selectors in e2e/utils/selectors.ts, tagged @smoke).

Verification gate (never skip)npm run test + npx tsc --noEmit + npm run lint. For non-trivial changes, run the code-reviewer agent.


16. Production Status & Metrics

Shipped (30 phases): Foundation → Infrastructure → Billing → Developer Platform → Industry & Onboarding → App Connect → Industry Content → Navigation → Feedback Bridge → Context Graph UI → Sandbox → Mark Foundation → Personalized Dashboard → Mark AI (full) → Brand Identity → Mark Firmware → Assessment Engine → Connected Apps Daemon → Agent Workflows → Atlas Trust Framework → Agent Builder → AI Services Platform → Hybrid Retrieval → Hybrid Architecture v2 → Research Engine → OpenClaw Ecosystem → Agent Contracts v2 (10-gate pipeline) → Unified Agent Builder (/build) → Activation Pipeline (first agent on your own files)Value Realization Ledger (/manage/value)CIE Wave 1 (provable integrity: signed ledger, Merkle anchoring, dual-control rulings).

In flight: CIE mediate cascade — automatic conflict adjudication with off/shadow/enforce modes (feat/cie-mediate-cascade, direction only, not yet merged).

Codebase metrics

  • 151 Prisma models with rich relationships and indexing
  • 365+ API route handlers across v1, v2, MCP, OpenClaw, research, health
  • 130+ dashboard pages across CCG, agents, build, context hub, golden path, sandbox, assessment, research, settings
  • 130+ core lib modules powering CCG, CIE, Atlas, governance, App Connect, feedback, sandbox, retrieval, research, OpenClaw, Mark
  • 42 Mark AI modules · 58 Inngest handler modules · 25 MCP tools / 4 resources / 3 prompts
  • 6 industries (50+ sub-industries, 30 use cases, 80+ demo scenarios) · 20+ connector providers
  • 3-signal hybrid retrieval · full audit trail on every state-changing operation

17. Getting Started

Commands

npm run dev           # Dev server (clears .next, port 3000)
npm run dev:quick     # Dev server without clearing .next
npm run build         # Full build: compile corpus → prisma generate → next build
npm run lint          # ESLint (flat config v9)
npm run test          # Vitest run
npm run test:coverage # Vitest + v8 coverage
npm run seed          # Seed DB (npx tsx prisma/seed.ts)
npx prisma db push    # Sync schema (no migrations directory)
npx prisma generate   # Regenerate Prisma client
npx tsc --noEmit      # Type check

Setup

git clone <repo-url> && cd ContextCore
npm install
cp .env.example .env        # local: DATABASE_URL="file:./dev.db" works with zero config
npx prisma generate && npx prisma db push && npm run seed
npm run dev                 # → http://localhost:3000

Key env vars (PostgreSQL prod): DATABASE_URL (pgbouncer:6543) + DIRECT_URL (5432), AUTH_SECRET, ANTHROPIC_API_KEY, OPENAI_API_KEY, NEXT_PUBLIC_SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY, INNGEST_EVENT_KEY + INNGEST_SIGNING_KEY, KV_REST_API_URL + KV_REST_API_TOKEN, STRIPE_SECRET_KEY + STRIPE_WEBHOOK_SECRET, BYOK_ENCRYPTION_KEY (32-byte hex), CRON_SECRET, RESEARCH_ENGINE_URL + RESEARCH_API_SECRET, SENTRY_DSN.

Demo account: demo@markmedown.io / demo1234


18. The Playbook — Research + README → Claude Code Spec

This section is the headline deliverable. It documents how to apply this README. The README itself is not a spec — it is the durable platform knowledge that, combined with scoped research, produces a deployable Claude Code feature spec. The spec is the output, not part of this file.

The equation

Platform Context (this README)  +  Scoped Research  →  Conforming, Verifiable Spec
        (what exists, the                (the volatile,           (the deployable
     vocabulary, the conventions,       feature-specific           instruction set
       where things live)               external knowledge)      Claude Code executes)
  • README = durable knowledge. What the platform already has (CCG, contracts, CIE, retrieval, the route/data map), the domain vocabulary, and the conventions a change must obey. Changes slowly. Reuse before you build.
  • Research = volatile knowledge. The per-task knowledge you gather: the external standard, the competitor pattern, the compliance requirement, the API you're integrating, the user problem. Changes every task.
  • Spec = the executable bridge. A structured instruction set that maps research onto platform primitives and conforms to the conventions — so Claude Code can build it and verify it.

When to use it

New feature · new connector/integration · new industry pack · new agent capability · new API surface · new lifecycle engine · any change touching the CCG, contracts, or the gate pipeline.

Step 1 — Prime the context

Paste this README (or the relevant sections) into chat first. At minimum the model needs: Core Vocabulary (§2), the Platform Map (§13), and Repository Conventions (§15). This gives the session the domain language, the "where does it live" map, and the rules — before it sees the task.

Step 2 — Gather and reconcile research

Collect the external knowledge (use the project's /deep-research skill, vendor docs, standards, competitor teardowns). Then reconcile it against what already exists — this is the step that prevents rebuilding what the platform has:

  • Which CCG layers/domains does this feature read or write? (§5)
  • Which contract fields / autonomy tier / gates does it touch? (§6)
  • Which existing lib modules already do part of this? (§2, §13, §15 — e.g. retrieval, contracts, cache, events)
  • Which routes / API families / Prisma models are affected? (§13)

Output of this step: a short "maps-onto" list pairing each research finding with the platform primitive it lands on.

Step 3 — Emit the spec using the Spec Anatomy

Have the model produce a spec with these slots. Each slot is constrained by a README section — keeping the output conforming and reuse-first.

SlotWhat goes hereConstrained by
Context / whyThe problem, what prompted it, intended outcome§4
OutcomeObservable definition of done
Affected surfaceExact routes, API endpoints, Prisma models, lib modules§13
Reuse-first inventoryExisting utils to call: withAuth, parseBody, withCache, emit, CCG/contract/retrieval helpers§15
Data-model changesPrisma model/field additions + npx prisma db push note; orgId on new tenant data§14, §15
Implementation stepsOrdered, each naming the file(s) and the pattern reused§15
Governance / security touchpointsorgId scoping; autonomy-tier or contract impact; which gates (G1–G10) apply; sensitivity classification§6, §15
Test planColocated .test.ts for lib; E2E test + data-testid; Page Object Model§15
Verification commandsnpm run test + npx tsc --noEmit + npm run lint (+ npm run e2e:smoke if routes added)§15
Out of scopeExplicit non-goals to bound the change

Step 4 — Hand to Claude Code

Drop the prompt below into Claude Code. It operationalizes via the project's planner agent and skills (/api-route, /inngest-handler, /tdd, /gen-test, /verify-task).

Using the platform context in README.md (esp. Core Vocabulary, Platform Map, and
Repository Conventions) and the research below, produce an implementation spec
following the README "Spec Anatomy".

Hard requirements:
- Reuse existing patterns/utilities — do not rebuild CCG, contracts, CIE, retrieval,
  caching, or auth. Cite the file path of each util you'll call.
- Conform to .claude/rules (withAuth + orgId scoping, parseBody + zod/v4,
  apiError, colocated tests, max ~50 lines/function).
- Name every file you'll create or modify, mapped to the Platform Map.
- End with the verification gate: npm run test + npx tsc --noEmit + npm run lint.
- For 3+ step work, enter plan mode and use the planner agent first.

RESEARCH:
<paste your reconciled research + the "maps-onto" list from Step 2>

Worked skeleton (template — not a real feature)

# Spec: <feature name>
Context:        <why now — the problem from §4 framing>
Outcome:        <done when ... observable>
Affected surface:
  routes:  /context/<x>  ·  api:  v1/<family>/<x>  ·  models: <Prisma model>  ·  lib: src/lib/<x>.ts
Reuse-first:    withAuth, parseBody(zod/v4), withCache(CacheKeys.<x>), emit(<event>)  [cite paths]
Data model:     + model <X> { orgId ... }  → npx prisma db push
Steps:
  1. <file> — <pattern reused>
  2. <file> — <pattern reused>
Governance:     orgId-scoped; contract impact <none|tier/gate>; gates G<n>; classification <internal>
Tests:          src/lib/<x>.test.ts (Vitest, mock prisma) ; e2e/tests/<x>.spec.ts (POM + data-testid)
Verify:         npm run test && npx tsc --noEmit && npm run lint
Out of scope:   <non-goals>

The discipline is always the same: prime with the README, scope with research, emit against the anatomy, verify with the gate.


19. License

All rights reserved.