Capsulang Reference Specification
v0.7 · Editor's Draft

Capsulang

A language and runtime for AI-authored, human-verifiable systems.

A capsule is a self-contained unit of executable intent: typed, effect-declared, replayable, and checkable. Capsulang lets humans and AI systems co-author capsules, while a deterministic parser, checker, interpreter, and ledger decide what is valid. The Capsule contract compiler now turns governance contracts into checked Authority IR, executable capsule workflows, EDL enclosure contracts, container runtime bundles, Seatbelt profiles, doorkeeper policies, telemetry, receipts, attestation evidence, and negative bypass tests. The runtime is also protocol-native: MCP, A2A, and A2UI are declared, checked, emitted, and audited as typed effects.

authoring
AI-proposed deltas
authority
mandates & capabilities
enclosure
Docker / Seatbelt / gates
protocols
MCP / A2A / A2UI native
UI target
React from A2UI surfaces
compiler
contract to runtime bundle
runtime
replayable, ledgered
New in the reference build: Capsule contracts compile through EDL into checked Capsulang, containerized runtime enclosure artifacts, mediated host-policy plans, and protocol-native A2UI/MCP/A2A manifests that keep UI actions, agent collaboration, and tool/resource access inside the auditable effect model. The React target turns checked A2UI surfaces into components, TypeScript action/state contracts, protocol manifests, and renderer-ready envelope fixtures.
§ 01

Overview

Capsulang is a small, typed, effect-aware language for describing agentic software systems: pure functions, state machines, typed effect intents, external protocol adapters, stores, surfaces, agents, ports, and contracts. It is designed so AI agents can help author systems without becoming the source of truth.

Trust boundary
  AI model
    └─▶ structured delta
          └─▶ session state
                └─▶ deterministic synthesis
                      └─▶ parser
                            └─▶ type / effect checker
                                  └─▶ interpreter / machine runtime
                                        └─▶ ledger + adapters

  ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
  ↑ outside trust         ↑ trust boundary       ↑ authority
    boundary                                         of record
System module graph
Capsulang module graphThree-column architecture: an authoring session feeds a draft capsule, which is parsed, checked, interpreted, and ledgered by the compiler; the runtime exposes MCP ports, A2A agents, A2UI surfaces, a SurrealDB ledger, and TypeDB semantics.AUTHORING SESSIONDRAFT CAPSULERUNTIMERequirementsAssumptionsHolesModule SuggestionsDraft CapsuleParserType CheckerEffect CheckerInterpreterLedger RuntimeMCP PortsA2A AgentsA2UI SurfacesSurrealDB LedgerTypeDB Semantics

Authoring sessions feed draft capsules; the compiler parses, checks, interprets, and ledgers them; runtimes emit typed effect intents that approved host adapters may execute.

Primary thesis. The model proposes. Capsulang checks, interprets, replays, and records. AI is not the compiler. AI is not the runtime.
The repository now includes a native Swift package at swift/CapsulangSwift. It gives Apple apps a dependency-free CapsulangCore runtime/SDK while the Python implementation remains the canonical authoring and tooling surface.
§ 02

Why Now

LLMs can produce plausible code, but plausible code is not enough. Agentic systems need typed intent, declared effects, executable state, provenance, replay, and compiler-grade rejection.

  • Current codebases are human-first: implicit conventions, prose docs, ad-hoc tests.
  • AI agents need deterministic contracts, schemas, declared effects, executable examples, validation, and replay.
  • Prose-only requirements are too ambiguous for safe autonomous implementation.
  • Existing programming languages execute well but expose authoring intent, effect boundaries, proof obligations, and conformance evidence weakly.
  • Capsulang is the bridge between AI-authored intent and deterministic software artifacts.
§ 03

End-to-End Walkthrough

One coherent example — ClaimReview — from English to ledgered execution.

  1. 01DescribeUser describes the system in chat or voice.
  2. 02DeltaLLM emits a structured AuthoringDelta (requirements, assumptions, holes, modules).
  3. 03SessionAuthoring session accumulates state and resolves holes.
  4. 04SynthesizeDeterministic synthesis emits a .caps source.
  5. 05CheckParser, type checker, and effect checker validate.
  6. 06InterpretMachine runtime steps the system through events.
  7. 07LedgerEvents, transitions, and effect intents are persisted.
  8. 08RenderA2UI surfaces project the state for humans.
ClaimReview state diagram
ClaimReview state machineidle transitions on SubmitClaim to awaiting_review, then on ReviewCompleted to awaiting_human_decision, then on Approve to accepted or on Reject to rejected.SubmitClaimReviewCompletedApproveRejectidleawaiting_reviewawaiting_human_decisionacceptedrejected

idle → awaiting_review → awaiting_human_decision → accepted | rejected.

The same ClaimReview capsule drives the source listing in §05, the runtime trace in §08, and the manifest in §19.

§ 04

Constructs & Implementation Status

Capsulang is a young language. To stay honest, the page distinguishes what is in the authoring model, what the parser accepts, what the checker validates, and what the interpreter executes.

ConstructAuthoringParsedCheckedInterpretedRuntimeCodegen
functionyesyesyesyesyespartial
pure functions execute; effectful functions are checked and routed through runtime adapters
machineyesyesyesyesyespartial
event-driven state machines execute; XState/SCXML emit checked topology
storeyesyesyesyesyeshost-artifact
operational/semantic stores; backend, persistence, effect targets, architecture plans, and host contracts are checked/exported
surfaceyesyesyesyesyesreact-target
A2UI-facing declaration; protocol version, catalog, state, actions, route, bound events, manifest, envelopes, and React/A2UI renderer output are checked/exported
portyesyesyesyesyesprotocol-plan
MCP/HTTP-facing declaration; protocol version, tools, resources, prompts, effect targets, protocol-plan output, and adapter plan are checked/exported
agentyesyesyesyesyesprotocol-plan
A2A/HTTP-facing declaration; protocol version, discovery, auth, typed skills, message/task/artifact targets, protocol-plan output, and adapter plan are checked/exported
contractyesyesyesn/an/ahost-artifact
contract declaration; store/function references, architecture plans, and host contracts are checked/exported
lineageyesyesyesn/aledger-readyn/a
declares parent/candidate semantic hashes, proposer, reason, and timestamp for governed successor comparison
objectiveyesyesyesn/aledger-readyn/a
declares improvement metrics, optimization direction, and constraints that bound what better means
eval-suiteyesyesyesn/aledger-readyn/a
declares datasets, metric thresholds, and examples/replay/property checks required before promotion
successor-contractyesyesyesn/aledger-readyn/a
declares preservation, prohibition, and required evidence rules across candidate successors
budgetyesyesyesn/aruntime-policyn/a
declares iteration, cost, wall-clock, CI, LLM, and effect allow/deny limits for improvement loops
gateyesyesyesn/aruntime-policyn/a
declares requirements and pass/fail actions for promotion, quarantine, rollback, and human approval
deployment-policyyesyesyesn/aruntime-policyn/a
declares shadow/canary/live modes, promotion gates, rollback targets, and quarantine triggers
improvement-recordyesyesyesn/aledger-readyn/a
records parent/candidate/diff hashes, eval/proof/policy decisions, approvals, outcomes, and rollback pointer
verification-hookyesyesyesn/aproof-policyn/a
declares improvement proof obligations for Lean, policy engines, or external verifiers
importyesyesyesn/an/an/a
module imports resolve from explicit roots, reject cycles, and record imported semantic hashes
typeyesyesyesyesyespartial
nominal records, enums, tagged variants, errors, events; primitive scalar subset is codegen-ready
profileyesyesyesn/an/an/a
constrains admissible effects
capsuleyesyesyesn/an/an/a
module header + version
principalyesyesyesn/aruntime-policyauthority-ir
Authority IR actor; identity, credential, attestation, owner, and accountability metadata are checked and exported
mandateyesyesyesn/aruntime-policyauthority-ir
bounded reason for action; issuer/recipient references, purpose, scope, revocation, and validity windows are checked/exported
delegationyesyesyesn/aruntime-policyauthority-ir
scoped handoff of authority; source, target, mandate, usable tools, expiry, and traceability requirements are checked/exported
capabilityyesyesyesn/aruntime-policyauthority-ir
short-lived action right; principal, effect target, mandate/delegation dependencies, risk, approvals, limits, and revocation metadata are checked/exported
authority-policyyesyesyesn/aruntime-policyauthority-ir
allow/deny/defer/escalate decision surface; outcomes, default, rule effects, and declared targets are checked/exported
trust-boundaryyesyesyesn/aruntime-policyauthority-ir
execution-environment requirement; sandbox, network, filesystem, egress, secrets, attestation, and capability references are exported to Authority IR
telemetry-obligationyesyesyesn/aledger-readyauthority-ir
contractual telemetry duty; required events, attribution fields, export sinks, and tamper-evidence metadata are checked/exported
memory-policyyesyesyesn/aruntime-policyauthority-ir
agent-memory governance; isolation, TTL, source attribution, hash validation, quarantine, and promotion rules are checked/exported

Source: specs/standard/constructs.json, mirrored to src/spec/constructs.json. The table is data-driven and covered by drift tests.

§ 05

Language Surface

A compact ClaimReview capsule. Identical content is shipped at /spec/claim_review.caps.

(module examples.claim_review
  (capsule "0")
  (profile agentic persistence.surrealdb external.a2a ui.a2ui)

  (store operational
    (backend surrealdb)
    (authority runtime-state))

  (store knowledge
    (backend typedb)
    (authority semantic-facts))

  (agent security_reviewer
    (protocol a2a)
    (skill review_claim))

  (surface claim_review_status
    (title "Claim review status")
    (route "/claims/status")
    (bind ClaimReview)
    (event SubmitClaim))

  (surface claim_review_decision
    (title "Claim review decision")
    (route "/claims/decision")
    (bind ClaimReview)
    (event ReviewCompleted))

  (surface claim_review_summary
    (title "Claim review summary")
    (route "/claims/summary")
    (bind ClaimReview)
    (event Approve Reject))

  (machine ClaimReview
    (version "0.3.0")
    (context
      (claim_id U64)
      (review_score U32)
      (approved Bool))
    (event SubmitClaim
      (claim_id U64))
    (event ReviewCompleted
      (review_score U32))
    (event Approve)
    (event Reject)
    (initial idle)
    (persistence
      (store operational)
      (event-log authoritative)
      (snapshot every-transition)
      (replay true))

    (state idle
      (on SubmitClaim
        (target awaiting_review)
        (assign
          (claim_id event.claim_id)
          (approved false))
        (effects
          (db.write operational.claims)
          (a2a.task security_reviewer.review_claim)
          (a2ui.emit claim_review_status))))

    (state awaiting_review
      (on ReviewCompleted
        (target awaiting_human_decision)
        (assign
          (review_score event.review_score))
        (effects
          (db.write operational.agent_tasks)
          (a2ui.emit claim_review_decision))))

    (state awaiting_human_decision
      (on Approve
        (guard (<= review_score 30))
        (target accepted)
        (assign
          (approved true))
        (effects
          (db.write operational.claims)
          (db.project operational.claims knowledge.typedb)
          (a2ui.emit claim_review_summary)))
      (on Reject
        (target rejected)
        (effects
          (db.write operational.claims)
          (a2ui.emit claim_review_summary))))

    (state accepted (type final))
    (state rejected (type final))))
§ 06

Type & Effect Model

Types

Built-in types include Unit, Bool, I32, I64, U32, U64, Text, Json, Timestamp, Address, Wei, plus parameterized lists, arrays, options, results, maps, vectors, records, tagged variants, and nominal references to declared types.

Effects

Effects are first-class declarations on every function and transition. Profiles constrain which effects are admissible. Pure functions expand to deterministic + no-io + no-state + no-external-call.

EffectDomainDeterminism
db.writeoperational store mutationledgered
db.projectprojection / read model writeledgered
typedb.querysemantic graph readcacheable
typedb.writesemantic graph mutationledgered
mcp.callMCP tool invocationexternal
mcp.read-resourceMCP resource readexternal/cacheable
mcp.subscribe-resourceMCP resource subscriptionexternal/observable
http.callgeneric HTTP port operationexternal
a2a.messageagent-to-agent message dispatchexternal
a2a.taskagent-to-agent task dispatchexternal
a2a.receive-artifactagent-to-agent artifact retrievalexternal
http.taskgeneric HTTP agent taskexternal
a2ui.emitUI event broadcastobservable
a2ui.update-dataA2UI data model updateobservable
a2ui.await-actionA2UI typed user action waitexternal/observable
requires-user-confirmationruntime user confirmation requirementpolicy
requires-authruntime auth scope requirementpolicy
uses-untrusted-external-dataexternal provenance and validation requirementpolicy
llm.callmodel or assistant invocation inside an improvement loopexternal
repo.diffrepository comparison or patch diff generationexternal/ledgered
repo.propose_patchrepository patch proposal without direct deployment authorityexternal/ledgered
repo.apply_patch.sandboxedsandboxed patch application before reviewexternal/ledgered
ci.runcontinuous integration job executionexternal/ledgered
eval.rundeclared eval-suite executionexternal/ledgered
proof.emitproof obligation generationdeterministic-or-ledgered
proof.verifytrusted verifier invocationexternal/ledgered
model.finetunebounded model fine-tuning jobexternal/ledgered
model.evalmodel capability or regression evaluationexternal/ledgered
deploy.shadowshadow deployment candidate activationexternal/ledgered
deploy.canarycanary deployment candidate activationexternal/ledgered
deploy.promotepromotion to primary deploymentexternal/ledgered
deploy.rollbackdeployment rollback to recorded pointerexternal/ledgered
approval.requesthuman or policy approval requestexternal/ledgered
risk.reviewrisk review request or evidence captureexternal/ledgered
Effects make external operation intents visible before execution. A function's effect set is part of its checked signature, not a runtime surprise.
§ 07

Claims Before Facts

External output does not become truth. External output becomes observation. Observation produces claims. Claims can be accepted, rejected, or superseded. Only accepted claims project into semantic stores as facts.

  MCP / A2A result
    └─▶ ExternalObservation
          └─▶ Claim
                └─▶ Human / Policy Review
                      ├─▶ Accepted Fact
                      │     └─▶ TypeDB Projection
                      ├─▶ Rejected
                      └─▶ Superseded by later Claim
  • Tool output is never silently authoritative.
  • Every fact in TypeDB has a traceable claim and acceptance event.
  • Rejected and superseded claims remain in the ledger for audit.
  • A capsule may declare its own acceptance policies (auto, quorum, human).
§ 08

Runtime Model

dry-run

Plans effects without executing. Returns the intended effect graph.

mock

Executes deterministic mock handlers. Suitable for CI and replay tests.

live

Executes configured handlers against real adapters and stores.

The ledger persists, per machine instance:

  • machine instance descriptor and current state,
  • events received (in arrival order),
  • snapshots and transition records,
  • effect intents (planned) and effect results (observed),
  • failed events with diagnostics.
  • semantic trace records for decisions, adapter calls, and proof workflow.

Replay re-executes the recorded event stream against the same module IR and verifies that resulting state and effect identities match the ledgered values byte-for-byte.

§ 09

Protocol-Native Runtime

Capsulang now treats MCP, A2A, and A2UI as first-class protocol contracts. Capsules declare tools, resources, collaborator agents, UI state, and user actions; the checked runtime emits typed effect intents while the host owns policy, credentials, transport, rendering, and audit writes.

Protocol integration is no longer an adapter afterthought. MCP tools/resources, A2A agent skills/tasks/artifacts, and A2UI surfaces/actions are part of the checked language surface, the protocol plan, the release preview, and the replayable runtime evidence trail.
MCP

Typed tool calls, resource reads, and subscriptions through declared ports, with host-owned credentials and provenance.

A2A

Agent cards, discovery, auth, typed skills, messages, tasks, and artifacts for checked collaborator workflows.

A2UI

Declarative surfaces with typed state/actions and deterministic JSON envelopes for renderers and audits.

(surface repo_review_ui
  (protocol a2ui "v0.9")
  (catalog "https://a2ui.org/specification/v0_9/basic_catalog.json")
  (state
    (repo Text)
    (issues Json)
    (approved Bool))
  (action approve_issue_creation
    (input
      (issue_title Text)
      (issue_body Text))
    (requires-user-confirmation true)))
Capsule machine
  -> typed protocol effects
  -> caps protocol-plan
  -> A2UI manifest/envelopes
  -> host policy, adapters, renderer, ledger

New CLI surfaces include caps protocol-plan, caps a2ui-manifest, and caps a2ui-envelope. Protocol effects now include mcp.read-resource, mcp.subscribe-resource, a2a.message, a2a.receive-artifact, a2ui.update-data, and a2ui.await-action.

caps check examples/30_protocol_native_a2ui.caps --json
caps protocol-plan examples/30_protocol_native_a2ui.caps --json
caps a2ui-manifest examples/30_protocol_native_a2ui.caps --json
caps a2ui-envelope examples/30_protocol_native_a2ui.caps repo_review_ui \
  --kind data --data '{"repo":"advatar/Capsulang","approved":false}' --json
§ 10

Semantic Trace

The replay ledger reconstructs state. The semantic trace explains what happened: runtime decisions, adapter calls, diagnostics, proof obligations, and recent breadcrumbs. It is a transport-neutral evidence stream for humans and AI debugging agents.

Trace shape
  human message
    + semantic event
    + trace context
    + diagnostic context

  trace_id · span_id · event · component · operation · service
  reason · expected · actual · error_code · duration_ms
  capsule_hash · machine_instance_id · effect_intent_id
  trace_history[] for error-level events
Runtime events
  • machine.transition.start / end / fail
  • snapshot
  • effect.intent / approved / executed / failed
  • adapter.call.start / end / fail
Verification events
  • proof.obligation.created
  • proof.obligation.discharged
  • proof.obligation.failed
  • invariant.fail, precondition.fail, postcondition.fail

Trace is diagnostic evidence, not an execution-control layer. Capsules still run as checked Capsule Core, emit typed effect intents, and rely on host adapters for external operations. Trace records make that path inspectable and replayable.

§ 11

AI Authoring & Threats

Capsulang supports AI-assisted authoring, but the AI is outside the trust boundary. The deterministic compiler remains the authority of record.

Authoring pipeline
  user message / voice
    └─▶ OpenAI structured AuthoringDelta
          ├─ requirements
          ├─ assumptions
          ├─ open holes
          └─ proposed modules
            └─▶ deterministic .caps synthesis
                  └─▶ parser / checker / interpreter
                        └─▶ diagnostics + repair loop

Threats considered

Threats
  • Prompt injection from external tools
  • A2A agent returning malicious instructions
  • A2UI action spoofing
  • Undeclared writes
  • Untrusted claims becoming facts
  • External operations without user approval
  • Non-replayable state transitions
Defenses
  • Structured authoring deltas
  • Type and effect checking
  • Host-policy adapter checks
  • Claims-before-facts persistence
  • Machine event validation
  • Ledger replay
  • Semantic IR hashes
§ 12

Improvement Governance

Capsulang now models governed recursive improvement as a checked workflow rather than an unchecked self-modification privilege. A candidate successor must declare lineage, objective metrics, regression evals, successor contracts, budgets, gates, deployment policy, approvals, proof hooks, and rollback evidence before a host can promote it.

Governance declarations
  • lineage: parent/candidate semantic hashes.
  • objective: metrics, maximize/minimize directions, constraints.
  • eval-suite: datasets, thresholds, examples, replay, proof checks.
  • successor-contract: cross-version preservation and authority rules.
  • budget: iteration, call, CI, cost, wall-clock, and effect limits.
  • gate and deployment-policy: approval, canary, quarantine, and rollback.
  • improvement-record: ledger-ready evidence for a candidate.
Typed improvement effects

Effects such as llm.call, repo.propose_patch, ci.run, eval.run, proof.verify, deploy.canary, deploy.promote,deploy.rollback, approval.request, and risk.review are declared intents. Runtime policy and host adapters decide whether they execute.

CPS-8 Improvement-Governed conformance means the parser, checker, canonical IR, and ledger evidence path understand these declarations. It does not mean a capsule gets ambient deployment authority.

(module ImprovementGovernanceDemo
  (capsule "0.7")

  (contract NoUnauthorizedEffects
    (summary "Successors must not acquire undeclared live authority."))

  (lineage CandidateLineage
    (parent "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    (candidate "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
    (reason "Improve claim triage while preserving authority boundaries.")
    (proposed-by agent:ReviewImprover)
    (created-at "2026-05-16T00:00:00Z"))

  (objective BetterTriage
    (summary "Improve claim triage quality without expanding live authority.")
    (metric f1_score "evals/claim_triage_gold.jsonl")
    (metric latency_ms)
    (maximize f1_score)
    (constraint latency_ms <= 500)
    (constraint live_effects_added == 0))

  (eval-suite ClaimReviewRegression
    (summary "Regression suite for candidate claim-review successors.")
    (dataset "evals/claim_review_regression.jsonl")
    (metric exact_match >= 98)
    (metric unsafe_action_rate == 0)
    (must-pass examples)
    (must-pass replay "ledgers/golden/*.jsonl"))

  (verification-hook ImprovementSafety
    (summary "Safety obligations generated for the recursive improvement gate.")
    (target lean4)
    (status open)
    (subject successor-contract:SafeSuccessor)
    (subject gate:DeployCandidate)
    (obligation deploy_requires_eval_pass)
    (obligation deploy_requires_approval)
    (obligation effect_expansion_requires_security_approval))

  (successor-contract SafeSuccessor
    (summary "Successor candidates must preserve authority and evaluation invariants.")
    (preserve contract:NoUnauthorizedEffects)
    (forbid effect-expansion unless approval:SecurityOwner)
    (require eval-suite:ClaimReviewRegression)
    (require verification-status checked)
    (require ledgered true))

  (budget ImprovementBudget
    (summary "Bound the autonomous iteration envelope for candidate generation.")
    (max-iterations 3)
    (max-llm-calls 50)
    (max-ci-runs 10)
    (max-wall-clock-ms 3600000)
    (max-cost-usd 25)
    (allow-effects llm.call repo.diff repo.propose_patch repo.apply_patch.sandboxed ci.run eval.run proof.emit proof.verify approval.request risk.review deploy.shadow deploy.canary deploy.promote deploy.rollback)
    (deny-effects deploy.live secret.read model.train.frontier))

  (gate DeployCandidate
    (summary "A candidate can reach deployment only after eval, contract, proof, ledger, and human approval evidence.")
    (requires eval-suite ClaimReviewRegression passed)
    (requires successor-contract SafeSuccessor preserved)
    (requires approval SecurityOwner granted)
    (requires verification-status checked)
    (requires ledgered true)
    (on-fail quarantine)
    (on-pass canary))

  (deployment-policy CandidatePolicy
    (summary "Deploy successors through shadow and canary stages with rollback to the parent hash.")
    (mode shadow-first)
    (canary-percent 5)
    (rollback-to parent)
    (promote-gate DeployCandidate)
    (quarantine-on eval-regression policy-violation unexpected-effect missing-ledger-record))

  (improvement-record CandidateRecord
    (summary "Illustrative ledger record for one candidate successor.")
    (parent-hash "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    (candidate-hash "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
    (diff-hash "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc")
    (objective BetterTriage)
    (eval-result ClaimReviewRegression passed)
    (proof-result ImprovementSafety checked)
    (policy-decision DeployCandidate passed)
    (approval SecurityOwner approved "security@example.test")
    (deployment-outcome shadow ok)
    (rollback-pointer "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))

  (machine ImprovementCycle
    (version "0.1")
    (event ProposeCandidate)
    (event StaticCheckPassed)
    (event EvalPassed)
    (event VerificationPassed)
    (event Approved)
    (event ShadowOk)
    (event CanaryOk)
    (event PolicyViolation)
    (initial drafting)

    (state drafting
      (on ProposeCandidate
        (target static_check)
        (effects
          (repo.propose_patch))))

    (state static_check
      (on StaticCheckPassed
        (target evaluate)
        (effects
          (ci.run))))

    (state evaluate
      (on EvalPassed
        (target verify)
        (effects
          (eval.run ClaimReviewRegression))))

    (state verify
      (on VerificationPassed
        (target human_review)
        (effects
          (proof.verify ImprovementSafety))))

    (state human_review
      (on Approved
        (target shadow_deploy)
        (effects
          (approval.request DeployCandidate))))

    (state shadow_deploy
      (on ShadowOk
        (target canary_deploy)
        (effects
          (deploy.shadow CandidatePolicy)))
      (on PolicyViolation
        (target quarantined)
        (effects
          (deploy.rollback CandidatePolicy))))

    (state canary_deploy
      (on CanaryOk
        (target promoted)
        (effects
          (deploy.canary CandidatePolicy)
          (deploy.promote CandidatePolicy)))
      (on PolicyViolation
        (target quarantined)
        (effects
          (deploy.rollback CandidatePolicy))))

    (state promoted (type final))
    (state quarantined (type final))))

See /spec/improvement-governance.md and /spec/improvement_governance.caps.

§ 13

Capsule Compiler & Runtime Enclosures

The Capsule contract compiler is Capsulang's governance contract path. A .capsule.yaml contract describes identity, effects, policy, telemetry, memory, and runtime boundaries, then lowers through EDL into checked Authority IR plus concrete runtime artifacts for containerized execution, mediated side effects, receipts, reconciliation, and negative bypass tests.

Capsule contract

Identity, mandates, scoped effects, approvals, memory, telemetry, and trust boundaries in one governance file.

EDL lowering

Contracts lower into explicit enclosure requirements before checked Capsulang and host-policy artifacts are emitted.

Container runtime

Docker Compose, Seatbelt, doorkeeper, telemetry, receipts, attestation, and negative tests ship as a reviewable bundle.

Enforcement rule. No attested enclosure, no live effect. No mediated gate, no protected side effect. No receipt, no accepted completion.
Compiler outputs
  • normalized .capsule.json contract IR
  • lowered EDL enclosure contract
  • checked .caps Authority IR and machine workflow
  • Docker Compose runtime enclosure
  • macOS Seatbelt sandbox profile
  • doorkeeper policy for mediated GitHub effects
  • telemetry, receipts, attestation, and negative tests
Rejected by design
  • ambient credentials and host keychain access
  • default-allow network policies in enforce mode
  • protected effects without gate actions
  • high-risk operations without approval-bound receipts
  • missing telemetry for authority decisions
caps capsule-check examples/29_capsule_refund_reviewer.capsule.yaml --json
caps capsule-ir examples/29_capsule_refund_reviewer.capsule.yaml
caps capsule-compile examples/29_capsule_refund_reviewer.capsule.yaml --out-dir build/capsule-refund --json
caps check build/capsule-refund/claims-refund-reviewer.caps --json
Lowering path
Capsule contract YAML
  -> normalized Capsule IR
  -> lowered EDL
  -> normalized Enclosure IR
  -> Capsulang Authority IR and machine workflow
  -> sandbox backend profiles
  -> doorkeeper policy
  -> telemetry and receipt plans
  -> negative bypass tests
  -> attestation artifact digests

Refund reviewer Capsule contract

capsule: 0.1
module: claims.refund_reviewer
version: 1.2.0
purpose: "Review refund requests and issue approved small refunds through mediated gates."

identity:
  id: agent:RefundReviewer
  kind: agent
  cryptographic: required
  credentials: short_lived
  attestation: required
  owner: human:ClaimsLead

inputs:
  - RefundRequest

outputs:
  - RefundDecision

effects:
  - read: CustomerDB.claims
  - call: RefundAPI.issue_refund
    max_amount_usd: 100
    approval_required_above_usd: 50

telemetry:
  required: true
  tamper_evident: true
  export: [otel, siem, ledger]

policy:
  default: deny
  escalation:
    - if: amount_usd > 50
      require: [human_approval]

runtime:
  image: ghcr.io/acme/refund-reviewer@sha256:REPLACE_WITH_DIGEST
  command: [refund-reviewer, run]
  workdir: /workspace
  doorkeeper_endpoint: https://doorkeeper.internal/mcp
  backend_preference: [docker, seatbelt]

memory:
  default: isolated
  stores:
    - id: mem:refund-session
      isolation: per_session
      ttl: 24h
      source_attribution: required
      hash_validation: on_read

Generated checked capsule

(module edl.claims_refund_reviewer
  (capsule "1.2.0")
  (profile agentic external.mcp persistence.ledger telemetry.otel)

  (store EnclosureLedger
    (backend file)
    (authority enclosure-receipts))

  (principal HumanClaimsLead
    (kind human)
    (identity passkey-or-oidc)
    (summary "EDL principal human:ClaimsLead"))

  (principal AgentRefundReviewer
    (kind agent)
    (identity cryptographic)
    (credential short-lived)
    (attestation required)
    (summary "EDL principal agent:RefundReviewer"))

  (mandate MandateClaimsRefundReviewer
    (issued-by HumanClaimsLead)
    (issued-to AgentRefundReviewer)
    (purpose "Review refund requests and issue approved small refunds through mediated gates.")
    (valid-for 30m)
    (revocable true)
  )

  (delegation DelegationClaimsRefundReviewer
    (from HumanClaimsLead)
    (to AgentRefundReviewer)
    (under MandateClaimsRefundReviewer)
    (may-delegate false)
    (expires-after 30m)
  )

  (port GateCapsule
    (protocol mcp)
    (endpoint "https://doorkeeper.internal/mcp")
    (tool db_read_customerdb_claims http_call_refundapi_issue_refund)
    (summary "EDL gate gate:capsule"))

  (gate HumanApprovalGate
    (summary "Human approval required for high-risk enclosed actions.")
    (requires approval HumanClaimsLead granted)
    (on-fail reject)
    (on-pass manual))

  (capability CapDbReadCustomerdbClaims
    (principal AgentRefundReviewer)
    (effect (mcp.call GateCapsule.db_read_customerdb_claims))
    (resource CustomerDB.claims)
    (valid-for 10m)
    (requires-mandate MandateClaimsRefundReviewer)
    (requires-delegation DelegationClaimsRefundReviewer)
  )

  (capability CapHttpCallRefundapiIssueRefund
    (principal AgentRefundReviewer)
    (effect (mcp.call GateCapsule.http_call_refundapi_issue_refund))
    (resource RefundAPI.issue_refund)
    (valid-for 5m)
    (requires-mandate MandateClaimsRefundReviewer)
    (requires-delegation DelegationClaimsRefundReviewer)
    (approval HumanClaimsLead)
    (limit single-use true)
  )

  (trust-boundary EncClaimsRefundReviewer
    (mode enforce)
    (fail-closed true)
    (sandbox required)
    (network deny-by-default)
    (filesystem root-read-only)
    (egress-only GateCapsule)
    (secrets ambient-deny)
    (requires-attestation true)
    (requires-profile-digest true)
    (capability CapDbReadCustomerdbClaims CapHttpCallRefundapiIssueRefund)
    (summary "EDL enclosure enc:claims-refund-reviewer"))

  (telemetry-obligation EnclosureTelemetry
    (must-emit invocation.start invocation.end enclosure.attested policy.evaluated capability.issued effect.intent effect.denied effect.escalated effect.executed receipt.emitted)
    (include trace_id span_id agent_id principal_id mandate_id delegation_id capability_jti contract_hash enclosure_id effect_intent_id policy_id gate_id)
    (export otel siem ledger)
    (tamper-evident true))

  (memory-policy MemRefundSession
    (isolation per-session)
    (ttl default 24h)
    (source-attribution required)
    (hash-validation on-read)
  )

  (authority-policy PolicyCapsule
    (input principal mandate delegation capability effect context risk)
    (outcome allow deny defer escalate)
    (default deny)
    (on allow (if "effect == \"db.read.CustomerDB.claims\""))
    (on escalate (if "effect == \"http.call.RefundAPI.issue_refund\" and (amount_usd > 50)"))
  )

  (machine EnclosedAgent
    (version "1.2.0")
    (context
      (repo Text)
      (branch Text)
      (request_id U64))
    (event ProposeChange
      (repo Text)
      (branch Text)
      (summary Text))
    (event RequestPrivilegedAction
      (repo Text)
      (branch Text)
      (request_id U64))
    (event HumanApproved
      (approval_id Text))
    (event HumanDenied
      (approval_id Text))
    (event Complete)
    (initial ready)
    (persistence
      (store EnclosureLedger)
      (event-log enclosure_events)
      (snapshot enclosure_snapshots)
      (replay true))
    (state ready
      (on ProposeChange
        (target ready)
        (effects
          (policy.evaluate PolicyCapsule)
          (mcp.call GateCapsule.db_read_customerdb_claims)
          (receipt.emit proposal_receipt)))
      (on RequestPrivilegedAction
        (target waiting_for_approval)
        (effects
          (policy.evaluate PolicyCapsule)
          (approval.request HumanApprovalGate)))
      (on Complete
        (target completed)
        (effects
          (receipt.emit enclosure_completed))))
    (state waiting_for_approval
      (on HumanApproved
        (target ready)
        (effects
          (capability.issue CapHttpCallRefundapiIssueRefund)
          (mcp.call GateCapsule.http_call_refundapi_issue_refund)
          (receipt.emit privileged_action_executed)))
      (on HumanDenied
        (target ready)
        (effects
          (receipt.emit privileged_action_denied))))
    (state completed (type final))))

See /spec/capsule-compiler.md, /spec/claims-refund-reviewer.capsule.yaml, and the generated Docker, Seatbelt, doorkeeper, telemetry, receipt, attestation, and negative-test artifacts in §28.

§ 14

Capsulang Compared With

Capsulang sits next to a number of adjacent technologies. It does not replace any of them; it composes them through checked Capsule Core, typed effect intents, and replayable state.

Agent-facing tool surface

Agent-first systems languages such as Zero emphasize small regular syntax, native artifacts, standard-library metadata, structured diagnostics, graph/size/ship/doctor workflows, and deterministic repair loops. Capsulang's center is different: governed agent workflows and capsules. The practical lesson is still useful, so the reference CLI now exposes a compact JSON-first agent surface.

caps agent-graph --json examples/03_claim_review_machine.caps
caps repair-plan --json examples/04_bad_missing_effect.caps
caps doctor --json
caps release-preview --json examples/01_abs_i64.caps

These commands provide inspectable module facts, typed repair options with safety labels, local readiness checks, hashes, verification status, and backend readiness without changing Capsulang into a native systems language.

Compared withDifference
Zero / agent-first systems languagesZero is a native systems language for agents with small regular syntax, standard-library metadata, JSON diagnostics, graph/size/ship/doctor workflows, and native artifact ambitions. Capsulang is a governed capsule runtime: dialog-to-spec authoring, checked state machines, typed effect intents, A2UI/MCP/A2A adapters, semantic trace, replay ledgers, persistence, and proof obligations.
Python / Swift / Rust / TypeScriptCapsulang is not mainly human-authored implementation code; it is typed executable intent.
Lean 4Lean proves; Capsulang orchestrates, checks effects, runs machines, and can emit proof obligations.
XStateXState models statecharts; Capsulang adds typed effect intents, persistence, protocol adapters, and replay.
SoliditySolidity is a deployment target for checked pure contract-safe functions and flat machine transition contracts; Capsulang models, checks, tests, traces, and emits effect-intent events before on-chain handoff.
MCP / A2A / A2UIThese are protocols; Capsulang is the policy and runtime layer around them.
Low-code / no-codeCapsulang is not visual scripting; it is formal, typed, and compiler-checked.
§ 15

Formal Definition & Verification

A Capsulang module is a tuple:

M = (N, C, P, T, R, E, S, A, F, X, K)
SymbolComponent
Nmodule name
Ccapsule version
Pset of profiles
Tnominal type declarations
Rruntime stores
Eevents and errors
Ssurfaces
Aexternal agents and ports
Fchecked functions
Xstate machines
Kcontracts

Checked function

f = (inputs, output, effects, requires, ensures, impl)

A function is valid when:

  • every input and output type resolves,
  • every expression type-checks,
  • every inferred effect is declared,
  • every precondition and postcondition is well-typed,
  • examples evaluate to their expected values.

Machine

machine = (context, events, initial_state, states, transitions, persistence)

A transition is valid when:

  • its event exists,
  • its target state exists,
  • its guard is pure and Boolean,
  • assignments type-check against machine context,
  • effects are declared and profile-compatible.

Verification ladder

Capsulang distinguishes checked from verified. The parser, checker, interpreter, examples, and replay engine provide executable evidence. Formal verification begins when proof obligations are generated and discharged by a trusted target.

LevelNameStatus
V0Parsed canonical IRimplemented
V1Type/effect checkedimplemented
V2Examples and ledger replayimplemented evidence, not proof
V3Proof obligationscaps verify-report, caps emit-lean-obligations
V4Kernel-checked proofcaps verify-lean; no open proof markers permitted
V5Backend refinementcaps refinement-report --require-closed for selected closed evidence
Lean 4 is the first high-assurance proof target. SMT-style solvers are useful for bounded arithmetic/refinement checks, and TLA+/state exploration is useful for finite abstractions of machines. A capsule is not called verified merely because examples pass. Generated Lean stubs are obligations, not proofs; verify-lean only succeeds when the generated/completed file is accepted by Lean and contains no sorry, admit, or axiom markers. The current proof-complete fixtures cover identity, Boolean negation, integer add-zero postconditions, and a simple machine final-state invariant. refinement-report records AST/IR, interpreter, and backend artifact evidence, checks supported Wasm WAT against examples with i64 wrap semantics, checks selected RISC-V assembly opcode patterns, and keeps proof-grade backend behavior claims open until accepted proofs or executable backend semantics exist. --require-closed lets CI fail any selected backend slice that still has open, blocked, failed, or unevidenced refinement claims. The regression suite now includes bounded Hypothesis generators for parse/print/semantic-hash roundtrips, whitespace stability, Unicode text, integer boundaries, and safe signed/unsigned Wasm agreement.

Canonical IR

Capsulang source is parsed into an AST, normalized into canonical JSON, and hashed with SHA-256 to produce a semantic hash. The semantic hash is the stable identity of the checked module — independent of formatting, comments, or declaration order.

§ 16

Private Proofs with Noir

Capsulang now has a restricted zk.noir profile for privacy-preserving proof predicates. The workflow remains Capsulang-governed: machines, policy, effects, trace, replay, and A2UI stay in Capsulang. Noir is used to prove selected private predicates, such as a private deployment risk score being below a public threshold, without revealing the private score or findings.

What Noir proves

A Noir circuit proves that private witness values satisfy a public relation. In Capsulang this is represented by azk-proof declaration and a zk.verifyeffect intent inside a state-machine transition.

(zk-proof DeploymentRiskProof
  (backend noir)
  (public
    (change_id U64)
    (threshold U32)
    (risk_model_hash Bytes32))
  (private
    (risk_score U32)
    (findings_commitment Bytes32))
  (proves (<= risk_score threshold)))
What Noir does not prove
  • It does not prove full Capsulang workflow correctness.
  • It does not prove the circuit is the right policy.
  • It does not replace Lean/SMT for public invariants.
  • It does not grant ambient authority to adapters.
caps zk-plan examples/24_private_deployment_risk_proof.caps --json
caps emit-noir examples/24_private_deployment_risk_proof.caps   --proof DeploymentRiskProof   --out-dir build/DeploymentRiskProof   --json
caps noir-compile build/DeploymentRiskProof --json
caps noir-execute build/DeploymentRiskProof --json

The generated Noir project contains Nargo.toml,Prover.toml, src/main.nr, and a Capsulang manifest binding the proof to the module semantic hash. See /spec/zk-noir.md and /spec/private_deployment_risk_proof.caps.

Privacy boundary: Noir proves private witness membership for a selected predicate. Capsulang still governs the workflow, proof artifact lifecycle, policy decision, effect handling, and semantic trace.
§ 17

AFPS Alignment

Note. AFPS (Agent-First Project Standard) is an adjacent proposed standard, maintained separately. Capsulang implementations that target AFPS should treat it as an evolving target, pin the version they conform against, and avoid assuming ecosystem-wide recognition.

AFPS describes how software projects expose operations, schemas, workflows, validation rules, and conformance evidence so independent AI agents can discover, execute, and verify them without guessing from prose or chat history.

Reference: afps.showntell.dev

A Capsulang implementation aligned with AFPS should:

  • publish an agent manifest at a stable path,
  • expose declared operations with input/output schemas,
  • provide executable examples and negative examples,
  • declare effect metadata for every operation,
  • provide non-interactive validation commands,
  • include conformance reports in CI,
  • generate documentation from, or trace it to, structured source artifacts.
§ 18

Reference Implementation Requirements

The repository has three complementary reference surfaces: Python for canonical authoring, tooling, adapters, and conformance workflows; Swift for Apple-platform runtime and SDK embedding; and Lean 4 for proof artifacts and verification claims.

Python

Canonical CLI, authoring UI, adapter integrations, verification reports, and code generation workflows.

Swift

Native CapsulangCore package for parser, checker, interpreter, semantic hash, machines, ledgers, and effect intents on Apple platforms.

Lean 4

Formal target for proof obligations and proof-complete fixtures. Generated stubs are obligations until accepted by Lean.

The Swift package is a real reference runtime/SDK, not a port of the Python authoring UI, LLM tooling, or web adapters. Its machine runtime returns EffectIntent values so the Apple host app keeps authority over external effects.

A conforming Capsulang implementation MUST include:

MUSTparser for the supported .caps subset
MUSTcanonical JSON IR emitter
MUSTsemantic hash generation
MUSTstatic type checker
MUSTeffect checker
MUSTpure function interpreter
MUSTmachine stepper
MUSTmachine runtime
MUSTarchitecture plan emitter
MUSTdry-run / mock / live modes
MUSTfile-backed ledger
MUSTreplay verifier
MUSTRISC-V RV64 pure-function emitter
MUSTconformance fixtures

A production implementation SHOULD include:

SHOULDSurrealDB or equivalent ledger adapter
SHOULDTypeDB-oriented semantic adapter
SHOULDMCP adapter
SHOULDgeneric HTTP port adapter
SHOULDA2A adapter
SHOULDgeneric HTTP agent adapter
SHOULDA2UI or UI event adapter
SHOULDOpenAI or other LLM authoring bridge
SHOULDschema-constrained authoring deltas
SHOULDCI conformance checks
§ 19

Swift Package

The native Swift package lives at swift/CapsulangSwift. It declares the library target CapsulangCore and the macOS/CI executable caps-swift. Supported platforms are macOS 13+, iOS 16+, tvOS 16+, watchOS 9+, and visionOS 1+.

CLI usage

Use the executable target for conformance checks, local examples, semantic hashes, and simple pure-function calls:

cd swift/CapsulangSwift
swift test

swift run caps-swift parse Examples/01_abs_i64.caps
swift run caps-swift check Examples/01_abs_i64.caps
swift run caps-swift examples Examples/11_text_ops.caps
swift run caps-swift call Examples/01_abs_i64.caps abs_i64 x=-7
swift run caps-swift hash Examples/17_imports.caps

The intentionally invalid example Examples/04_bad_missing_effect.caps should fail with E_EFFECT_NOT_DECLARED.

Embedding in Apple apps

Add swift/CapsulangSwift as a Swift Package Manager dependency and import CapsulangCore. App bundles should ship checked .caps modules and let the host policy decide which returned effects may execute.

import CapsulangCore

let url = Bundle.main.url(
    forResource: "01_abs_i64",
    withExtension: "caps"
)!
let loaded = try ModuleLoader.load(url)
guard let module = loaded.module else {
    fatalError("Capsulang module did not parse")
}

let check = checkModule(module)
guard !check.diagnostics.contains(where: { $0.isError }) else {
    fatalError(check.diagnostics.map { $0.render() }.joined(separator: "\n"))
}

let function = module.functions["abs_i64"]!
let result = Interpreter(module: module).evalFunction(
    function,
    inputs: ["x": .int(BigInt(-7))]
)

Machine effects

Machine execution is intentionally capability-safe. The Swift runtime computes the transition and returns effect intents as data; it does not perform database, network, UI, or agent calls.

let runtime = try MachineRuntime(
    module: module,
    machineName: "SimpleGate"
)

let snapshot = runtime.start()
let transition = runtime.step(
    snapshot,
    event: MachineEvent(name: "Close")
)

// Present transition.effects to host policy and adapters.
§ 20

AFPS Manifest Example

A minimal AFPS manifest for a Capsulang reference implementation. Mirror at /spec/afps_manifest.json.

{
  "schema_version": "0.2",
  "standard": "AFPS",
  "conformance_target": "AFPS-3",
  "project": {
    "id": "capsulang.reference",
    "name": "Capsulang Reference Implementation",
    "version": "0.7.0"
  },
  "validation": {
    "commands": [
      "python -m pytest -q",
      "caps check examples/01_abs_i64.caps",
      "caps architecture-plan examples/03_claim_review_machine.caps",
      "caps emit-riscv examples/01_abs_i64.caps",
      "caps machine-run examples/03_claim_review_machine.caps ClaimReview SubmitClaim --mode dry-run"
    ]
  },
  "operations": [
    {
      "id": "capsulang.check",
      "type": "cli_action",
      "command": "caps check <file>",
      "schemas": {
        "input": "agent/schemas/check-input.schema.json",
        "output": "agent/schemas/check-output.schema.json"
      },
      "examples": [
        "agent/examples/check.valid.json",
        "agent/examples/check.invalid.json"
      ],
      "external_effects": false
    },
    {
      "id": "capsulang.machine-run",
      "type": "cli_action",
      "command": "caps machine-run <file> <machine> <event>",
      "supports_dry_run": true,
      "external_effects": true
    },
    {
      "id": "capsulang.architecture-plan",
      "type": "cli_action",
      "command": "caps architecture-plan <file>",
      "external_effects": false
    },
    {
      "id": "capsulang.emit-riscv",
      "type": "cli_action",
      "command": "caps emit-riscv <file>",
      "external_effects": false
    }
  ]
}
§ 21

Conformance Levels

LevelNameRequirementScope
CPS-0ParsedSource parses into ASTparser
CPS-1CheckedTypes and effects validatechecker
CPS-2InterpretablePure functions and examples executeinterpreter
CPS-3Runtime-CapableMachines step and run in dry-run / mock / live modes with deterministic timeout, retry, failure, and cancellation semanticsruntime
CPS-4LedgeredExecution is persisted and replay-verifiableledger
CPS-5TraceableSemantic trace events include trace/span ids, event kind, component, operation, diagnostics, and bounded breadcrumbstrace
CPS-6Agent-OperableManifest, schemas, examples, and CI evidence existagent
CPS-7VerifiedConfigured proof obligations are accepted by a trusted verifier with no open proof markersverification
CPS-8Improvement-GovernedImprovement lineage, objectives, eval suites, successor contracts, budgets, gates, deployment policies, and improvement records are parsed, checked, canonicalized, and ledger-readyimprovement
CPS-9Authority-GovernedAuthority IR principals, mandates, delegations, capabilities, policies, trust boundaries, telemetry obligations, and memory policies are parsed, checked, canonicalized, and exportable as a host-policy artifactauthority
CPS-10Protocol-NativeMCP tools/resources/prompts, A2A discovery/auth/skills, A2UI surfaces/state/actions, protocol effect targets, protocol-plan export, and A2UI manifest/envelope export are parsed, checked, canonicalized, and runtime-adapter readyprotocols
Conformance is cumulative. A CPS-4 implementation satisfies CPS-0 through CPS-3. CPS-6 is the threshold for autonomous agent operation against the implementation, CPS-7 requires trusted proof acceptance with no open proof markers, and CPS-8 adds improvement-governance declarations for safe successor workflows. CPS-9 adds Authority IR for principals, mandates, delegations, capabilities, policies, trust boundaries, telemetry, and memory controls.

The versioned standard manifest is mirrored at /spec/standard_manifest.json.

{
  "compatibility": {
    "diagnostics": "Diagnostic codes are stable within a minor line unless explicitly deprecated.",
    "ir": "Canonical IR now includes improvement-governance and Authority IR declarations; semantic hash changes require a compatibility note and conformance fixture update.",
    "semantics": "Breaking semantic changes require a new standard version.",
    "syntax": "New syntax must be feature-gated or additive within a minor line."
  },
  "conformance_levels": [
    {
      "id": "CPS-0",
      "name": "Parsed",
      "requirement": "Source parses into AST",
      "scope": "parser"
    },
    {
      "id": "CPS-1",
      "name": "Checked",
      "requirement": "Types and effects validate",
      "scope": "checker"
    },
    {
      "id": "CPS-2",
      "name": "Interpretable",
      "requirement": "Pure functions and examples execute",
      "scope": "interpreter"
    },
    {
      "id": "CPS-3",
      "name": "Runtime-Capable",
      "requirement": "Machines step and run in dry-run / mock / live modes with deterministic timeout, retry, failure, and cancellation semantics",
      "scope": "runtime"
    },
    {
      "id": "CPS-4",
      "name": "Ledgered",
      "requirement": "Execution is persisted and replay-verifiable",
      "scope": "ledger"
    },
    {
      "id": "CPS-5",
      "name": "Traceable",
      "requirement": "Semantic trace events include trace/span ids, event kind, component, operation, diagnostics, and bounded breadcrumbs",
      "scope": "trace"
    },
    {
      "id": "CPS-6",
      "name": "Agent-Operable",
      "requirement": "Manifest, schemas, examples, and CI evidence exist",
      "scope": "agent"
    },
    {
      "id": "CPS-7",
      "name": "Verified",
      "requirement": "Configured proof obligations are accepted by a trusted verifier with no open proof markers",
      "scope": "verification"
    },
    {
      "id": "CPS-8",
      "name": "Improvement-Governed",
      "requirement": "Improvement lineage, objectives, eval suites, successor contracts, budgets, gates, deployment policies, and improvement records are parsed, checked, canonicalized, and ledger-ready",
      "scope": "improvement"
    },
    {
      "id": "CPS-9",
      "name": "Authority-Governed",
      "requirement": "Authority IR principals, mandates, delegations, capabilities, policies, trust boundaries, telemetry obligations, and memory policies are parsed, checked, canonicalized, and exportable as a host-policy artifact",
      "scope": "authority"
    },
    {
      "id": "CPS-10",
      "name": "Protocol-Native",
      "requirement": "MCP tools/resources/prompts, A2A discovery/auth/skills, A2UI surfaces/state/actions, protocol effect targets, protocol-plan export, and A2UI manifest/envelope export are parsed, checked, canonicalized, and runtime-adapter ready",
      "scope": "protocols"
    }
  ],
  "last_revised": "2026-06-12",
  "normative_artifacts": [
    {
      "description": "Normative language and implementation standard for Capsulang v0.7.",
      "id": "standard",
      "media_type": "text/markdown",
      "path": "specs/standard/capsulang-v0.7-standard.md"
    },
    {
      "description": "Construct implementation status by authoring, parser, checker, interpreter, runtime, and codegen support.",
      "id": "constructs",
      "media_type": "application/json",
      "path": "specs/standard/constructs.json"
    },
    {
      "description": "Known effect domains and determinism classifications.",
      "id": "effects",
      "media_type": "application/json",
      "path": "specs/standard/effects.json"
    },
    {
      "description": "Cumulative Capsulang conformance levels.",
      "id": "conformance",
      "media_type": "application/json",
      "path": "specs/standard/conformance.json"
    },
    {
      "description": "Backend code generation coverage, ABI notes, memory conventions, validation hooks, and unsupported feature matrix.",
      "id": "backend-capabilities",
      "media_type": "application/json",
      "path": "specs/standard/backend_capabilities.json"
    }
  ],
  "reference_mirrors": [
    {
      "base_path": "web/public/spec",
      "description": "Static artifacts published by the reference web site.",
      "id": "web-public"
    },
    {
      "base_path": "web/src/spec",
      "description": "Reference web source data imported by the UI.",
      "id": "web-src"
    }
  ],
  "standard": "Capsulang",
  "status": "Editor's Draft",
  "version": "0.7"
}
§ 22

Implementation Packs

A Capsulang standard ships implementation packs for agents — bounded, self-contained units of work that an autonomous agent can pick up, execute, and verify without further clarification.

Each pack includes:

target conformance level
the CPS level this pack delivers
files in scope
exact paths the agent may modify
files out of scope
explicit do-not-touch list
required commands
deterministic execution steps
smoke tests
minimum acceptance checks
negative tests
inputs that must fail and how
expected artifacts
files / outputs produced on success
rollback instructions
how to undo a failed pack
done criteria
machine-checkable completion signal
§ 23

Compilation

Capsulang compilation is a deployment and performance path, not a replacement for the checked reference interpreter. The pipeline starts from checked Capsule Core rather than raw source:

.caps source
  -> parser
  -> canonical IR
  -> type/effect checker
  -> Capsule Core
  -> backend-specific lowering

The current add-on implements WebAssembly text, conditional Wasm binary assembly, RV64 textual assembly for the restricted pure scalar subset, and a native-AArch64 manifest that describes the intended Wasm-AOT path. Effectful workflows do not compile into binaries with ambient authority. They compute state transitions and typed EffectIntent records; the host runtime owns policy, adapters, trace, and ledger writes.

WAT

Implemented for supported pure scalar functions.

Wasm

Binary .wasm when wat2wasm is installed; text fallback available.

RISC-V

RV64 assembly for the restricted pure scalar subset.

React

A2UI components, TypeScript host bindings, protocol plan, manifest, and envelope fixtures.

ARM native

Planned through Wasm AOT or LLVM/Cranelift; current command emits an honest plan.

caps compile-backends
caps capsule-abi
caps compile-plan examples/01_abs_i64.caps --target all
caps compile --target wat examples/01_abs_i64.caps --out build/abs.wat --json
caps compile --target wasm examples/01_abs_i64.caps --out build/abs.wasm --allow-text-fallback --json
caps compile --target riscv64 examples/01_abs_i64.caps --out build/abs.s --json
caps compile --target react examples/30_protocol_native_a2ui.caps --out build/repo-review-react --json
caps compile --target native-aarch64 examples/01_abs_i64.caps --out build/native-plan.json --json
caps diff-compiled --target wasm examples/01_abs_i64.caps
Compilation status is target-specific. Use compile-planand release-preview before claiming an artifact is deployable or equivalent to the interpreter.
§ 24

Backend Coverage

Backend generation is deliberately reported as a capability matrix, not a blanket portability claim. The parser, checker, interpreter, and runtime remain authoritative; generated artifacts expose diagnostics when a feature is outside a backend's stable subset. CapsulangCore is a native runtime/SDK, so it is documented in §18 rather than listed as a code generation backend.

BackendStatusFunctionsMachinesABI / MemoryValidation
WebAssembly text
.wat
partialPure scalar functions over Bool, signed I32/I64/Int, and unsigned U32/U64 in the current i64 ABI.not generated
Each exported pure function uses named params; Bool maps to i32. I32/I64/Int map to i64 with signed division, remainder, and ordered comparisons; U32/U64 map to i64 with unsigned division, remainder, and ordered comparisons.
No linear-memory ABI yet; Text, records, lists, maps, options, results, tagged variants, Json, Address, Bytes32, I128/U128, U256/Wei, and Duration layouts are not stable.
wasm-tools validate, wat2wasm
RISC-V RV64 assembly
.s
partialPure scalar functions over Bool, signed I32/I64/Int, and unsigned U32/U64 in the current RV64 integer ABI.not generated
RV64 integer ABI: up to eight integer params in a0-a7, result in a0, callee saves s-registers used for parameters. I32/I64/Int use signed division, remainder, and ordered comparisons; U32/U64 use unsigned divu/remu/sltu lowering.
No heap/string/aggregate/tagged-variant memory convention yet.
riscv64-unknown-elf-as, riscv64-linux-gnu-as, llvm-mc -triple=riscv64
Solidity contract
.sol
partialPure deterministic functions over Bool, Text, Address, signed I32/I64/Int, and unsigned U32/U64/U256/Wei scalar values.not generated
Public Solidity functions with mapped scalar parameter and return types; integer literals in arithmetic and comparisons are explicitly cast to the checked Capsulang operand type. Solidity owns signed/unsigned arithmetic and checked-overflow behavior for those mapped types.
Solidity owns string memory; Bytes32, Json, Timestamp, Duration, QName, Probability, aggregate, and tagged-variant layouts are not stable.
solc --bin
Lean definitions
.lean
partialPure scalar functions as Lean definitions; unsupported functions become explicit axioms.not generated
Lean source is a proof artifact, not a runtime ABI. Capsulang Int maps to Int; unsigned-like integers map to Nat until refinement types land.
No runtime memory model; aggregate and tagged-variant values require proof-level encodings.
lean
XState TypeScript
.xstate.ts
partialnot generatedChecked machine topology, events, context defaults, guards metadata, assignments metadata, effects metadata, retry/on-error metadata, timeout metadata.
Exports one XState config and createMachine instance per Capsulang machine.
Context defaults are JSON values; host code owns richer value coercion.
TypeScript/Vite build in the reference site, structural JSON config checks
SCXML
.scxml
partialnot generatedChecked machine topology, transitions, final states, datamodel defaults, timeout/retry/on-error metadata, effect metadata in Capsulang namespace.
W3C SCXML document with Capsulang extension attributes/elements for non-SCXML semantics.
Datamodel defaults are JSON string expressions; host interpreter owns type coercion.
XML parse
React A2UI bundle
react-target directory
partialnot generatedTyped host bindings, machine/event/effect contracts, and a host bridge hook.
Exports React components for declared A2UI surfaces plus TypeScript contracts for machine events, effect intents, surface state, and surface actions.
Surface state and actions use JSON-compatible TypeScript values; host runtime owns snapshot serialization and adapter payload coercion.
structural React/TypeScript source checks
Use caps compile-plan file.caps --target all to inspect target readiness and caps compile --target wat, caps compile --target wasm, or caps compile --target riscv64 for pure compiled subsets, or caps compile --target react for A2UI surface bundles. Older codegen commands remain useful for backend reports, but compile-plan and release-preview are the preferred agent-facing readiness surfaces.

Source: specs/standard/backend_capabilities.json, mirrored to src/spec/backend_capabilities.json and /spec/backend_capabilities.json.

§ 25

Agent Installation

Capsulang ships repo-local and user-installable instructions for Codex, Claude Code, and other coding agents. These files teach the agent how to write `.caps` modules, run the checker, inspect an agent graph, produce repair plans, and understand the compilation boundary.

Codex

.agents/skills/capsulang-builder/SKILL.md and AGENTS.md

Claude Code

.claude/skills/capsulang-builder/SKILL.md, .claude/commands/use-capsulang.md, and CLAUDE.md

Shared references

language cheatsheet, compilation guide, and deployment-approval workflow guide

Install script

scripts/install_agent_support.sh --user

scripts/install_agent_support.sh --repo
scripts/install_agent_support.sh --user
scripts/verify_agent_support.sh

A good first prompt is: Use Capsulang to build a regulated deployment change approval workflow with risk review, security and manager approvals, A2UI surfaces, deployment and rollback effect intents, semantic trace, and replayable audit history.

caps check examples/23_change_approval_workflow.caps
caps agent-graph --json examples/23_change_approval_workflow.caps
caps release-preview --json examples/23_change_approval_workflow.caps
§ 26

Learnable, Library-First, Inspectable

Capsulang's agent-facing surface is now organized around three goals: learn the language while working, start from documented workflow patterns, and inspect every repair/deployment decision through stable JSON.

Learnable on demand

caps explain, caps fmt, language cheatsheets, and repo-local skills help Codex and Claude learn Capsulang during the task.

Library first

caps patterns list/show/new gives agents standard approval, claim-review, and exception workflows instead of a blank page.

Inspectable by tools

caps check, test, agent-graph, cost, repair-plan, manifest, compile-plan, and release-preview emit structured agent-readable data.

Pattern library

The pattern library is Capsulang's practical standard library: a set of known-good stateful workflows with context, events, effects, A2UI surfaces, and first commands. Agents should start from a pattern and customize it.

caps patterns list --json
caps patterns show regulated-deployment-approval --json
caps patterns show access-change-approval --template --json
caps new access-change-approval --out access_change.caps

Daily inspection loop

caps check access_change.caps --json
caps test access_change.caps --json
caps agent-graph --json access_change.caps
caps cost --json access_change.caps
caps repair-plan --json access_change.caps
caps manifest access_change.caps --json
caps release-preview --json access_change.caps

On-demand learning

caps explain E_EFFECT_NOT_DECLARED
caps fmt access_change.caps
caps skills list --json
caps skills get capsulang-builder --platform codex --full
The goal is not to reduce Capsulang to a tiny systems language. The goal is to expose a small default path for agents while retaining state machines, effect intents, A2UI, MCP/A2A, trace, replay, verification, and compilation.
§ 27

Annotated Demo: Regulated Deployment Approval

The canonical public demo follows a production deployment change from an English requirement into a checked Capsulang machine, scenario evidence, diagrams, A2UI output, trace records, replay ledger, compile plan, release preview, and verification report.

Stateful

The lifecycle moves through request, risk review, approvals, deployment, rollback, and rejection states.

Effectful

Deployment, rollback, persistence, A2A review, and A2UI updates are emitted as effect intents.

Inspectable

Every step has machine-readable evidence for agents, CI, and public review.

Demo command sequence

caps check examples/23_change_approval_workflow.caps --json
caps visualize examples/23_change_approval_workflow.caps --kind machine
caps visualize examples/23_change_approval_workflow.caps --kind effects
caps test examples/23_change_approval_workflow.caps \
  --scenario examples/scenarios/change_approval_happy_path.json \
  --json
caps release-preview --json examples/23_change_approval_workflow.caps
caps compile-plan examples/23_change_approval_workflow.caps --target all
caps verify-report examples/23_change_approval_workflow.caps --format json

Source capsule

(module examples.change_approval
  (capsule "0")
  (profile agentic persistence.surrealdb external.mcp external.a2a ui.a2ui)

  (store operational
    (backend surrealdb)
    (authority runtime-state))

  (store knowledge
    (backend typedb)
    (authority semantic-facts))

  (port ci
    (protocol mcp)
    (tool deploy)
    (tool rollback))

  (agent security_reviewer
    (protocol a2a)
    (skill review_change))

  (surface change_status
    (title "Deployment change status")
    (route "/changes/status")
    (bind ChangeApproval)
    (event SubmitChange RiskReviewed SecurityApprove ManagerApprove Reject Deploy Rollback))

  (surface change_approval
    (title "Deployment change approval")
    (route "/changes/approval")
    (bind ChangeApproval)
    (event SecurityApprove ManagerApprove Reject))

  (surface change_deployment
    (title "Deployment execution")
    (route "/changes/deploy")
    (bind ChangeApproval)
    (event Deploy Rollback))

  (machine ChangeApproval
    (version "0.1.0")
    (context
      (change_id U64)
      (risk_score U32)
      (security_approved Bool)
      (manager_approved Bool)
      (deployed Bool))
    (event SubmitChange
      (change_id U64))
    (event RiskReviewed
      (risk_score U32))
    (event SecurityApprove)
    (event ManagerApprove)
    (event Reject)
    (event Deploy)
    (event Rollback)
    (initial idle)
    (persistence
      (store operational)
      (event-log authoritative)
      (snapshot every-transition)
      (replay true))

    (state idle
      (on SubmitChange
        (target awaiting_risk_review)
        (assign
          (change_id event.change_id)
          (risk_score 0)
          (security_approved false)
          (manager_approved false)
          (deployed false))
        (effects
          (db.write operational.change_requests)
          (a2a.task security_reviewer.review_change)
          (a2ui.emit change_status))))

    (state awaiting_risk_review
      (on RiskReviewed
        (target awaiting_approvals)
        (assign
          (risk_score event.risk_score))
        (effects
          (db.write operational.change_reviews)
          (a2ui.emit change_approval))))

    (state awaiting_approvals
      (on SecurityApprove
        (target awaiting_approvals)
        (assign
          (security_approved true))
        (effects
          (db.write operational.approvals)
          (a2ui.emit change_approval)))
      (on ManagerApprove
        (target ready_to_deploy)
        (guard security_approved)
        (assign
          (manager_approved true))
        (effects
          (db.write operational.approvals)
          (a2ui.emit change_deployment)))
      (on Reject
        (target rejected)
        (effects
          (db.write operational.approvals)
          (a2ui.emit change_status))))

    (state ready_to_deploy
      (on Deploy
        (guard (and security_approved manager_approved (<= risk_score 40)))
        (target deployed)
        (assign
          (deployed true))
        (effects
          (db.write operational.deployments)
          (mcp.call ci.deploy)
          (a2ui.emit change_deployment)))
      (on Reject
        (target rejected)
        (effects
          (db.write operational.approvals)
          (a2ui.emit change_status))))

    (state deployed
      (on Rollback
        (target rolled_back)
        (assign
          (deployed false))
        (effects
          (db.write operational.deployments)
          (mcp.call ci.rollback)
          (a2ui.emit change_deployment))))

    (state rolled_back (type final))
    (state rejected (type final))))

Machine diagram

stateDiagram-v2
  title ChangeApproval
  [*] --> idle
  idle --> awaiting_risk_review: SubmitChange / assign, (db.write operational.change_requests), (a2a.task security_reviewer.review_change), (a2ui.emit change_status)
  awaiting_risk_review --> awaiting_approvals: RiskReviewed / assign, (db.write operational.change_reviews), (a2ui.emit change_approval)
  awaiting_approvals --> awaiting_approvals: SecurityApprove / assign, (db.write operational.approvals), (a2ui.emit change_approval)
  awaiting_approvals --> ready_to_deploy: ManagerApprove / assign, guard, (db.write operational.approvals), (a2ui.emit change_deployment)
  awaiting_approvals --> rejected: Reject / (db.write operational.approvals), (a2ui.emit change_status)
  ready_to_deploy --> deployed: Deploy / assign, guard, (db.write operational.deployments), (mcp.call ci.deploy), (a2ui.emit change_deployment)
  ready_to_deploy --> rejected: Reject / (db.write operational.approvals), (a2ui.emit change_status)
  deployed --> rolled_back: Rollback / assign, (db.write operational.deployments), (mcp.call ci.rollback), (a2ui.emit change_deployment)
  rolled_back --> [*]
  rejected --> [*]

Effect graph

flowchart LR
  subgraph M["machine ChangeApproval"]
    state_idle["idle"]
    state_awaiting_risk_review["awaiting_risk_review"]
    state_awaiting_approvals["awaiting_approvals"]
    state_ready_to_deploy["ready_to_deploy"]
    state_deployed["deployed"]
    state_rolled_back["rolled_back"]
    state_rejected["rejected"]
  end
  state_idle --> transition_idle_SubmitChange_0{"SubmitChange"}
  transition_idle_SubmitChange_0 --> state_awaiting_risk_review
  effect_0_db_write_operational_change_requests[["(db.write operational.change_requests)"]]
  transition_idle_SubmitChange_0 -. emits .-> effect_0_db_write_operational_change_requests
  effect_1_a2a_task_security_reviewer_review_change[["(a2a.task security_reviewer.review_change)"]]
  transition_idle_SubmitChange_0 -. emits .-> effect_1_a2a_task_security_reviewer_review_change
  effect_2_a2ui_emit_change_status[["(a2ui.emit change_status)"]]
  transition_idle_SubmitChange_0 -. emits .-> effect_2_a2ui_emit_change_status
  state_awaiting_risk_review --> transition_awaiting_risk_review_RiskReviewed_1{"RiskReviewed"}
  transition_awaiting_risk_review_RiskReviewed_1 --> state_awaiting_approvals
  effect_3_db_write_operational_change_reviews[["(db.write operational.change_reviews)"]]
  transition_awaiting_risk_review_RiskReviewed_1 -. emits .-> effect_3_db_write_operational_change_reviews
  effect_4_a2ui_emit_change_approval[["(a2ui.emit change_approval)"]]
  transition_awaiting_risk_review_RiskReviewed_1 -. emits .-> effect_4_a2ui_emit_change_approval
  state_awaiting_approvals --> transition_awaiting_approvals_SecurityApprove_2{"SecurityApprove"}
  transition_awaiting_approvals_SecurityApprove_2 --> state_awaiting_approvals
  effect_5_db_write_operational_approvals[["(db.write operational.approvals)"]]
  transition_awaiting_approvals_SecurityApprove_2 -. emits .-> effect_5_db_write_operational_approvals
  transition_awaiting_approvals_SecurityApprove_2 -. emits .-> effect_4_a2ui_emit_change_approval
  state_awaiting_approvals --> transition_awaiting_approvals_ManagerApprove_3{"ManagerApprove"}
  transition_awaiting_approvals_ManagerApprove_3 --> state_ready_to_deploy
  transition_awaiting_approvals_ManagerApprove_3 -. emits .-> effect_5_db_write_operational_approvals
  effect_6_a2ui_emit_change_deployment[["(a2ui.emit change_deployment)"]]
  transition_awaiting_approvals_ManagerApprove_3 -. emits .-> effect_6_a2ui_emit_change_deployment
  state_awaiting_approvals --> transition_awaiting_approvals_Reject_4{"Reject"}
  transition_awaiting_approvals_Reject_4 --> state_rejected
  transition_awaiting_approvals_Reject_4 -. emits .-> effect_5_db_write_operational_approvals
  transition_awaiting_approvals_Reject_4 -. emits .-> effect_2_a2ui_emit_change_status
  state_ready_to_deploy --> transition_ready_to_deploy_Deploy_5{"Deploy"}
  transition_ready_to_deploy_Deploy_5 --> state_deployed
  effect_7_db_write_operational_deployments[["(db.write operational.deployments)"]]
  transition_ready_to_deploy_Deploy_5 -. emits .-> effect_7_db_write_operational_deployments
  effect_8_mcp_call_ci_deploy[["(mcp.call ci.deploy)"]]
  transition_ready_to_deploy_Deploy_5 -. emits .-> effect_8_mcp_call_ci_deploy
  transition_ready_to_deploy_Deploy_5 -. emits .-> effect_6_a2ui_emit_change_deployment
  state_ready_to_deploy --> transition_ready_to_deploy_Reject_6{"Reject"}
  transition_ready_to_deploy_Reject_6 --> state_rejected
  transition_ready_to_deploy_Reject_6 -. emits .-> effect_5_db_write_operational_approvals
  transition_ready_to_deploy_Reject_6 -. emits .-> effect_2_a2ui_emit_change_status
  state_deployed --> transition_deployed_Rollback_7{"Rollback"}
  transition_deployed_Rollback_7 --> state_rolled_back
  transition_deployed_Rollback_7 -. emits .-> effect_7_db_write_operational_deployments
  effect_9_mcp_call_ci_rollback[["(mcp.call ci.rollback)"]]
  transition_deployed_Rollback_7 -. emits .-> effect_9_mcp_call_ci_rollback
  transition_deployed_Rollback_7 -. emits .-> effect_6_a2ui_emit_change_deployment

A2UI mock stream

{"version":"v0.9","createSurface":{"surfaceId":"change_status","catalogId":"capsulang.basic","sendDataModel":true}}
{"version":"v0.9","updateComponents":{"surfaceId":"change_status","components":[{"id":"root","component":"Card","child":"body"},{"id":"body","component":"Column","children":["title","state","risk","actions"]},{"id":"title","component":"Text","text":"Deployment change #1001","variant":"h2"},{"id":"state","component":"Text","text":{"path":"/state"}},{"id":"risk","component":"Text","text":{"path":"/risk_summary"}},{"id":"actions","component":"Row","children":["approve_security","approve_manager","deploy"]},{"id":"approve_security","component":"Button","text":"Security approve","action":{"event":{"name":"SecurityApprove"}}},{"id":"approve_manager","component":"Button","text":"Manager approve","action":{"event":{"name":"ManagerApprove"}}},{"id":"deploy","component":"Button","text":"Deploy","action":{"event":{"name":"Deploy"}}}]}}
{"version":"v0.9","updateDataModel":{"surfaceId":"change_status","path":"/","value":{"state":"awaiting_approvals","risk_score":25,"risk_summary":"Low risk; deployment blocked until security and manager approvals are both recorded.","security_approved":false,"manager_approved":false,"deployed":false}}}

Evidence artifacts

The demo proves checked state transitions, inspectable effect intents, trace and ledger evidence, and release planning. It does not claim live CI deployment, live A2A/MCP calls, native compilation of the effectful workflow, or completed Lean proofs.
§ 28

Quick Start

Clone the reference implementation and check the canonical example:

git clone https://github.com/advatar/Capsulang.git
cd Capsulang
scripts/install_capsulang.sh

caps check examples/01_abs_i64.caps
caps machine-run examples/03_claim_review_machine.caps \
  ClaimReview SubmitClaim --mode dry-run

The installer creates an isolated virtualenv, links caps into ~/.local/bin by default, and prints the exact PATH export if your shell needs one.

Run the native Swift package for Apple-platform runtime checks:

cd swift/CapsulangSwift
swift test
swift run caps-swift call Examples/01_abs_i64.caps abs_i64 x=-7

The command prints 7. For app embedding, import theCapsulangCore library target and route returned EffectIntent records through host-owned policy.

Compile a Capsule governance contract into checked Capsulang and container runtime artifacts:

caps capsule-check examples/29_capsule_refund_reviewer.capsule.yaml --json
caps capsule-compile examples/29_capsule_refund_reviewer.capsule.yaml --out-dir build/capsule-refund --json
caps check build/capsule-refund/claims-refund-reviewer.caps --json

The generated bundle includes Docker Compose, Seatbelt, doorkeeper, telemetry, receipt, attestation, and negative-test artifacts.

Inspect the protocol-native runtime surface for A2UI, MCP, and A2A:

caps check examples/30_protocol_native_a2ui.caps --json
caps protocol-plan examples/30_protocol_native_a2ui.caps --json
caps a2ui-manifest examples/30_protocol_native_a2ui.caps --json
caps a2ui-envelope examples/30_protocol_native_a2ui.caps repo_review_ui --kind create --json

The protocol plan lists declared MCP ports, A2A collaborators, A2UI surfaces, typed protocol effects, and renderer-ready A2UI envelopes.

Generate React components and TypeScript bindings from checked A2UI surfaces:

caps compile --target react examples/30_protocol_native_a2ui.caps \
  --out build/repo-review-react \
  --json

The React bundle renders A2UI state/actions and returns typed user actions to the host runtime. It does not execute external effects.

Run the authoring UI with an LLM backend:

export OPENAI_API_KEY=...
export OPENAI_MODEL=gpt-5.4

caps serve-authoring-ui --host 127.0.0.1 --port 8123

Capsulang reference URLs are placeholders until v0.7 is published.

§ 29

Get the Artifacts

Standard data is mirrored from specs/standard/ into src/spec/ and served under /spec/. This section includes the protocol-native A2UI/MCP/A2A example, the Capsule contract compiler notes, the EDL lowering outputs, and the generated container runtime artifacts used for review and publishing.

Read spec (Markdown)Normative standard (Markdown)ClaimReview example (.caps)Change approval workflow example (.caps)Annotated deployment approval demo guideDeployment approval scenario evidenceDeployment approval A2UI mock streamImprovement governance example (.caps)Authority IR example (.caps)Authority IR note (Markdown)Protocol-native MCP/A2A/A2UI example (.caps)Protocol-native runtime note (Markdown)React/A2UI compiler target noteCapsule compiler noteCapsule contract schemaRefund reviewer Capsule contractGenerated Capsule IRGenerated Capsule workflow (.caps)Generated lowered EDLGenerated Capsule Docker ComposeGenerated Capsule doorkeeper policyGenerated Capsule telemetry planGenerated Capsule receipt planGenerated Capsule attestation evidenceGenerated Capsule negative testsGenerated Capsule Seatbelt profileLower-level EDL compiler noteGitHub coding-agent EDL sourceGenerated enclosure capsule (.caps)Generated Docker Compose enclosureGenerated normalized Enclosure IRGenerated doorkeeper policyGenerated telemetry planGenerated receipt planGenerated attestation evidenceGenerated negative testsGenerated Seatbelt profileImprovement governance note (Markdown)Recursive self-improvement note (Markdown)AFPS manifest exampleConstructs status (JSON)Conformance levels (JSON)Effect catalog (JSON)Backend capabilities (JSON)Standard manifest (JSON)Swift reference package notePattern library noteAgent learnability noteTool inspection noteCapsulangSwift packageCapsulang v0.7 repoAFPS reference