MarkMeDown — ContextCore
Context Drives Outcomes with AI.
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
- TL;DR — What This Is
- Core Vocabulary
- The Mental Model — Context · Contracts · Confidence
- The Problem
- The Company Context Graph (CCG)
- Agent Governance
- The Unified Agent Builder (
/build) - Mark — AI Ops Guide
- Context Lifecycle Systems
- OpenClaw Ecosystem
- Developer Platform
- Pricing
- Platform Map
- Architecture & Tech Stack
- Repository Conventions
- Production Status & Metrics
- Getting Started
- The Playbook — Research + README → Claude Code Spec
- License
1. TL;DR — What This Is
MarkMeDown (codebase: ContextCore) is a multi-tenant SaaS platform that does three things, in order:
- 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).
- 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.
- 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
/buildflow with Journey (no-code) and Architect (governance) modes over a sharedAgentSpecV3, 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.
| Term | Definition | Source |
|---|---|---|
| CCG | Company Context Graph — the 9-layer graph of everything the business knows | src/lib/ccg-context.ts |
| CCGML | The file format for a CCG node — Markdown + structured frontmatter (authority, temporal, classification, security) | src/lib/ccg-schema.ts |
| Layer | One of 9 semantic buckets: L1_IDENTITY … L9_RELATIONSHIPS | src/lib/ccg-schema.ts |
| Domain | A hierarchical topic path within layers (e.g. operations/dispatch); has a maturity score L0–L5 | src/lib/ccg-domain-maturity.ts |
| Relationship | A typed edge between nodes — constrains, requires, supersedes, owned_by, requires_approval_from, … (16 types) | src/lib/ccg-schema.ts |
| Decay profile | Freshness model: volatile_7d, standard_90d, stable_365d, immutable, custom | src/lib/ccg-decay.ts |
| Confidence (4D) | Declared + observed confidence, drift velocity, drift direction per node | src/lib/ccg-learning.ts |
| Intent assembly | Query-intent-driven, token-budgeted context retrieval across layers/domains | src/lib/ccg-intent-patterns.ts |
| Hybrid retrieval | pgvector semantic + tsvector fulltext + RRF fusion + graph-informed reranking | src/lib/retrieval/ |
| AgentContract | The governance object bounding one agent: capabilities, access, constraints, prohibitions, escalation, kill switch, rate limits, lifecycle | src/lib/contracts/, prisma/schema.prisma |
| Autonomy tier | Trust level 1 (Autonomous) → 4 (Info-Only) | src/lib/ccg-authority.ts |
| CIE | Context Integrity Engine — evaluates graph health and runs the 10-gate action pipeline | src/lib/cie-gates.ts |
| Gate (G1–G10) | One of 10 pre-execution checks every agent action passes | src/lib/cie-gates.ts |
| CCS | Context Confidence Score — weighted graph-quality score (completeness, consistency, recency, specificity) | src/inngest/cie-compute-ccs |
| AgentSpecV3 | The single canonical builder state; intent (Journey) + contract overrides (Architect) | src/lib/agent-spec/types.ts |
| Claw / OpenClaw / NemoClaw | Governed workspace-file delivery; OpenClaw = workspace generator, NemoClaw = YAML policy runtime | src/lib/openclaw/, src/lib/claw/ |
| Mark | The in-app AI ops guide | src/lib/mark/ |
| Atlas | Translation pipeline + trust framework (doc → CCGML; multi-language; provenance) | src/lib/atlas/ |
| Golden Path | Industry-specific guided journey from zero to AI-ready | src/lib/golden-path.ts |
| HITL | Human-in-the-Loop — the unified review/approval queue | /hitl, src/lib/contracts/ |
| BYOK | Bring Your Own Key — customer-supplied LLM credentials, AES-256-GCM encrypted | src/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.
| Challenge | What Happens |
|---|---|
| Knowledge lives in people's heads | When key staff leave, critical context walks out the door |
| Documents are unstructured chaos | PDFs, wikis, Slack threads — none of it is machine-readable |
| AI hallucinates without context | Agents make confident decisions based on nothing |
| No governance for autonomous agents | No contracts, no boundaries, no audit trail, no kill switch |
| Option | Cost | Timeline | Outcome |
|---|---|---|---|
| Hire consultants | $200K–$2M+ | 6–18 months | Report sits on a shelf |
| Build in-house | $500K–$3M+/yr | 12–24+ months | Custom but fragile |
| Buy generic AI tools | $50K–$300K/yr | Months | Discover it doesn't work |
| MarkMeDown | Starts free | Hours | Context 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_requirestemporal— effective date, review-due date, seasonal variants, business-hours-only, timezoneclassification—taxonomy·policy·procedure·decision_framework·entity_model·constraint·narrative·historysecurity_classification—public·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 profiles —
volatile_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
| Component | What it controls |
|---|---|
| Access control | Read/write per CCG layer, path patterns, exclusions |
| Capabilities | Allowed actions per domain, with conditions |
| Hard constraints | Unbreakable rules — never violated regardless of context |
| Soft constraints | Warnings that flag risky actions without blocking |
| Prohibitions | Explicit forbidden actions |
| Escalation rules | Target role, channel, timeout, fallback behavior |
| Kill switch | Instant contract revocation — agent stops immediately |
| Rate limits | Actions/hour, decisions/day, CCG writes/run |
| Audit level | Full decision trail with reasoning, confidence, authority source |
| Lifecycle | Effective / expiration / review dates, version history |
4 Autonomy Tiers — trust is earned
| Tier | Mode | Scope |
|---|---|---|
| Tier 1 | Autonomous | Acts independently within contract boundaries, full audit |
| Tier 2 | Supervised / Guided | Acts within domains, human notified after |
| Tier 3 | Approval Required / Reporting | Proposes; human approves before execution |
| Tier 4 | Info-Only | Read-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.
| Gate | Purpose | |
|---|---|---|
| G1 | Identity | Verify agent/user identity and org membership |
| G2 | Contract | Validate active contract and appropriate autonomy tier |
| G3 | Kill Switch | Immediate deny if kill switch active |
| G4 | CCG Rules | Validate against CCG governance rules and boundary constraints |
| G5 | Behavioral Governance | Enforce hard/soft constraints and prohibitions |
| G6 | Confidence | Context confidence must meet threshold for this action type |
| G7 | Compliance | Industry framework verification (HIPAA, SOC 2, FINRA, GDPR, PCI-DSS, …) |
| G8 | Temporal / Resource | Operating-hours and resource-budget checks |
| G9 | Rate / Cost | Rate-limit and cost-budget enforcement |
| G10 | Approval | Determine 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.opentohistory.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 viaprevAnchorHash);GET /api/cie/integrity/proofreturns entry, signature, lineage and the Merkle inclusion path with public keys — everything needed to re-verify offline. - Dual-control rulings — contested facts resolve via
IntegrityRulingrequiring a proposer + second approver (both Ed25519-signed); UI at/integrity/rulingswith break-glass override. - Blast-radius simulation —
src/lib/integrity/blast-radius.tsreports affected files/contracts/assertions before a ruling lands; captured inIntegrityRuling.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. - Flags —
INTEGRITY_FEATURESenv + per-orgOrgSettings.integrityFlags(resolver:src/lib/integrity/flags.ts). Ledger + rulings shipped; the mediate cascade (automatic conflict adjudication with off/shadow/enforce modes) is in flight onfeat/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.contractoverrides. The effective contract is always re-derived fromintentviaprojectToContract(projection.ts), then overrides are layered on top.overriddenFieldsrecords 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) composescomputeAllDomainMaturities+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.tsxvia/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.)
| Capability | Details |
|---|---|
| Role personas | Owner/Admin (strategic), Builder (technical), Contributor (domain), Viewer, Guest |
| Channels | Sidebar, Fullpage, Voice, Tooltip, Docs |
| View modes | Collapsed pill, Compact, Expanded, Fullscreen |
| Voice I/O | Push-to-talk + continuous listening via ElevenLabs (TTS + STT) |
| Model routing | Opus (compliance/governance), Sonnet (general), Haiku (nudges) |
| Confirmation protocol | 4 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.
| System | What it does | Source |
|---|---|---|
| Atlas Translation Pipeline | 6 stages — Ingest → Classify → Extract → Reconcile → Generate → Validate — turns PDFs/DOCX into CCGML | src/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 Ledger | Realized + estimated value per agent, in dollars, attributed to the CCG files that produced it; surfaced at /manage/value and /api/v1/insights/value | src/lib/ai-ledger.ts, src/lib/value/auto-emit.ts |
| Activation Pipeline | Free-tier signup → gap map → first look over the customer's own files → estimated value emitted; Inngest-checkpointed (assess → firstLook → value) | src/inngest/activation-quickstart.ts, src/lib/activation/ |
| Research Engine | Deep research via Python microservice (FastAPI + GPT-Researcher); gap analysis, context-fill, credits (1/5/5/10 RC by type) | src/lib/research/ |
| App Connect | OAuth connections → schema discovery → logic-unit extraction → drift & conflict detection; 20+ providers | src/lib/connect/, src/lib/connectors/ |
| Feedback Bridge | Closed loop — rate outcome → trace to CCG files → auto-refine → unified review queue → CCG updated | src/lib/feedback-bridge.ts |
| Context Assessment Engine | Free 6-step readiness wizard; NorthStar graph (50+ verticals); dual CCG scoring vs industry median | src/lib/assessment/ |
| Golden Path | Industry guided journeys — 30 use cases across 6 industries with seed templates + readiness scoring | src/lib/golden-path.ts, industry-use-cases.ts |
| Agent Sandbox | Isolated 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.
| Channel | Description |
|---|---|
| REST API | OpenAPI 3.1; v1 (public) + v2 (agent runtime); granular scope auth; key rotation with grace periods |
| MCP Server | Per-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 |
| Webhooks | HMAC-SHA256 signed; 21 event types; exponential retry + dead-letter queue; field filtering |
| OpenClaw | Workspace 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 CCG —
assemble_context,check_boundary,get_authority,search_context,get_confidence,list_layers,get_governance - CCG architecture —
ccg_resolve,ccg_traverse,ccg_list_domains,ccg_freshness,ccg_intent_patterns - Governance / Claw —
contract_check,product_catalog,escalation_check,context_refresh,policy_lookup,contract_status,contract_delegate,contract_report_violation - Workspace & deployment —
generate_workspace,generate_policy,agent_provision,agent_status,search_answers
Auth, keys, BYOK
- Scopes —
ccg: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.
| Free | Starter | Growth | Pro | Enterprise | |
|---|---|---|---|---|---|
| Price | $0 | $49/mo | $149/mo | $399/mo | $799/mo |
| BYOK | — | $39 | $119 | $319 | $639 |
| Target | Explore | Solo | 5–25 | 25–100 | 100+ |
| CCG Files | 5 | 15 | 50 | 200 | Unlimited |
| AI Agents | 1 | 2 | 5 | 10 | Unlimited |
| AI Credits/mo | 500K | 2M | 5M | 10M | 20M |
| Connectors | — | 1 | 3 | 5 | Unlimited |
| MCP Connections | — | 1 | 2 | 3 | 10 |
| 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
- Build & agents —
(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, exportv1/agents/*,v1/build/[specId]/deploy,v1/launch/*— the five session-authed builder endpoints that survived the/launchretirement (suggest, preview, context-preview, assess-readiness, test-gates);v1/launch/{deploy,build-deploy}are deliberate 410 tombstones pointing at the governedv1/build/[specId]/deploy, not usable endpointsv1/journey/*— builder session CRUD, compile, writeback, ask-mark, audit, templates (list)v1/manage/contracts/*,v1/manage/approvals— contract lifecycle + HITLv1/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 valuev1/connect/*,v1/connectors/*— app connections, sync jobs, logic units, daemonv1/research/*,v1/convert/*,v1/sandbox/*,v1/claw/*,v1/openclaw/*v1/partner,v1/translation,v1/developer,v1/goals,v1/use-cases,v1/insightsv2/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 / Auth —
User,Organization,OrgMembership,ApiKey,ByokCredential,Webhook,PartnerOrg - CCG —
CcgFile,CcgRelationship,CcgSource,CcgBlueprint,DecayProfile,DomainRegistry,IntentPattern - Agents / Contracts —
Agent,AgentContract,AgentContractVersion,AgentContractExecution,AgentContractViolation,ContractDriftSnapshot,AgentDecision,AgentHeartbeat,AgentWorkflow,AgentHandoff,EscalationRequest - CIE —
CieAnalysisRun,Assertion,Contradiction,Gap,UpgNode,UpgEdge,CcsSnapshot - Integrity ledger —
LedgerEntry,LedgerActor,LedgerKey,LedgerAnchor,LedgerVerification,IntegrityRuling,RulingApproval - Connect —
Connector,ConnectorSyncJob,ConnectorLogicUnit,EnrichmentSuggestion,IntelligenceSource - Research —
ResearchRun,ResearchEnrichment,ResearchCredit,ResearchCache - Billing —
Subscription,BillingEvent,AiCreditBalance,AiActionLedger - Mark —
MarkConversation,MarkSessionState,MarkEngagementLog,MarkUserPattern,MarkExperiment,MarkSupportCase - Governance / Audit —
ChangeRequest,AuditLog,ConfidenceHistory,DriftMetric,DivergencePattern,SlaMetric - Goals / Use cases —
Goal,GoalObjective,OrgUseCase,IndustryTemplate - Builder / Ops —
JourneySession,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
| Category | Technology |
|---|---|
| Framework | Next.js 16, React 19, TypeScript 5, Tailwind CSS 4 |
| Database | Prisma 7 — dual adapter: PostgreSQL (Supabase, pgbouncer) / SQLite (local) |
| Auth | NextAuth v5 — Credentials, Google, GitHub |
| AI | Anthropic Claude SDK (translation, classification, Mark, agent config); OpenAI embeddings |
| Search | pgvector (1536d) + tsvector + RRF + graph rerank |
| Research | GPT-Researcher (FastAPI microservice) |
| Voice | ElevenLabs (TTS eleven_turbo_v2_5 + STT scribe_v1) |
| MCP | @modelcontextprotocol/sdk — 25 tools, 4 resources, 3 prompts |
| Async | Inngest — durable workflows, webhook delivery, embeddings, research, scheduled jobs |
| Caching | Vercel KV (Redis) |
| Billing | Stripe |
| Validation | Zod 4 (zod/v4 import path) |
| State | TanStack Query v5 |
| Monorepo | npm workspaces — @markmedown/sdk, @markmedown/cli |
- Dual Prisma adapter —
DATABASE_URLscheme 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)orwithAdminAuth(handler)fromsrc/lib/api-utils.ts. Never roll custom auth. - Every Prisma query scopes by
orgId— this is multi-tenant. Child models lacking their ownorgIdscope through the relation (e.g.AgentContractVersionviacontract: { orgId }). - Validate request bodies with
parseBody(req, schema)usingzod/v4. Return safe errors viaapiError(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,CacheTTL—src/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()inccg-eventsis async (writes to DB) — callers mustawait.- Prefer UI primitives in
src/components/ui/and the semantic design tokens inglobals.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.
| Slot | What goes here | Constrained by |
|---|---|---|
| Context / why | The problem, what prompted it, intended outcome | §4 |
| Outcome | Observable definition of done | — |
| Affected surface | Exact routes, API endpoints, Prisma models, lib modules | §13 |
| Reuse-first inventory | Existing utils to call: withAuth, parseBody, withCache, emit, CCG/contract/retrieval helpers | §15 |
| Data-model changes | Prisma model/field additions + npx prisma db push note; orgId on new tenant data | §14, §15 |
| Implementation steps | Ordered, each naming the file(s) and the pattern reused | §15 |
| Governance / security touchpoints | orgId scoping; autonomy-tier or contract impact; which gates (G1–G10) apply; sensitivity classification | §6, §15 |
| Test plan | Colocated .test.ts for lib; E2E test + data-testid; Page Object Model | §15 |
| Verification commands | npm run test + npx tsc --noEmit + npm run lint (+ npm run e2e:smoke if routes added) | §15 |
| Out of scope | Explicit 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.