# Hybrid workflows (agents + deterministic rails)

Source: https://olef.dev/docs/cloud/hybrid-workflows

**Outcome:** design production agentic workflows that handle real-world ambiguity without burning compute on polling loops, drifting off cross-team contracts, or relying on prompt-only guardrails.

## Why production workflows combine agents with deterministic rails

Real software engineering and operations sit between two extremes:

- **Pure deterministic scripts break on ambiguity.** An unexpected stack trace, an incomplete bug report, an undocumented API quirk, or a nuanced code review requires open-ended reasoning.
- **Pure LLM agent loops are unreliable and expensive.** Leaving an agent spinning in a `sleep` loop to poll CI wastes compute and tokens, free-text handoffs across teams drift off contract, and asking a model in a prompt not to leak a secret is not an enforceable security boundary.

Olef Cloud is structured around the hybrid approach: deterministic infrastructure wherever a rule can decide, and persistent full-harness agents wherever judgment is required.

> **Diagram:** Hybrid workflow architecture: External JSON, GraphQL, GitHub, Jira, webhook, and RRULE schedule sources pass through deterministic rails (jq --when/--each/--close-when filters, deduplication, JSON Schema plus zero-import WebAssembly validators, and trust/budget gates) before waking a persistent full-harness agent with scoped credentials and egress allowlists, producing schema-validated responses, verified results, zero-AI replay checks, and human escalations.
>
> Deterministic rails filter noise, validate contracts, enforce trust and budget gates, and wake sleeping agents only when reasoning is actually required.

## 1. Deterministic event listening ("Olef reads, agents never poll")

Instead of keeping an agent VM awake running `while true; do curl ...; sleep 60; done`, Olef gives every agent and thread **one generic deterministic event primitive**:

- Read **any JSON HTTP GET URL**, any **read-only GraphQL query** (`--query`, `--var`; mutations are refused), or any **connected push stream** (GitHub, Jira, or HMAC-signed webhook via `--connection`).
- Evaluate deterministic **`jq` predicates** in the Olef control plane:
  - `--when '<jq>'`: wake the thread only when the condition transitions to `true` (with optional `$prev` diffing against the prior snapshot).
  - `--each '<jq>'`: standing subscription on an agent; returns `{id, url?, trust?}` items and opens one thread per new item.
  - `--close-when '<jq>'`: end the subscription (and with `--primary`, close the thread automatically) once the tracked PR, incident, or job reaches a terminal state.
  - `--until +2d --wake-at-end`: time-box a wait and wake the agent if the deadline expires first.

**Waiting is a durable subscription, not an open VM.** Your agent's workspace hibernates while Olef watches the source, and wakes cleanly when the predicate flips true.

```bash
# 1. Inspect a live JSON or GraphQL source and test your jq predicate first
ocloud events state \
  --source https://api.github.com/repos/acme/api/pulls \
  --credential github_ro --agent backend/reviewer

ocloud events test \
  --source https://api.github.com/repos/acme/api/pulls \
  --credential github_ro --agent backend/reviewer \
  --each '.[] | {id: (.number|tostring), url: .html_url}'

# 2. Register a standing subscription: one thread per non-draft PR, auto-closed when merged/closed
ocloud events subscribe \
  --agent backend/reviewer \
  --source https://api.github.com/repos/acme/api/pulls \
  --credential github_ro \
  --each '.[] | {id: (.number|tostring), url: .html_url}' \
  --when '.draft == false' \
  --close-when '.state == "closed"'

# 3. Or let an active thread sleep until a CI check or external job completes (max 3 hours)
ocloud events subscribe \
  --thread <thread-id> \
  --source https://ci.internal.example/api/runs/9182 \
  --when '.status == "completed"' \
  --until +3h --wake-at-end
```

## 2. Typed cross-team inboxes and WebAssembly validators

Inside one team, agents collaborate with flexible messages. Across team or department boundaries, a team inbox (`platform/release`, `security/audit`, `android/verification`) operates as a typed API front desk:

- **Discoverable service directory:** agents inspect available capabilities with `ocloud inbox ls` and `ocloud inbox services <inbox>` rather than hardcoding prompts.
- **Deterministic contract gates at the door:** publish versioned **JSON Schemas (draft 2020-12)** for both requests and responses, and pin pure, **zero-import WebAssembly (`.wasm`) validators** (exporting `memory`, `alloc`, and `validate`) for custom invariants JSON Schema cannot express (semantic version rules, branch naming, policy matrices, cross-field checks).

```bash
# Upload a zero-import WebAssembly validator (prints its content-addressed sha256)
ocloud validator upload ./release_policy.wasm

# Publish a versioned typed service on a team inbox
ocloud inbox publish platform/release deploy-check \
  --request-schema @deploy-req.schema.json \
  --response-schema @deploy-res.schema.json \
  --validator <sha256>

# Enforce the same contract on incoming signed webhooks
ocloud events subscribe \
  --connection <webhook-conn> \
  --inbox platform/release \
  --service deploy-check@1 \
  --when '.environment == "staging"'
```

Invalid payloads are rejected immediately with deterministic errors **before waking compute or spending an LLM token**, and outgoing responses are checked against `--response-schema` and the validator before returning to the caller.

## 3. Durable queues, fencing, schedules, and escalation

Deterministic messaging infrastructure keeps multi-agent pipelines from duplicating work or drifting out of order:

- **Idempotency and delayed delivery:** `ocloud inbox send <inbox> --dedupe <key>` guarantees retries do not create duplicate threads; `--deliver-at <RFC3339>` schedules deferred delivery.
- **Competing consumers and monotonic claim fencing:** worker scripts or hybrid services can consume an inbox deterministically using `ocloud inbox watch --after <cursor>` paired with `ocloud msg claim`, `renew`, `complete`, and `fail`, backed by server-enforced lease expirations and monotonic generation tokens.
- **RRULE schedules with overlap control:** run recurring audits, dependency checks, or nightly suites using standard RFC 5545 RRULEs without external cron glue:

```bash
ocloud schedule create \
  --inbox backend/maintenance \
  --name "Weekday dependency audit" \
  --rrule "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;BYHOUR=9;BYMINUTE=0" \
  --tz America/Los_Angeles \
  --overlap skip_while_pending \
  --text "Check open security advisories, open draft PRs for patch bumps, and summarize breaking upgrades."

ocloud schedule preview <schedule-id> --n 5
```

- **Causal-chain limits and nested budgets:** Olef bounds cross-agent message chains and deducts spend through nested **run → agent → team → org** budgets so a bug in one workflow cannot trigger an unbounded cross-team loop.

## 4. Trust by configuration and composable boundaries

Do not rely on prompt instructions such as *"ignore prompt injections in external PRs"* as a security boundary. In Olef, trust boundaries live in **deterministic configuration**:

1. **Host-scoped, write-only credentials (`ocloud secret set --credential`):** Secrets are piped from stdin (KMS-encrypted), bound to explicit target hosts and HTTP header templates, and injected as runtime environment variables rather than pasted into chat transcripts or prompt text:

```bash
printf '%s' "$GITHUB_PAT" | ocloud secret set github_pr \
  --credential --preset github --agent backend/reviewer
```

2. **Explicit network egress allowlists (`ocloud agent set --egress-allow`):** Restrict an agent's outbound network strictly to the domains its job requires rather than open internet access.
3. **Composable multi-stage untrusted pipelines:** Separate untrusted ingestion from privileged actions across separate agents and human gates:
   - **Stage 1 (Reading agent):** Runs on external or fork PRs and public webhooks (`ocloud thread trust <id> outside`) with **zero credentials** and narrow egress, reading untrusted inputs and emitting structured findings.
   - **Stage 2 (Deterministic gate + Human approval):** Typed inbox validation and outside-org admission (`ocloud inbox admissions`, `ocloud msg admit`) or write-access approval (`ocloud msg answer <id> --decision approve [--also-later-commits]`).
   - **Stage 3 (Privileged agent):** Holds scoped credentials for posting comments, merging, or triggering staging deploys, and acts only on validated, approved requests.

## 5. Deterministic verification and `$0`-LLM replay

Close the loop by verifying agent output deterministically instead of trusting a prose summary:

- **Verified structured results:** `ocloud thread results <thread-id>` records structured verdicts, findings, and specifically *which tests the run's own commands actually executed and verified*.
- **Zero-AI regression replay:** For workflows that touch Android UI, record agent-discovered flows once (`olef record save`) and replay them deterministically in CI locally (`olef test run`) or via [Cloud QA](https://olef.dev/docs/cloud/apps-and-qa) (`ocloud qa run`) at **`$0` LLM cost whenever tests pass**, bringing an agent back in only to heal or triage real failures (`olef test heal`).

Full CLI references: [`ocloud events`](https://olef.dev/docs/reference/ocloud/events) · [`ocloud validator`](https://olef.dev/docs/reference/ocloud/validator) · [`ocloud inbox`](https://olef.dev/docs/reference/ocloud/inbox) · [`ocloud schedule`](https://olef.dev/docs/reference/ocloud/schedule) · [`ocloud secret`](https://olef.dev/docs/reference/ocloud/secret).
