Skip to content
Press / to search

How It Works

Follow a refund through context, authorization, tool execution, outcome verification, and a replayable DecisionRecord.

Living DocumentLast reviewed: Edit on GitHub
At a glance

This page walks one request through a ContextOS-conformant implementation, naming every primitive that touches it and every artifact that comes out. The example is support.refund because it exercises every plane: retrieval, policy, identity, native action risk, v1 compatibility, decision typing, and audit.

The workflow is illustrative. This repository supplies the contracts, deterministic validators and synthetic reference workflows; an implementing runtime supplies execution, atomic stores and the external payment system. Synthetic checks do not prove production enforcement. If you already have an agent, start with its acceptance and control boundaries before reproducing the full architecture.

Keep three states distinct throughout: an order can qualify for a refund, a caller can be authorized to issue it, and a payment system can confirm that it happened. A positive answer to one does not establish the others. Planner, Executor, and Critic describe responsibilities in the canonical loop; they do not require three separately deployed agents.

Core promise

A request enters an implementing runtime carrying a RunContext. The Compiler assembles a bounded CompiledContext from the pinned Context Pack. The bounded Planner / Executor / Critic triad runs the cognitive loop. Every side effect routes through the Tool Gateway, which evaluates the capability’s native ActionRisk, actual arguments, effective authority, and approval state. The output is a typed DecisionRecord with evidence, approvals, controls, and a trace.

Simplified compatible compiler flowEight deterministic stages consume caller-supplied evidence and memory to emit CompiledContext. Applicable policy errors stop visibly. Independent current execution controls still govern effects.1. Intent AnalysisResolve intent2. Policy EngineJsonLogic Eval3. Tool SurfacePerms ∩ RulesCompiledContextRequestCOMPILE FILTERS1. Registry ∩ permissions2. Rule prohibitions3. Native risk + v1 ceilingSimplified view of eight stages; caller supplies eligible evidence and promoted memory.Compiled context does not authorize an effect; current independent controls remain required.

The canonical contract (recap)

invokeAgent(request_envelope, run_context)
  → admit(exact profiles, workflow features, implementation support)
  → compile(packs, request, run_context) → CompiledContext
  → loop {
       planner(CompiledContext)         → Plan
       critic.verify(Plan)              → ok | replan | reject
       executor(Plan, ToolGateway)      → step_results, evidence
       critic.score(step_results)       → accept | retry | replan | escalate
       consolidate(effects, evidence)   → memory_proposals
     }
  → DecisionRecord(evidence_refs, approvals, controls_active, trace_id)

Step 1 — Receive the request

The caller sends an invokeAgent envelope; the trusted runtime constructs the separate RunContext. See API Contracts for both shapes. An illustrative request:

{
  "request_id": "req_9f3a12",
  "session_id": "sess_42f1",
  "tenant_id": "tenant_acme_prod",
  "user": { "user_id": "usr_771", "delegation": { "auth_type": "oauth2", "scopes": ["orders.read", "payments.refund"], "subject": "u:user:771" } },
  "agent": { "agent_id": "agt_support", "workload_identity": "spiffe://contextos/agents/support", "role": "support_ops" },
  "context_pack_refs": ["ctxpack.support@5.2.0"],
  "input": {
    "intent": "support.refund",
    "message": "Refund order ord_881 for INR 4200.",
    "context": { "identity_verified": true, "order_id": "ord_881", "refund_amount": 4200, "currency": "INR" }
  },
  "mode": "stream",
  "runtime": { "plan_timeout_ms": 15000, "max_tool_calls": 8, "max_payload_bytes": 1048576 },
  "trace": { "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "span_id": "00f067aa0ba902b7", "trace_flags": "01" }
}

The runtime materializes a RunContext (run_id, the trace IDs, safety_mode, run_budget) and pins the Context Pack version + Knowledge Graph snapshot for replay.

For this enterprise workflow, admission resolves the exact contextos.enterprise@1 definition and requirements activated by the actual workflow features. Additional profiles can be required; requirements are cumulative. The execution-contract attachment preserves the existing envelopes. Support negotiation establishes compatibility; authenticated observations, source verification and current enforcement still belong to the runtime. In particular, a caller’s identity_verified: true field must not self-authenticate the caller.

Step 2 — Compile the Context Pack

The Context Pack Compiler runs its eight stages:

  1. Intent classification — resolve support.refund to its template in the Intent-Task Catalog.
  2. Policy resolution — evaluate JsonLogic rules from the pack’s POLICY_RETURNS_V4 bundle against the Run Context. An applicable expression error stops compilation with a structured ContextCompileError; a false expression follows its normal false/else path.
  3. Tool surfacing — intersect Registry ∩ Permissions − Prohibitions; apply native-risk policy and the v1 safety_mode compatibility ceiling.
  4. Evidence normalization — accept retrieved candidates and conflict markers, verify hashes, and label integrity, freshness, provenance, and the requirements each candidate can satisfy.
  5. Memory recall — pull promoted memory only and preserve its source lineage.
  6. Token budget allocation — distribute run_budget.bucket_tokens across context buckets.
  7. Bucket admission and assembly — apply control or data_only, admit eligible evidence, pack each bucket, and record structured omissions.
  8. Manifests + runtime controls — evaluate context sufficiency and emit the admitted evidence_manifest, context_admission, and conflict-aware per-decision evidence_gates with the rest of the envelope.

The output is a CompiledContext envelope. See Agentic Context Engineering for the discipline; see Context Pack for the schema.

The retrieval layer does not hand the compiler anonymous text. It supplies a structured candidate:

{
  "evidence_ref": "kg:order:ord_881#snapshot_2026_07_31",
  "source_id": "orders-db",
  "content": "{\"order_id\":\"ord_881\",\"customer_id\":\"cus_77\",\"status\":\"delivered\"}",
  "integrity": "verified",
  "freshness": "current",
  "satisfies": ["order_lookup"]
}

The compiler derives the content hash; this candidate omits the optional caller-supplied hash. If supplied, it must match the actual content bytes or compilation throws. Integrity and freshness labels require upstream verification; deriving a hash does not authenticate the source. Retrieved content is always rendered with instruction_treatment: "data_only"; text inside the record cannot become a runtime instruction.

Step 3 — Plan

The Planner reads the CompiledContext and produces a typed Plan:

{
  "plan_id": "plan_refund_01",
  "intent": "support.refund",
  "steps": [
    { "id": "s1", "tool": "adp_orders.lookup", "params": { "order_id": "ord_881" }, "approval_mode": "read_only" },
    { "id": "s2", "tool": "adp_policy.eval", "depends_on": ["s1"], "approval_mode": "read_only" },
    { "id": "s3", "tool": "adp_payments.issue_refund",
      "depends_on": ["s2"],
      "approval_mode": "destructive",
      "requires": ["GATE_FINANCE_APPROVAL"] }
  ],
  "decision_checkpoints": [
    { "decision_id": "support.refund.execute", "after_step": "s2" }
  ]
}

The Planner cannot execute anything; it only proposes the plan.

The current PlanStep carries approval_mode for v1 compatibility. Native ActionRisk is owned by the registered capability and is re-evaluated with the proposed arguments at the Gateway; the Planner cannot lower it by writing a safer label.

Step 4 — Critic verifies the plan

The Critic checks:

  • every tool exists in the pack’s tool_manifest,
  • every argument satisfies its schema,
  • the step’s compatibility approval_mode does not understate the registered capability,
  • the capability’s native ActionRisk and proposed arguments satisfy every independent policy dimension,
  • the decision checkpoint resolves to a Decision Spec whose evidence gate can be closed by admitted, current, verified evidence,
  • every retrieved or recalled block remains data_only, including any instruction-like text it contains,
  • the plan does not violate any guardrail in runtime_controls.

A clean verify produces an ok verdict; otherwise control returns to the Planner under the max_replan_attempts budget.

Step 5 — Executor runs the plan

For each step, the Executor calls the Tool Gateway:

  • s1 and s2 are read_only; they can execute after current read authority, data-flow and budget checks. Reading customer data is still governed work.
  • At the decision checkpoint after s2, before the destructive refund call, the Critic requires runtime_controls.evidence_gates["support.refund.execute"].commit_allowed to be true for verified identity, order lookup, and policy decision.
  • s3 projects to the v1 destructive mode and its native vector is an external, user-delegated, compensatable API effect over confidential data. Policy routes it through propose → approve → execute. Approval binds the complete ActionBinding, including exact arguments, evidence, policy/profile/release pins and INR amount in explicit minor units. The runtime validates current eligible approvers, quorum and any separation of duties, then atomically redeems the approval for that operation.
  • Because the request is for INR 4200 by a support_agent, the INR 3000 high-value threshold activates GATE_FINANCE_APPROVAL.

The ToolCallEnvelope carries the policy decision, principal chain, v1 mode fields, optional native-risk fields, evidence refs, idempotency key, and trace identity. The paired ToolResultEnvelope records status, validated output, artifacts, citations, mutations, risk tags, policy linkage, and latency. Deployment telemetry carries the W3C trace context across the protocol boundary.

Immediately before dispatch, the runtime rechecks unrevoked authority, current policy and approval validity, brokered credentials, observed boundary configuration, actual recipient/processor/data route, and an aggregate budget reservation. The operation ledger uses atomic revision/generation checks; an idempotency key alone cannot make a provider safe to retry. A lost acknowledgement leaves the effect unknown until verified reconciliation resolves it. Cancellation does not imply rollback, and resume retains the operation identity, uncertainty and original shared budget rather than resetting them. Execution Contract defines these obligations and their reference limits.

ContextOS ContractPolicy & GatesCompiler & MemoryAdapter MeshExact profiles · current authority · active boundariesFenced effects · shared budgets · scoped evidenceContextActions

Step 6 — Critic scores

After all steps complete, the Critic scores the run on evaluators (Policy / Utility / Latency / Safety / Economics) and renders one of accept / retry / replan / escalate. Acceptance produces the DecisionRecord:

Acceptance of this example requires verified payment effect and postcondition evidence. A DECIDED status, policy allow, or successful transport response alone does not establish that the refund happened. The record below illustrates the existing v1 receipt; its abbreviated hashes are display placeholders, and the separate execution-contract attachments retain exact action, approval, operation and evidence bindings.

{
  "record_id": "dr_2026_05_04_a17",
  "decision_key": "support.refund.execute",
  "decision_version": "1.0.0",
  "timestamp": "2026-05-04T09:31:42Z",
  "status": "DECIDED",
  "actor": { "type": "AGENT", "id": "agt_support" },
  "outputs": { "refund_amount": 4200, "currency": "INR", "transaction_id": "txn_q9..." },
  "evidence_refs": [
    "kg:order:ord_881#snapshot_kg_2026_05_03_T0930",
    "tool:adp_orders.lookup:tc_117",
    "tool:adp_policy.eval:tc_119",
    "tool:adp_payments.issue_refund:tc_121"
  ],
  "policy_decisions": [{ "policy_decision_id": "pol_9901", "rule_ids": ["R_REFUND_REQUIRES_IDV", "R_HIGH_VALUE_REQUIRES_APPROVAL"] }],
  "approvals": [{
    "gate_id": "GATE_FINANCE_APPROVAL",
    "approver": "user_finance_lead_77",
    "approval_mode_effective": "destructive",
    "evidence_snapshot_hash": "sha256:b2a1...",
    "decided_at": "2026-05-04T09:31:30Z"
  }],
  "controls_active": {
    "must_refuse": [],
    "must_escalate": [],
    "approval_gates_active": ["GATE_FINANCE_APPROVAL"],
    "redaction_rules_active": [],
    "context_admission": {
      "data_only_block_ids": ["ev_order"],
      "untrusted_block_ids": [],
      "privileged_sink_policy": "verified_or_user_intent"
    },
    "evidence_gates": [
      {
        "decision_key": "support.refund.execute",
        "required": ["identity_verified", "order_lookup", "policy.eval"],
        "satisfied": ["identity_verified", "order_lookup", "policy.eval"],
        "unresolved": [],
        "rejected_evidence": [],
        "conflicts": [],
        "sufficiency": "sufficient",
        "commit_allowed": true
      }
    ]
  },
  "budget_usage": { "tokens": 4720, "tool_calls": 4, "cost_usd_cents": 0.91, "wall_clock_ms": 1840 },
  "lineage": { "pack_version": "ctxpack.support@5.2.0", "decision_spec": "support.refund.execute@1.0.0", "kg_snapshot": "kg_2026_05_03_T0930" },
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}

Step 7 — Consolidate

The Consolidation layer produces memory write proposals (e.g., “customer prefers email updates” with evidence_ref, consent_check: passed). They land in the Memory review queue per the pack’s promotion policy. A model-emitted consent flag is a proposal field; the memory service verifies authority, consent, namespace/readers, retention and propagation obligations before admitting durable memory.

Reference architecture

See Reference Architecture for the full reference design.

Inputs and outputs

Inputs

  • invokeAgent envelope with RunContext
  • Pinned Context Pack + Knowledge Graph snapshot
  • Memory state (working / episodic / semantic / durable, post-promotion only)
  • Adapter registry with native ActionRisk, v1 compatibility modes, schemas, and authority ceilings

Outputs

  • DecisionRecord with evidence_refs, approvals, controls_active, trace_id
  • Tool transcripts and evidence manifest
  • Memory write proposals
  • OTEL trace bundle and scorecard

Failure modes that block execution

  • Policy gate or guardrail not satisfied at the boundary.
  • required_evidence missing, stale, untrusted, unknown-freshness, or omitted by the context budget.
  • Caller-provided evidence hash does not match the supplied content.
  • A retrieved or recalled block is treated as an instruction instead of data_only.
  • Approval gate unanswered within the gate timeout.
  • Tool schema validation fails at the Tool Gateway.
  • Loop guard trips on repeated identical tool calls.
  • Run Budget exhausted before the plan can complete.
  • Required profile/control unsupported, current boundary evidence missing, or authority revoked.
  • An uncertain external effect cannot be safely retried or a resumed worker cannot acquire current ownership/fencing.

Runtime control failures produce explicit denial, escalation, waiting or rejected-transition results appropriate to that boundary. Compilation can throw: applicable policy-expression failures use the serializable ContextCompileError, while invalid evidence hashes also stop compilation. The invocation boundary must catch and report these failures safely; it must not fabricate a successful CompiledContext or treat an expression error as false.

Where each step is specified

StepSpec doc
Receive requestAPI Contracts
Admit profiles, dispatch and recoverExecution Contract, Control Profiles, Conformance
CompileCognitive Core, Context Pack, Agentic Context Engineering
Plan / Verify / Execute / ScoreOrchestration
Tool executionAdapter Mesh
Approval gateGovernance, High-Risk Workflow
Decision typingDecision Catalog
ConsolidationMemory, Memory Fabric
Trace + audit + replayEvaluation and Observability, Security and Compliance

Where to go next

You have now seen one run end-to-end. Pick your next door:

  • Build it → Quickstart — model this same support.refund workflow as the smallest governed MVP.
  • Run the compiler → Context Pack — change the inputs and watch the CompiledContext (and its deterministic hash) recompile live.
  • Go deep → Reference Architecture — the full five-plane reference design.
  • Find your path → the Docs Overview has reading paths tailored to platform, product, applied-AI, security, and executive readers.