Skip to content
Back to Blog

Inside ContextOS: Shared Business Limits for AI Agents

Published Updated Editorial policy & corrections

Share:XBSMRedditHNEmail

Two support agents receive requests about the same order. One works the email queue; the other handles chat. Each has permission to issue an INR 800 refund. Each has enough execution budget. Each passes its own policy checks.

The order has a shared refund ceiling of INR 1,000.

If both agents act, the company refunds INR 1,600. Neither agent needed to ignore an instruction. The failure sits between independently valid decisions and shared business state.

ContextOS is now public. The Rust runtime and Tower governance plane put a protected boundary in front of consequential tools: check the exact action, reserve shared capacity before dispatch, and retain exposure when the external outcome is unresolved. Existing agent frameworks continue to plan and coordinate work.

This first runtime article follows that refund race through the implementation. It explains where determinism ends, where storage atomicity begins, and why an unknown effect must remain someone’s liability.

Source and release scope: this walkthrough examines public revision a61a247, reviewed on October 26, 2026. The first public release is v0.1.0-alpha.1. APIs and storage formats are evolving. The examples below describe synthetic workflows and source behavior; they make no production performance or deployment-conformance claim.

Update, October 29, 2026: v0.1.0-alpha.2 replaces alpha.1 as the release to try. Its Linux archives need glibc 2.28 or newer; alpha.1’s Linux contextosd needed glibc 2.38 and failed to start on systems such as Ubuntu 22.04. It also contains two breaking changes that affect this article’s dispatch path: every effectful HTTP capability must declare recovery.completion, so a 2xx settles an effect only when the provider’s reported state says so, and an effectful 4xx is unknown unless the manifest lists that status as not applied. Tower approvals are now bound to each capability’s risk. The walkthrough below still describes revision a61a247; the alpha.2 release notes list the changes and upgrade steps, and Project Status tracks current versions.

The unit of control is a business resource

Per-agent permissions answer whether a principal may request a refund. Per-run budgets answer how much one run and its delegated children may consume. Neither boundary automatically coordinates two unrelated runs against the same order.

The shared-guarantee extension introduces a separate accounting domain:

(authenticated tenant, configured guarantee, canonical business resource)

For that domain, the invariant is:

committed + held <= limit
available = limit - committed - held

committed accounts for confirmed effects. held accounts for reservations and effects that might still apply. Changing a run ID does not change the resource’s capacity. Another server replica does not create another allowance when it shares the same tenant, guarantee definition and protected store.

This is an opt-in runtime extension alongside the portable execution contract. It does not change the specification’s run-budget semantics. The architecture decision keeps these responsibilities separate: a business ceiling survives the runs that consume it.

The initial implementation governs configured numeric ceilings. A refund ceiling is a policy limit, not a live query of captured payment, refundable balance or every historical refund. The integration must account for prior exposure and retain the business service’s own invariant checks.

Three layers, with different jobs

The public repository contains an embeddable decision kernel, an enforcing runtime and a fleet governance plane.

The kernel computes a decision

contextos-kernel performs no I/O, reads no ambient clock and draws no randomness. Time and verified observations arrive as explicit inputs. Compiler, authorization and ledger functions can therefore be replayed against recorded inputs.

That separation makes a boundary reviewable. Given identical state, proposal and observations, a transition should produce the same acceptance or refusal. The kernel does not ask another model whether exceeding a ceiling seems reasonable.

A kernel verdict alone cannot cause or authorize an external effect in isolation. Its caller must authenticate the facts and enforce the verdict where the effect occurs. Embedding a pure checker in an agent process does not provide a durable shared store or prevent a different process from bypassing it.

The runtime owns enforcement

contextosd combines the kernel with authenticated requests, current authority and approval providers, protected storage, executor fencing, adapters and audit signing. Its gateway mediates the transition from a proposed tool call to an external invocation.

An agent can choose a capability and propose arguments. It cannot make its own claim of permission authoritative, choose a larger shared ceiling, or erase a pending reservation by starting again.

Tower governs the fleet

towerd and its console consume evidence from configured runtimes, verify source chains and expose governance views, reviews, guardrails and waivers. Runtime control, including a fleet kill switch, uses scoped runtime APIs. Agents submit work to their runtime; Tower is outside that tool-call path.

Optional AI assistance in Tower is advisory. A generated explanation does not grant tool authority. The Tower architecture describes this separation in detail. Dedicated shared-exposure views remain planned work at the reviewed revision; the runtime already exposes tenant-scoped inspection endpoints.

Follow one action to the dispatch boundary

The gateway implementation is useful to read as a sequence of obligations.

First, surface the capability. The tool must belong to the run’s pinned manifests and compiled context. Cited evidence must have been admitted. Tool discovery does not confer permission to execute every discoverable capability.

Bind the complete proposal. An action digest uses RFC 8785 canonical JSON and covers the full action binding. Nested arguments, evidence and relevant policy, profile and release pins belong to that binding. Approval for one proposal cannot be reused after changing its amount or destination.

Evaluate current authorization. Authority, composed policy, independent constraints and any required exactly bound approval must agree. Approval redemption uses protected compare-and-swap state. Selected execution requirements also need their actual boundary and data-flow observations; a caller’s label is insufficient.

Reserve execution resources and claim the operation. The run budget remains conserved. A stable operation identity is distinct from its transport attempts. Claims use the current executor generation, so a stale worker cannot rely on an old ownership view to start a new governed attempt.

Reserve shared business exposure. For a configured guarantee, the gateway extracts the resource and amount from the same action arguments, pins the guarantee definition, persists its operation link and reserves capacity atomically. The reservation is signed before the provider call is permitted.

Activate the exact attempt, dispatch, observe and settle. A durable dispatch-start transition must succeed for that receipt before invoking the adapter. The resulting observation drives recovery and accounting. A timeout preserves uncertainty. It does not establish that the provider did nothing.

These are distinct controls. A valid approval cannot manufacture business capacity. Available capacity cannot override a revoked authority chain. Neither substitutes for a current executor claim or an acceptable provider recovery contract.

Configure the ceiling outside agent output

The shared-refund example uses this top-level runtime configuration:

[[guarantees]]
id = "refunds-per-order"
capability_ids = ["adp_payments.issue_refund"]
resource_pointer = "/order_id"
amount_pointer = "/amount_minor"
limit = 100000
unit = "INR_minor"

For this integration, 100000 minor units represents INR 1,000. The JSON pointers identify fields in the bound tool arguments. The unit is trusted configuration metadata; ContextOS does not perform currency conversion.

The runtime refuses missing resource values and invalid amounts, including zero, negatives, fractions and values outside its exact integer range. Resource identifiers must already be canonical. If ord_881 and ORD_881 refer to one business order upstream, the integration must resolve that alias before either reaches this boundary.

Every participating replica must use the same guarantee definitions, tenant identities and protected store. An in-memory store demonstrates coordination inside one process. Durable coordination across processes requires PostgreSQL. Independent stores define independent enforcement domains, even when their configuration files look identical.

The configuration and recovery guide specifies these constraints and inspection routes.

The race is resolved by a committed transition

Suppose both agents read an empty ledger at revision 7:

limit = 100000; committed = 0; held = 0
agent A requests 80000
agent B requests 80000

Each can independently calculate that its proposed reservation fits. That calculation becomes useful only when the storage layer commits it against the revision it actually read.

In one possible interleaving:

  1. A computes held = 80000 and wins the compare-and-swap against revision 7.
  2. B attempts a write against revision 7 and encounters a conflict.
  3. B reloads the ledger and recomputes the transition against A’s reservation.
  4. B’s proposed total is now 160000, exceeding 100000; it is refused before dispatch.

Which agent wins depends on scheduling. The safety condition is independent of the winner.

The split is visible in the source. reserve_exposure validates the ledger, recomputes held and committed totals from receipts, checks arithmetic and produces a transition. The store’s transact_state rereads and redecides on revision conflicts, with a bounded retry count. Exhausted contention returns an error; it cannot fall through to dispatch.

The reservation and the durable adapter-start gate are separate steps. There is no claim of an atomic transaction spanning PostgreSQL and an arbitrary external provider. Recovery must explicitly handle the gaps between local durable state and external effects.

Why a reservation needs an exact-attempt dispatch gate

Consider a worker that reserves capacity and pauses immediately before dispatch. Recovery observes a stranded reservation and wants to release it. The original worker might wake up and invoke the tool after that release, while another agent spends the newly available capacity.

A lease timeout alone cannot resolve that race.

The shared-exposure receipt tracks whether dispatch started or was aborted. Dispatch activation and pre-dispatch recovery compete on that exact receipt. Recovery can close an unstarted attempt; it can also establish a tombstone before a delayed reservation arrives. The delayed worker cannot revive a closed attempt.

Conversely, after dispatch has started, an absence assertion cannot free capacity while that call may still run. If the worker disappears before recording an observation, the alpha conservatively refuses absence-based release with shared_guarantee_dispatch_active. Additional recovery tooling would be needed to establish externally fenced absence.

This is a practical boundary on availability. Conservative accounting can strand capacity. Releasing it without sufficient evidence can violate the business ceiling. The shared-guarantee gateway code preserves the hold and records why it cannot safely release it.

Unknown effects continue to consume capacity

After the first INR 800 refund is confirmed, the ledger has INR 200 available. Now a third agent requests INR 150 and the provider returns a pending task.

EventCommittedHeldAvailable
First refund confirmedINR 800INR 0INR 200
INR 150 effect pendingINR 800INR 150INR 50
Another INR 100 requestedINR 800INR 150INR 50; request withheld
Provider query confirms pending effectINR 950INR 0INR 50

These are the synthetic shared-guarantees demo’s expected balances.

The same accounting principle applies when the connection times out after the provider may have committed. Retrying with a fresh operation ID does not make the earlier effect disappear. For shared operations, unknown outcomes must be reconciled before retry, even when the ordinary provider contract supports an idempotent retry strategy.

Confirmed definitive effects commit the entire reservation. Unknown, partial and conflicting outcomes retain it. Capacity is released only when protected history establishes that every potentially dispatched attempt is definitively absent, or an unstarted attempt has been safely closed. Run completion, cancellation, restart and elapsed time do not refill the ledger.

The first accepted definitive observation seals a shared attempt. Later contradictory facts are refused and signed as incident evidence, rather than rewriting a balance that may already have been reused. This makes the source of finality a serious trust boundary: authenticated providers and authorized operators can still be wrong.

An operator’s artifact reference is an attributable assertion. The runtime does not independently fetch and verify the cited document. Recovery procedures must therefore define who may assert absence, what evidence they need, and how to establish that the effect cannot still apply.

Configuration is part of the invariant

A protected ledger helps only while deployments address the same ledger under the same meaning.

Suppose a replica changes resource_pointer under an existing guarantee ID. It could start mapping an action to a different resource and create apparently fresh capacity. ContextOS pins the complete semantic definition by tenant and guarantee ID before extracting the resource. A changed pointer, capability set, unit or ceiling under that identity fails closed, including for a newly encountered resource.

That protects against semantic drift under the same identity. Renaming or removing a guarantee, omitting it from a replica, or changing stores can still escape the enforcement domain. Deployment configuration remains a trusted operational responsibility. The first version has no live guarantee-migration API.

The ledger also retains at most 1,024 operation receipts per resource, including released receipts. Saturation blocks new operations. Deleting receipts or adding a TTL to regain capacity would discard the history needed to reject stale attempts. Accounted rollover and dynamic balances are future work, rather than invisible fallback behavior.

What signed evidence establishes

The runtime uses Ed25519-signed, hash-chained audit records. Shared-exposure events include reservation, refusal, settlement requests, settlement completion and refused observations. The offline verifier can check an exported chain against trusted keys and its stated anchor.

ctx audit-verify --entries entries.json --keys keys.json

This lets a reviewer establish the integrity of the recorded sequence relative to that trust anchor. It does not establish that the provider told the truth, that no credential bypass existed, or that the deployment captured every external effect.

DecisionRecords and replay packets connect decisions to their evidence. The portable specification remains normative; the Rust runtime checks its semantics against golden vectors generated from a pinned TypeScript reference snapshot. The conformance provenance explains how to reproduce that comparison.

Vector agreement establishes reference parity for those cases. Deployed conformance needs evidence for the actual workflow, implementation, release and environment: useful positive work, required denials, injected faults and the relevant operational controls. A passing pure transition test cannot establish PostgreSQL isolation or a provider’s recovery behavior.

Run the first example, then challenge its assumptions

With Git, the repository’s pinned Rust toolchain, Python 3.9 or newer, Bash and curl, run the source demo at the reviewed revision:

git clone https://github.com/contextosai/ContextOS.git
cd ContextOS
git checkout a61a24776e38b62709168915b3a1f37ffb38b157
./examples/shared-guarantees/run.sh

The script builds the server and CLI, starts synthetic loopback services, races two separately admitted agents, demonstrates pending exposure, queries the provider and exports the audit for offline verification. It asserts both balances and actual synthetic provider call counts. No model API key or payment account is required.

The demo uses in-memory storage and development credentials. Its published runtime key serves as the local verification anchor. For an integration, independently trusted keys, durable storage and real provider semantics need their own verification. Release archives offer a path without compiling Rust; download v0.1.0-alpha.2 and follow its checksum and provenance instructions. (This article originally pointed to the alpha.1 instructions; alpha.1’s Linux archives need glibc 2.38.)

Before expanding a workflow, make its failure cases observable:

ExperimentRequired observation
Race unrelated runs against one resourceAggregate committed plus held exposure stays within the ceiling; refused work makes no provider call
Pause a worker before dispatch; recover concurrentlyA closed exact attempt cannot later activate
Lose a response after provider commitExposure remains held until accepted reconciliation; no blind repeat effect
Fail the settlement writeReconciliation repairs accounting from protected history without invoking the effect again
Change the configured pointer under the same guarantee IDDefinition mismatch blocks the call
Present contradictory final observationsThe accepted final fact stays sealed; the contradiction becomes incident evidence

These are evaluation targets for the implementing environment, not claims that this article ran those experiments. Measure useful completion and stranded exposure alongside denials. A boundary that preserves a ceiling but cannot recover useful capacity still has operational work left.

Where to read the code

QuestionSource at the reviewed revision
What is the pure shared-exposure state machine?contextos-kernel/src/shared_exposure.rs
How are definition pins, operation links and signed reservations wired together?contextos-gateway/src/shared_guarantees.rs
Where do ordinary authorization and operation claims happen?contextos-gateway/src/lib.rs
What does revision-checked persistence mean?contextos-store/src/lib.rs
How does the runnable example assert provider calls and balances?examples/shared-guarantees/demo.py

The useful first adoption is one consequential capability with an explicit business resource, a configured ceiling, a protected store and a provider recovery contract you can test. Keep the existing framework. Put the credentials and every relevant effect behind the governed boundary. Then test the races and crashes that a successful single-agent demonstration never exercises.

Found this useful? Share it.

Share:XBSMRedditHNEmail

Continue through the same topic without returning to the index.

View the series