{"version":"v0.2.0-alpha","pages":[{"path":"/examples/01-echo","title":"Echo: one graph, two worlds","description":"Run one graph with a real cat process or scripted Lab responses, then inspect a recording without starting the process again.","text":"---\ntitle: \"Echo: one graph, two worlds\"\ndescription: Run one graph with a real cat process or scripted Lab responses,\n  then inspect a recording without starting the process again.\nurl: https://docs.rastok.com/examples/01-echo\nsource_revision: v0.2.0-alpha\n---\n\n# Echo: one graph, two worlds\n\nA line of text enters the program, and a real `cat` program, which repeats\nwhat it reads, sends it back. The line leaves the App through its output.\n\nThere are two ways to run this program: the real world (App) starts `cat`;\nthe virtual world (Lab) supplies its responses from a mock. The graph stays\nthe same. You can test its success, filtering and timeout before starting\nan external process.\n\nThe three [file formats](/guide/09-command-line.md#file-formats) have different\njobs: `.rkg` is the program and its Lab, `.rkc` is a scenario's reference\ntrace, and `.rkr` is a recording of a real execution.\n\n## Run\n\nFrom the repository root, with `rastok` installed:\n\n```sh\nrastok simulate examples/echo.rkg --compare examples/traces/echo\n```\n\n```text\nPASS smoke.roundtrip\nPASS smoke.filtered\nPASS smoke.silence_expires\n3 scenario(s), 0 failed\n```\n\nThis reads `examples/echo.rkg` and compares each scenario with its reviewed\nfile in `examples/traces/echo/`. The command starts no external process and\nwrites no reference trace.\n\nTo inspect the same scenario, use a binary built with `hosted-ui`:\n\n```sh\nrastok simulate examples/echo.rkg --compare examples/traces/echo --ui\n```\n\nOpen the complete URL printed by the CLI and keep it private. In Terminal\non macOS, hold Command and double-click the URL to open it. If your terminal\ndoes not open links, copy the complete URL into your browser instead.\nThe [debugger tour](/debugger.md) explains its controls and source view.\n\n## Read the program\n\nOpen `examples/echo.rkg` and read from top to bottom.\n\n`graph echo : App` declares the application. It contains a Connector and\nan Operator, with wiring between their ports.\n\nThe Connector `shell : Process` talks to an external program under the\n[Process contract](/reference/connectors/process.md).\nHere `mode = job` starts a child for each Call, `command = \"cat\"` selects the\nprogram, and `codec = lines` exchanges lines of text. `timeout = duration(\"5s\")`\nbounds the wait. The declarations of idempotence and deterministic behavior\ndescribe the repetition guarantee and the expected behavior of this command.\n\nThe Operator `relay` does not start a process. Its `on in where data != \"\"`\nhandler accepts a nonempty input and emits that data on `out`. An empty line\nproduces no output.\n\nThe wiring `in -> relay -> shell -> out` sends the App input to `relay`,\nthen to `shell`, then to the App output. The two remaining outputs,\n`shell.err` and `shell.exit`, go to `nothing`: the program explicitly\ndiscards them. They still exist in the journal and can be checked by the Lab.\n\nBelow the App, `lab smoke` describes the virtual world. It contains the\nshared mock and scenarios directly; no intermediate simulation block is needed.\n\n`mock shell` supplies the process response. In `on in { ... }`, `out = .`\nmeans “emit the data this mock received”: the dot is the received data, so the\nmock echoes it. `exit = Exited { exit_code = 0, signal = null }` then ends\nthe simulated process successfully. See [mock responses](/reference/lab.md#mock-responses)\nfor the other forms.\n\nThe scenarios are independent:\n\n- `roundtrip` sends `\"hello\"`; `expect app.out == \"hello\"`\n  requires exactly one matching App output, then `expect shell.err == nothing`\n  requires no error output.\n- `filtered` sends `\"\"`; `expect shell.in == nothing` and `expect app.out == nothing`\n  check that the empty line reaches neither the process nor the App output.\n- `silence_expires` replaces the shared mock with `out = nothing`, providing no\n  terminal response; `advance duration(\"5s\")` moves virtual time and the final\n  expectation checks `TimeoutExpired` on `shell.exit`.\n\nAn [expectation](/reference/lab.md#expectations-and-windows) examines the\nobservations since the preceding input or time advance. It does not consume\nthem, so successive expectations can inspect the same window.\n\n<a id=\"graph\"></a>\n\nSource: `examples/echo.rkg`\n\n```rkg\n// A nonempty line goes to cat and comes back on the App output.\n// The Lab tests the echo, an empty line and a child that never answers.\n\n\ngraph echo : App {\n  connector shell : Process {\n    mode = job ; command = \"cat\"\n    codec = lines\n    idempotent = true; behavior = deterministic\n    timeout = duration(\"5s\")\n  }\n\n  operator relay {\n    on in where data != \"\" {\n      out = data\n    }\n  }\n\n  in -> relay -> shell -> out\n  shell.err -> nothing\n  shell.exit -> nothing\n}\n\nlab smoke {\n  mock shell {\n    on in {\n      out = .\n      exit = Exited { exit_code = 0, signal = null }\n    }\n  }\n\n  scenario roundtrip {\n    app.in = \"hello\"\n    expect app.out == \"hello\"\n    expect shell.err == nothing\n  }\n\n  scenario filtered {\n    app.in = \"\"\n    expect shell.in == nothing\n    expect app.out == nothing\n  }\n\n  scenario silence_expires {\n    mock shell {\n      on in { out = nothing }\n    }\n    app.in = \"hello\"\n    advance duration(\"5s\")\n    expect shell.exit == TimeoutExpired {}\n  }\n}\n```\n\n## Expected result\n\nThe roundtrip scenario follows this sequence, with the Lab supplying the\nresponse instead of starting `cat`.\n\n```mermaid\nsequenceDiagram\n    participant lab as Lab: smoke.roundtrip\n    participant app as echo\n    participant relay as relay\n    participant shell as shell: Process\n    lab->>app: in = hello\n    app->>relay: in = hello\n    relay->>shell: out to in = hello\n    shell->>lab: Scripted Call request\n    lab-->>shell: out = hello, exit = Exited(0)\n    shell-->>app: out = hello\n    Note over shell: Exited is disposed to nothing\n```\n\nTo run in the real world, use a macOS or Linux shell with `cat` on PATH.\nThe following command starts `cat` and writes `echo.rkr` in your current\ndirectory. A recording captures the real execution so it can be inspected\nwithout starting that process again. Use an unused filename: existing\nrecordings are never overwritten.\n\n```sh\nprintf 'hello\\n' | rastok run examples/echo.rkg --record echo.rkr\n```\n\n```text\nhello\nrecorded: 8 causal records · seal 80f1263274f3b1b7480fdb13c007459e18e1e4cf10cc9bf08b5d12b63a4b7e0e\n```\n\nEcho has one App output, so stdout contains the value alone. The `recorded:`\nsummary goes to stderr. Now inspect the recording:\n\n```sh\nrastok replay echo.rkr\n```\n\n```text\nreplay: 8 causal records · seal 80f1263274f3b1b7480fdb13c007459e18e1e4cf10cc9bf08b5d12b63a4b7e0e · completed recording · no Driver I/O\nhello\n```\n\nReplay needs neither the original source nor `cat`. Its summary goes to\nstderr; the output value goes to stdout. The matching seals describe the\nsame recorded execution, not a new call to the outside world. The seal above\nis from one run; compare your replay with the seal printed by your own run.\n\nA Lab execution and a real run do not have equal raw seals by default:\ntheir input provenance differs, and real response timing can differ from\nvirtual time. Here the proof is equality between the real run and its\nrecorded replay.\n\n## Break it\n\nIn `mock shell`, change exactly `out = .` to `out = \"changed\"`.\nLeave the expected value `\"hello\"` unchanged. Run:\n\n```sh\nrastok simulate examples/echo.rkg --compare examples/traces/echo\n```\n\n```text\nFAIL smoke.roundtrip\n     expect app.out == \"hello\"  (echo.rkg:34)\n     observed app.out: \"changed\"\n     expected 1 matching delivery on app.out, but observed 0\n     golden divergence: record 6: closure(32)[1][0][1][1]; expected 82066568656c6c6f; got 8206676368616e67…(10 bytes); cause: EGRESS \"shell\" · emitting_id 801cfc175b8f2151…(16 bytes) · call_key absent\nPASS smoke.filtered\nPASS smoke.silence_expires\n3 scenario(s), 1 failed\n```\n\nRestore the checked-in source:\n\n```sh\ngit checkout -- examples/echo.rkg\n```\n\nThat command discards your edits to this example. Then run the complete\ncomparison again:\n\n```sh\nrastok simulate examples/echo.rkg --compare examples/traces/echo\n```\n\nIt prints the same three PASS lines and zero-failed total shown under Run.\n\n## Read the golden difference\n\nThe expectation names the source line, the observed `\"changed\"` value and\nthe failed count. The golden difference names the first differing record,\nits field, the expected and actual encoded values, and the Call that produced\nit. Those are two checks: the assertion checks the authored expectation;\nthe trace comparison checks the reviewed causal history. Do not save a new\nreference merely to make the comparison pass.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/echo/smoke.roundtrip.rkc`\n\n```rastok-trace\na6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024882066568656c6c6f09636c61620a000b000d81826c2e696e3e72656c61792e696e824982816572656c61798000\na7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na80702116572656c617912824982816572656c6179800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000\na80702116572656c617912824982816572656c617980001364703a696e1481836c2e696e3e72656c61792e696e82438280800001178183636f757400a50150801cfc175b8f2151fe076d50a05c2b580250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024882066568656c6c6f1818818201502d4efb509bf4e072a22ea0314c1c7ee11819818350801cfc175b8f2151fe076d50a05c2b587272656c61792e6f75743e7368656c6c2e696e82498281657368656c6c8000\na8070211657368656c6c1282498281657368656c6c800013676c3a737461727414801780181a50801cfc175b8f2151fe076d50a05c2b581822824382808000\na60703181b50801cfc175b8f2151fe076d50a05c2b58181c657368656c6c181e58208e4c7c1b99dbfd50e7a95185fead5ee1448fa904a2fdd778eaf5f2dbfd629a99181f0118217272656c61792e6f75743e7368656c6c2e696e\na70703181b50801cfc175b8f2151fe076d50a05c2b58181c657368656c6c181e58208e4c7c1b99dbfd50e7a95185fead5ee1448fa904a2fdd778eaf5f2dbfd629a99181f02182082018282636f757482024882066568656c6c6f8264657869748202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618217272656c61792e6f75743e7368656c6c2e696e\na6070211657368656c6c1282498281657368656c6c80001364703a696e1481837272656c61792e6f75743e7368656c6c2e696e824982816572656c6179800001178283636f757400a50150233ee7a209d98e59c5f7b3aa16a9345a0250801cfc175b8f2151fe076d50a05c2b580350f3df1105112054d397a04ed0666ca4c804010582024882066568656c6c6f83646578697400a501509403fe6e10f58d02bd0e61df7a9d3e760250801cfc175b8f2151fe076d50a05c2b580350f3df1105112054d397a04ed0666ca4c80401058202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f6\nseal 7e20cb99d172b4d2816136dfab6e60fadc99e592aa754a520059e2d4bfea5ea9\n```\n\n</details>\n\n## Carry forward\n\nFor the concepts behind this example, read [A program](/guide/01-a-program.md)\nand [The Lab](/guide/04-the-lab.md).\n\nAn injected fault belongs to the virtual world (Lab); the application stays\nthe same as in the real world (App). Keep that distinction when a partner\nenvironment is not available yet.\n\nNext: [File pipeline](/examples/02-file-pipeline.md). Replace the external program with\ntwo file operations and ask what each effect is allowed to do.\n\n## Limits\n\nReference traces contain causal evidence. Recordings are bounded local\ndiagnostics, not durable deployment journals or share-safe exports. The\nrecorder currently refuses personal-data plans and boot-dependent deployment\nprofiles. Diagnostic replay reconstructs recorded facts; it does not execute\na Lab scenario.\n"},{"path":"/guide/01-a-program","title":"A program","description":"Read a complete Rastok program by separating its Graph, Operators, Connectors, wiring and Lab.","text":"---\ntitle: A program\ndescription: Read a complete Rastok program by separating its Graph, Operators,\n  Connectors, wiring and Lab.\nurl: https://docs.rastok.com/guide/01-a-program\nsource_revision: v0.2.0-alpha\n---\n\n# A program\n\nAfter this chapter you can read a small `.rkg` file, identify where its\ndecisions and external work belong, and check its wiring without starting\nthe external program.\n\n## Start with one boundary\n\nOpen `examples/echo.rkg` in the checkout. Its first declaration is a Graph\nnamed `echo`. A Graph contains children and the connections between them.\nIt also defines the boundary through which the surrounding program can send\nand receive data. Its children own the application handlers and private\n`var` state.\n\nThe `: App` annotation attaches the App Extension. It marks this Graph as\nthe public root of the compiled unit. There must be exactly one such root\namong the files compiled together. A unit can span several files; this\nexample fits in one.\n\nThis is the complete Graph, from `examples/echo.rkg`, lines 5–22:\n\n```rkg\ngraph echo : App {\n  connector shell : Process {\n    mode = job ; command = \"cat\"\n    codec = lines\n    idempotent = true; behavior = deterministic\n    timeout = duration(\"5s\")\n  }\n\n  operator relay {\n    on in where data != \"\" {\n      out = data\n    }\n  }\n\n  in -> relay -> shell -> out\n  shell.err -> nothing\n  shell.exit -> nothing\n}\n```\n\n## Read declarations before connections\n\nThe `relay` Operator owns the decision. Its handler reacts to an envelope\non `in`; `data` refers to that envelope's payload. The guard rejects the\nempty string. On the accepted path, assigning to `out` emits the payload.\nOperators perform pure computation and may keep declared private state; this one\nneeds none.\n\nThe `shell` Connector owns the external boundary. `Process` names its\nContract, while `mode = job` selects a finite child-process invocation.\n`command` and `codec` describe the requested external work and framing.\nThe timeout bounds waiting for that invocation. The compiler checks these\nsettings against the Process Contract.\n\nA Driver implements the Contract. With `run`, the physical Process Driver\nstarts `cat`. With `simulate`, a Lab mock supplies its outcomes. The\nOperator and the wiring remain the same.\n\n## Account for every possible output\n\nThe final three lines are the wiring. `->` carries values in one direction.\nA bare Node name in a route means its `out` port as a source and its `in`\nport as a destination; any other port is written `node.port`.\nAn Operator input reached by a route needs an `on` handler or a join that\nnames it. The App input feeds\n`relay`, its accepted output feeds `shell`, and the echoed text crosses the\nApp output boundary.\n\nThe two remaining outputs matter. Process `err` carries stderr, while\n`exit` carries the typed terminal outcome of the invocation, including a\ntimeout. Both are explicitly sent to `nothing`. That is a deliberate\ndiscard, not an unwired output that the runtime happens to ignore.\n\nEvery output the compiler considers possible needs a destination. A\nstatically proven impossible output is exempt. Removing either discard\nfrom this Graph produces `E-UNWIRED-OUTPUT`. A discarded emission remains\nvisible in the journal and in Lab expectations. The journal is not a log\nordered by the clock: it links each output to the decision and the input\nthat caused it; the [Overview](/index.md#what-a-run-leaves-behind)\ncontrasts the two.\n\n## Check before running\n\nFrom the repository root:\n\n```sh\nrastok check examples/echo.rkg\n```\n\nThe command checks the source and reports its Node count and semantic hash.\nIt does not start `cat`, and it does not write a separate plan file that\nyou must pass to the next command. The accepted plan contains resolved\ntypes, declarations and wiring for the runtime to interpret.\n\nThe rest of this source file is `lab smoke`. It supplies scenarios for the\nsame App, including the empty input and a silent process. Run those with\n`rastok simulate examples/echo.rkg`. Each scenario records the graph's\ntransactions and the scripted boundary outcomes. Adding a scenario does\nnot change the program's semantic hash: the Lab is not deployed.\n\nThe normative sources are [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md) for declarations and\n[`docs/spec/delivery-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/delivery-semantics.md) for output dispositions. The conceptual\nmodel is also explained in `WHITEPAPER.md`, section 2. The current scope\nremains an experimental alpha; read\n[what is available today](/index.md#what-is-available-today) before treating\na successful example as a deployment guarantee.\n\n## Summary\n\n- A Graph contains Nodes and wiring; `App` marks the public root.\n- An Operator decides; a Connector crosses a declared external boundary.\n- Every possible output has an explicit destination.\n- Checking, simulation and real execution are different commands over the\n  same source program.\n\n## Next\n\nContinue with [Types and expressions](/guide/02-types-and-expressions.md) to read\nthe values carried by those connections. For the hands-on mirror, run\n[Echo](/examples/01-echo.md), change its mock and inspect the first golden\ndifference.\n"},{"path":"/","title":"Overview","description":"What Rastok is, what it is for and how it works: a situation every integration team knows, one file that outlives the project, one plan for two worlds, and a journal that explains every run.","text":"---\ntitle: Overview\ndescription: \"What Rastok is, what it is for and how it works: a situation every\n  integration team knows, one file that outlives the project, one plan for two\n  worlds, and a journal that explains every run.\"\nurl: https://docs.rastok.com/\nsource_revision: v0.2.0-alpha\n---\n\n# Overview\n\n## What is Rastok?\n\nAn integration rarely breaks on the happy path. It breaks on the edge\ncases: unavailable dependencies, unexpected replies, missing or incomplete\ntests. With AI, writing a flow has never been faster; keeping it correct\nand stable over time is another story. **Rastok is a simulation-first\nintegration platform.** The specification and exhaustive scenarios are\nwritten together, in a dedicated, strict language. The same program runs in\na simulated world, then, without a rewrite, in the real one.\n\nHere the simulated world is the Lab and the real one is the App. One file\nholds the flow, the scenarios that test it, faults included, and a journal\nthat explains each run. Within the supported Contract and Lab profiles, the\nsame checked program runs against scripted partners in the Lab or against\nreal systems in the App, without rewriting the graph.\n\nYou write `.rkg` programs. Rastok itself is written in Rust; you do not need\nRust to use it.\n\nThis page is the map. [Getting started](/getting-started.md) installs the\ntool and opens the two paths: the user guide, or the\n[examples](/examples/01-echo.md).\n\n## What it is for\n\nMost of an integration's life happens in the Lab. Write the flow and its\nscenarios, faults included; simulate; fix, or add a scenario; simulate again.\nThat loop needs no partner environment. Confronting the real systems is slow\nand expensive, so it comes after the simulation, not instead of it:\nacceptance with real Drivers once the scenarios pass, then production, where\nan incident is recorded and comes back into the Lab as one more scenario.\n\n```mermaid\nflowchart LR\n    subgraph lab [\"Virtual world (Lab): where most of the time goes\"]\n        design[\"Design or change: the flow and its scenarios, faults included\"] --> simulate[\"Simulate: scripted partners, virtual time, compared against the goldens\"]\n        simulate --> design\n    end\n    simulate -.->|\"once the scenarios pass\"| acceptance[\"Acceptance: the same program, real Drivers\"]\n    acceptance -.->|\"in production\"| incident[\"Incident: recorded facts, replayed\"]\n    incident -.->|\"one more scenario\"| design\n```\n\n| Moment | What teams usually have | What the file gives |\n|---|---|---|\n| Design | A partner that is not ready, a contract nobody has exercised | A scripted partner in the Lab, with fault scenarios from the first day |\n| Change | The fear of breaking what works | `--compare` against the reviewed goldens, with the first divergence named |\n| Acceptance | A second version of the flow for the real environment | The same checked program, with real Drivers |\n| Incident | Logs that say what happened, not why | Recorded facts, replayed without side effects, then a scenario that reproduces them |\n\nThe alpha does not automatically convert a recording into a Lab scenario:\nwriting the scenario is a human step. Keep it, with its reviewed golden, so\nthe next change can be checked against it.\n\n## At a glance\n\n- Types include exact decimals, timestamps with and without zones, structs, arrays, maps and unions; projections target JSON Schema, Avro, Arrow and OpenAPI. [Types and schemas](/reference/types.md), [guide](/guide/02-types-and-expressions.md)\n- Use `is` to test a typed value, `as?` to try a conversion and `in` to test array elements or map keys. Wiring provides bounded static fan-out. [Expressions and dispatch](/reference/expressions.md)\n- Keys scope instances by tenant, sensor or event, with `persistent`, `idle`, `age`, `once` and `slot` lifetimes, and joins bound waiting. [Instances, state and time](/guide/06-instances-state-and-time.md)\n- Loop can prove termination through a decreasing measure; Retry checks the safe-repetition rule. [Loops and retries](/guide/07-loops-and-retries.md)\n- Typed Contracts define HTTP/1.1 to HTTP/3 (HTTP/3 behind the `hosted-http3` feature), WebSocket, process and file exchanges. [Standard contracts](/reference/contracts.md), [guide](/guide/03-connectors-and-outcomes.md)\n- The Lab supplies mocks, scenarios, virtual time, injected faults and golden traces. [The Lab](/reference/lab.md), [guide](/guide/04-the-lab.md)\n- The journal records execution; recording, replay and the debugger expose those facts for inspection. [Running for real](/guide/05-running-for-real.md)\n- Schema annotations declare personal data, secrets and measurements. [Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md)\n- The core evaluates deterministically, without a clock, network or randomness, on targets without an operating system. [How it works](#how-it-works)\n\n## How it works\n\n### The smallest program\n\n`examples/echo.rkg` is a whole integration in one file. A nonempty line of\ntext enters; under `rastok run`, a real `cat` process echoes it and the echo\nleaves.\n\n```rkg\ngraph echo : App {\n  connector shell : Process {\n    mode = job ; command = \"cat\"\n    codec = lines\n    idempotent = true; behavior = deterministic\n    timeout = duration(\"5s\")\n  }\n\n  operator relay {\n    on in where data != \"\" {\n      out = data\n    }\n  }\n\n  in -> relay -> shell -> out\n  shell.err -> nothing\n  shell.exit -> nothing\n}\n```\n\nThree kinds of Node appear here, and one Extension.\n\n- `graph echo : App` is the **Graph**: a typed boundary, its children and\n  their static wiring. A Graph owns scope and lifetime; it has no\n  application handler. `App` is the **Extension** that marks the public root.\n- `operator relay` is an **Operator**: the decision. A typed transition\n  that may keep private state and never performs external I/O.\n- `connector shell : Process` is a **Connector**: an explicit boundary to\n  the outside, under one exact, versioned **Contract**. A **Driver**\n  implements the Contract: a real process in the App, a script in the Lab.\n- `shell.err -> nothing` and `shell.exit -> nothing` are decisions the\n  compiler can see. Every output the compiler considers possible needs an\n  explicit destination, including `nothing` for a deliberate discard.\n  An output proven impossible needs no destination.\n\nTwo other Extensions exist in the alpha. `Loop` adds finite recurrence\nover time. `Retry` repeats the same outbound Call under a bounded policy\nthe compiler checks. The executable standard Contract families are\n`Process`, `File`, `HttpClient`, `HttpServer`, `WebSocketClient` and\n`WebSocketServer`; `rastok connectors` lists their modes, installed\nimplementations, Lab bindings and untested cases.\n\nThe [standard library reference](/reference/stdlib.md) lists the types,\nContracts, annotations and value frontends available to a program.\n\nThe Lab lives in the same file. This is the scenario that tests the fault\ncase, a process that never answers:\n\n```rkg\nscenario silence_expires {\n  mock shell {\n    on in { out = nothing }\n  }\n  app.in = \"hello\"\n  advance duration(\"5s\")\n  expect shell.exit == TimeoutExpired {}\n}\n```\n\nTime is an input: `advance` moves the virtual clock by five seconds and the\ntimeout becomes a typed fact the scenario asserts. No process starts.\nAdding a scenario changes nothing in the program's identity: the Lab is\npart of the source, not of the semantic hash. The [first example](/examples/01-echo.md)\nruns this file, breaks it and reads the result.\n\n### One source, one plan, two worlds\n\nThe real world (App) and the virtual world (Lab) use different Drivers\naround the same compiled graph and journal semantics.\n\n```mermaid\nflowchart TD\n    source[\"flow.rkg: graph and Lab scenarios\"] --> compiler[\"Compiler: types, wiring, Contracts\"]\n    compiler --> plan[\"One executable plan\"]\n    plan --> lab[\"Virtual world (Lab): scripted outcomes, virtual time\"]\n    plan --> app[\"Real world (App): physical Drivers, elapsed time\"]\n    lab --> journal[\"Journal: what came in, what was decided, what went out\"]\n    app --> journal\n```\n\nEach command compiles the source; `rastok check` validates it, rather than\nwriting a plan file that the other commands require. The compiler rejects an\nill-typed or badly wired graph before it runs. What it accepts becomes a\nplan: tables and expression trees, not generated code. The runtime\ninterprets that plan. `rastok simulate` supplies scripted boundary responses\nand virtual time; `rastok run` uses physical Drivers and explicit elapsed\ntime.\n\nThe core reads no clock, network or randomness: CI checks it for three targets\nwithout an operating system and builds and runs the RP2350 spike under\nCortex-M33 emulation; [Sensor alarm](/examples/05-sensor-alarm.md#carry-forward) states\nthe tested boundary and the physical-board limit.\n\n### The rule that makes two worlds possible\n\nOperators decide. Connectors act. Outcomes return as typed observations\nthat execution records in the journal. This is the conceptual separation,\nnot the signature of a public API:\n\n```text\nstep(plan, state, event) -> (new_state, effect_intents)\n\nDriver execution : effect_intents -> real outcomes\nLab simulation   : effect_intents -> controlled outcomes\n```\n\nThe runtime commits an outbound obligation before asking its Driver to\nperform the effect. A scripted partner can therefore stand in for one that\nis not ready. Supported faults and timeouts become scenarios, while the\nsame checked program can later use real Drivers.\n\n### What a run leaves behind\n\nExecution writes an in-memory journal. It is not a log.\n\n| A log | The journal |\n|---|---|\n| Orders events by the machine clock | Links each output to the decision and the input that caused it |\n| Differs at every run: timestamps, latencies, interleavings | For the same scenario, the same records on another machine, byte for byte |\n| Says what happened; the reader guesses why | Keeps the whole chain from cause to effect |\n\nThat chain is what *causal* means on this site: typed records, in causal\norder, for what came in, what was decided and what went out. Three things\nuse the journal.\n\n```mermaid\nflowchart LR\n    labJournal[\"Lab run journal\"] --> golden[\"Golden trace, versioned with the flow\"]\n    golden --> compare[\"simulate --compare: first divergence\"]\n    appJournal[\"App run journal\"] --> recording[\"--record: diagnostic recording\"]\n    recording --> replay[\"rastok replay: same facts, no Driver I/O\"]\n    labJournal --> ui[\"--ui: paused debugger\"]\n    replay --> ui\n```\n\n- **Golden traces.** A scenario's journal is projected into a canonical\n  trace. Save it, review it and version it with the flow. `rastok simulate\n  flow.rkg --compare <directory>` reports the first divergence for each\n  differing scenario. For the same program, equal ingress provenance,\n  ordered inputs and boundary outcomes, and observable logical time give\n  equal causal facts. Real runs and Lab runs use different ingress\n  provenance by default; matching displayed output alone does not give\n  matching trace seals.\n- **The debugger.** `rastok simulate flow.rkg --ui` starts paused. Forward\n  controls advance the simulation and record transitions; history navigation\n  inspects those recorded transitions. It does not edit the flow or fork\n  another world. `run --ui` is not supported.\n- **Recordings.** `rastok run flow.rkg --record capture.rkr` captures a real\n  run. `rastok replay capture.rkr`, optionally with `--ui`, reconstructs\n  the recorded state without any Driver I/O. Recordings are bounded,\n  sensitive local files, not a durable deployment journal. The current\n  recorder refuses personal-data plans, nonempty deployment attestations\n  and boot-dependent Connector settings.\n\n## What Rastok is not\n\n- Not a durable workflow engine yet. The journal is in memory; durable\n  storage is later work.\n- Not an exhaustive catalogue of ready-made connectors. Six standard\n  Contract families are executable today. `rastok connectors` lists modes,\n  support and installed implementations; declared but non-executable families\n  are marked as deferred.\n- Not a visual designer. The source is text, versioned in Git. The debugger\n  explains recorded execution; it does not edit the flow.\n- Not a proof about the outside world. Passing a simulation does not prove\n  that an external system honors its Contract, or make the alpha\n  production-ready.\n\n## What is available today\n\nChecked for `v0.2.0-alpha`, 1 December 2026. Rastok is experimental.\n`rastok check` requires a lifetime for each keyed node and checks reads\nof array elements and map keys that might be absent. The gallery has eight\nrunnable examples, including the resident gateway and typed HTTP model adapter.\n\nThe deployment journal is in memory. Diagnostic replay restores recorded\nfacts without repeating external effects; it does not restart a stopped\ndeployment. Planned work includes a durable local journal for recovery and\na way to turn a real incident into a replayable Lab scenario. The full\nopening qualification remains in progress. No reading-time claim is made\nbefore independent installation trials.\n\n## Vocabulary\n\n| Term | Meaning |\n|---|---|\n| Graph | Typed boundary, children and wiring; owns scope and lifetime |\n| Operator | Typed transition with private state; no external I/O |\n| Connector | Explicit boundary to an external system, under one Contract |\n| Contract | Exact, versioned interface of a Connector |\n| Driver | Implementation of a Contract: physical in the App, scripted in the Lab |\n| Extension | Protocol attached to one Node; executable here: `App`, `Loop`, `Retry` |\n| Lab | Scenarios that script boundary outcomes, time and faults |\n| Plan | The compiled, executable form of a program |\n| Semantic hash | Identity of the program, independent of formatting and of the Lab |\n| Journal | Typed causal records and unsealed recovery evidence of a run |\n| Golden trace | Versioned canonical projection of a scenario's journal |\n| Recording | Captured real run, replayable without Driver I/O |\n\n## Where to go next\n\nStart with [Authoring rules](/reference/authoring-rules.md) for short examples\nof common refusals. The rest of the Reference covers types, expressions,\nContracts, Lab syntax and diagnostics.\n\n- Install and run a first graph: [getting started](/getting-started.md).\n- The short route through the examples: [echo](/examples/01-echo.md), then\n  [webhook to partner](/examples/04-webhook-to-partner.md).\n- The normative specification and architecture notes live in the repository,\n  under `docs/spec` and `docs/architecture`.\n"},{"path":"/reference/authoring-rules","title":"Authoring rules","description":"Short examples of what check refuses or warns about, what to write, and where to find the rule.","text":"---\ntitle: Authoring rules\ndescription: Short examples of what check refuses or warns about, what to write,\n  and where to find the rule.\nurl: https://docs.rastok.com/reference/authoring-rules\nsource_revision: v0.2.0-alpha\n---\n\n# Authoring rules\n\nUse these pairs when writing a graph or reading a refusal. The left column is\ncode to diagnose, not a template. A warning still allows the graph to run.\n\n| Rule | Refused or warned | Write instead | Diagnostic |\n|---|---|---|---|\n| [Render an integer](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#14-rendering-a-value-as-text) | `data as string` | `string(data)` | `E-EXPR` |\n| [Narrow a uint to int](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md#numeric-widening-and-the-common-type) | `data as int` | `(data as? int).orValue(0)` | `E-EXPR` |\n| [Read an array](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#15-absence) | `data[0]` | `data[?0].orValue(\"none\")` | `E-EXPR` |\n| [Read a map field](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#15-absence) | `data.name` | `data.?name.orValue(\"none\")` | `E-EXPR` |\n| [Read a schemaless JSON object](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#5-narrowing) | `out = data is Receipt` | `val receipt = data as? Receipt; out = receipt != null` | `E-EXPR` |\n| [Initialize state](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md#4-mutable-state-has-one-executor-owner) | `var last: string` | `var last: string = \"\"` | `E-EXPR` |\n| [Test array membership](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#11-compatibility-oracle-and-divergence-ledger) | `data.exists(x, x == \"red\")` | `\"red\" in data` | `E-EXPR` |\n| [Test a map key](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#11-compatibility-oracle-and-divergence-ledger) | `1 in data` | `\"id\" in data` | `E-EXPR` |\n| [Build an array](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#11-compatibility-oracle-and-divergence-ledger) | `[\"a\"] + [\"b\"]` | `[\"a\", \"b\"]` | `E-EXPR` |\n| [Test a string](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#1-expression-contract) | `data.matches(\"^a.*b.*c$\")` | `data.startsWith(\"a\") && data.contains(\"b\") && data.endsWith(\"c\")` | `E-EXPR` |\n| [Choose when a key expires](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md#6-lifetime) | `instance = { key = data }` | `instance = { key = data }; lifetime = { kind = idle; max = duration(\"5m\") }` | `E-LIFETIME-REQUIRED` |\n| [Close an outbound Call](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md#71-the-bounded-closing-contract) | `lifetime = { kind = once }` | `lifetime = { kind = once }; closing = { drain_for = duration(\"1s\"); settle_for = duration(\"1s\") }` | `E-INSTANCE` |\n| [Discard a lost answer](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/delivery-semantics.md#44-recovery--a-triage-not-a-gamble) | `_ => out = \"failed\"` | `_ => nothing` | `W-MATCH-CATCHALL` |\n| [Mock HTTP 204](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md#32-httpclient--outbound-http) | `out = \"body\"; exit = Completed { status = 204 }` | `exit = Completed { status = 204 }` | `E-CONTRACT-REQUIRED` |\n| [Mock HTTP 205](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md#32-httpclient--outbound-http) | `out = \"body\"; exit = Completed { status = 205 }` | `exit = Completed { status = 205 }` | `E-CONTRACT-REQUIRED` |\n| [Describe a codec refusal](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md#32-httpclient--outbound-http) | `exit = DecodeFailed {}` | `exit = DecodeFailed { message = \"expected a status\" }` | `E-PORT-TYPE` |\n\n`int` and `uint` are signed and unsigned 32-bit integers. Either fits a\n`long`; a computed `long` need not fit either narrower type. For an array\nreceived at a port, even index zero might be absent. Choose a fallback only\nif it means something for your application; otherwise handle null separately.\n\nA schemaless JSON codec delivers an object as a map. If it does not fit\n`Receipt`, `receipt` is null. Use `is` for a typed union or its case.\nAn HTTP timeout does not\nprove that the operation failed. If you record an outcome instead of\ndropping it, name each lost-answer case the warning lists before the\nwildcard, even if several cases go to the same destination.\n\nFor example, this handler distinguishes an unknown outcome from a known failure:\n\n```rkg\non in match data {\n  Completed => out = \"answered\"\n  BodyTooLarge | DecodeFailed | OutcomeUnknown | ProtocolFailed | TimeoutExpired => out = \"unconfirmed\"\n  _ => out = \"failed\"\n}\n```\n\nLifetime choices are `persistent`, `idle`, `age`, `slot` and `once`.\nA finite owner with an outbound Connector also declares its closing budgets.\nA 204 or 205 has a terminal but no body. A codec refusal carries a message\nabout the expected data, not a copy of the value received.\n\n## Specified, not shipped\n\n| Not available | Alternative in this release |\n|---|---|\n| The iteration macro `exists` | Use [membership](/reference/expressions.md#operators) for an element or key. |\n| Array concatenation with `+` | Construct the known elements explicitly. There is no general concatenation operator. |\n"},{"path":"/reference/connectors/file","title":"File","description":"Ports, terminal outcomes, settings and qualification evidence for the File connector.","text":"---\ntitle: File\ndescription: Ports, terminal outcomes, settings and qualification evidence for\n  the File connector.\nurl: https://docs.rastok.com/reference/connectors/file\nsource_revision: v0.2.0-alpha\n---\n\n# File\n\n`std/file@1`. One file operation per Call. `read` publishes complete bytes; `replace` stages and atomically replaces one file. Directory operations are outside this Contract.\n\n## Declaration\n\nThis declaration comes from `examples/file-pipeline.rkg`. Place the Connector in a Graph\nand wire its ports; the excerpt alone is not an App. Its App input is\n`string`: each producer of `read_file.in` must supply a string for the\nplain `data as string` in the path setting to be safe.\n\n```rkg\nconnector read_file : File {\n  mode = read\n  path = data as string\n  max_read = \"64KiB\"\n  timeout = duration(\"2s\")\n}\n```\n\nThe [contract index](/reference/contracts.md) explains shared settings, build features\nand the distinction between a Contract, a Lab model and an installed Driver.\n\nSelector: `mode` is required.\n\nCalls on one instance are serialized; [queue time counts toward `timeout`](/reference/execution.md#instances-own-state-not-threads).\n\n| Mode | Driver direction | Exchange | Lab model | Installed in this binary |\n|---|---|---|---|---|\n| `read` | outbound | call | `lab-call` | `file` |\n| `replace` | outbound | call | `lab-call` | `file` |\n\n## Ports and completion\n\n| Mode | Port | Direction | Type rule |\n|---|---|---|---|\n| read | `in` | input | `variant` |\n| read, replace | `out` | output | `array<byte>` |\n| read, replace | `exit` | output | FileExit, below |\n| replace | `in` | input | `array<byte>` |\n\n| Mode | Output cardinality |\n|---|---|\n| read | `out`: exactly one on `Completed`; exactly one final `exit` per Call |\n| replace | `out`: never; exactly one final `exit` per Call |\n\n## Exit union\n\n| Case | Payload | Call visibility |\n|---|---|---|\n| `AtomicReplaceUnavailable` | Empty | before_effect |\n| `Completed` | Empty | after_effect |\n| `InvalidPath` | Empty | before_effect |\n| `IoFailed` | Empty | outcome_unknown |\n| `NotAFile` | Empty | before_effect |\n| `NotFound` | Empty | before_effect |\n| `OutcomeUnknown` | Empty | outcome_unknown |\n| `PermissionDenied` | Empty | before_effect |\n| `ReadLimitExceeded` | `{ limit: ulong }` | after_effect |\n| `TimeoutExpired` | Empty | outcome_unknown |\n\n## Settings\n\n| Mode | Setting | Domain | Presence / default | Latest phase |\n|---|---|---|---|---|\n| read, replace | `path` | `string` | required | invocation |\n| read, replace | `idempotent` | `bool` | `true` | plan |\n| read, replace | `behavior` | `deterministic` | `deterministic` | plan |\n| read, replace | `timeout` | `duration` | optional | instance |\n| read | `max_read` | `ByteSize` | `\"8MiB\"` | plan |\n\nFile paths are logical paths relative to the deployment root. A replacement has no truncate fallback and makes no crash-durability promise. The checker fixes File repetition to idempotent and behavior to deterministic.\n\n## Qualification inventory\n\n`read`: fixture `crates/rastok/tests/conformance_file.rs`. Cases without a portable forced fixture: `PermissionDenied`, `AtomicReplaceUnavailable`, `IoFailed`, `TimeoutExpired`, `OutcomeUnknown`. Related tests: `crates/rastok/tests/file_connector.rs`.\n\n`replace`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/tests/file_connector.rs`.\n"},{"path":"/examples/02-file-pipeline","title":"File pipeline: effects with a contract","description":"Read a bounded file, reject an empty input, count its bytes and atomically replace a second file, then replay without disk access.","text":"---\ntitle: \"File pipeline: effects with a contract\"\ndescription: Read a bounded file, reject an empty input, count its bytes and\n  atomically replace a second file, then replay without disk access.\nurl: https://docs.rastok.com/examples/02-file-pipeline\nsource_revision: v0.2.0-alpha\n---\n\n# File pipeline: effects with a contract\n\nThis program reads a file, counts its bytes and copies nonempty content to another file.\n\nEcho separated computation from the world. Now the world contains files you\ncould overwrite. How do you make the permitted operation, its limits and its\nrefusals visible before the flow runs?\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root, with `rastok` installed:\n\n```sh\nrastok simulate examples/file-pipeline.rkg --compare examples/traces/file-pipeline\n```\n\n```text\nPASS files.copy\nPASS files.empty\nPASS files.utf8\nPASS files.directory\nPASS files.single_byte\n5 scenario(s), 0 failed\n```\n\nFor the controls and source view, see [the debugger tour](/debugger.md).\n\n## Read the program\n\nFind the two [File](/reference/connectors/file.md) Connectors: one reads, one replaces. Their modes describe\ndifferent operations under the same Contract. Between them, the Operator\ndecides whether the bytes should continue. Follow the `exit` routes too:\na refused read has a destination, rather than disappearing into a log.\nThe Lab replaces both file operations, using the same resolved port types.\n\nIn a port declaration, the name after `:` is its payload's type: the values\nit may accept or emit. `output failed: FileExit` declares an output port\nnamed `failed`, not a new type. See the [type reference](/reference/types.md)\nfor the notation. `FileExit` comes from the [standard library](/reference/stdlib.md#types),\nwithout an import or copied declaration; its cases are the ones on File's\n`exit` port.\n\nThe [Lab reference](/reference/lab.md) explains mock responses, expectations\nand observation windows. `advance` supplies virtual time; a mock's terminal\nresponse ends its simulated exchange, not the whole scenario.\n\n<a id=\"graph\"></a>\n\nSource: `examples/file-pipeline.rkg`\n\n```rkg\n// Bounded File read, byte count and empty-file validation, atomic replacement.\n// The deployment root is supplied by --file-root; the Lab never opens a file.\n\ngraph file_pipeline : App {\n  input in: string\n  output bytes_read: int\n  output empty: bool\n  output failed: FileExit // Standard-library type; no import is needed.\n\n  connector read_file : File {\n    mode = read\n    path = data as string\n    max_read = \"64KiB\"\n    timeout = duration(\"2s\")\n  }\n  operator inspect {\n    input in: array<byte>\n    output accepted: array<byte>\n    output bytes_read: int\n    output empty: bool\n    on in match {\n      size(data) > 0 => { bytes_read = size(data); accepted = data }\n      _ => empty = true\n    }\n  }\n  connector write_file : File {\n    mode = replace\n    path = \"copy.txt\"\n    timeout = duration(\"2s\")\n  }\n\n  in -> read_file -> inspect\n  inspect.accepted -> write_file\n  inspect.bytes_read -> bytes_read\n  inspect.empty -> empty\n  write_file.out -> nothing\n  read_file.exit -> match {\n    Completed -> nothing\n    AtomicReplaceUnavailable | InvalidPath | IoFailed | NotAFile | NotFound\n      | OutcomeUnknown | PermissionDenied | ReadLimitExceeded | TimeoutExpired -> failed\n  }\n  write_file.exit -> match {\n    Completed -> nothing\n    AtomicReplaceUnavailable | InvalidPath | IoFailed | NotAFile | NotFound\n      | OutcomeUnknown | PermissionDenied | ReadLimitExceeded | TimeoutExpired -> failed\n  }\n}\n\nlab files {\n  mock read_file {\n    on in { out = base64! { YWxwaGEKYmV0YQo= }; exit = Completed {} }\n  }\n  mock write_file {\n    on in { exit = Completed {} }\n  }\n  scenario copy {\n    app.in = \"input.txt\"\n    expect app.bytes_read == 11\n    expect write_file.in where size(data) == 11\n    expect app.failed == nothing\n  }\n  scenario empty {\n    mock read_file { on in { out = base64! {}; exit = Completed {} } }\n    app.in = \"empty.txt\"\n    expect app.empty\n    expect write_file.in == nothing\n  }\n  scenario utf8 {\n    mock read_file { on in { out = base64! { w6kK }; exit = Completed {} } }\n    app.in = \"utf8.txt\"\n    expect app.bytes_read == 3\n    expect write_file.in where size(data) == 3\n    expect app.failed == nothing\n  }\n  scenario directory {\n    mock read_file { on in { exit = NotAFile {} } }\n    app.in = \"directory\"\n    expect app.failed where data is NotAFile\n    expect write_file.in == nothing\n  }\n  scenario single_byte {\n    mock read_file { on in { out = base64! { eA== }; exit = Completed {} } }\n    app.in = \"single-byte.txt\"\n    expect app.bytes_read == 1\n    expect write_file.in where size(data) == 1\n    expect app.empty == nothing\n    expect app.failed == nothing\n  }\n}\n```\n\n## Expected result\n\nIn `files.copy`, both File Calls use Lab responses; the count is emitted\nbefore the accepted bytes reach `write_file`.\n\n```mermaid\nsequenceDiagram\n    participant lab as Lab: files.copy\n    participant app as file_pipeline\n    participant read as read_file: File\n    participant inspect as inspect\n    participant write as write_file: File\n    lab->>app: in = input.txt\n    app->>read: in = input.txt\n    read->>lab: Scripted read request\n    lab-->>read: 11 bytes, then Completed\n    read->>inspect: out to in = alpha\\nbeta\\n\n    inspect-->>app: bytes_read = 11\n    inspect->>write: accepted to in = the same bytes\n    write->>lab: Scripted replace request for copy.txt\n    lab-->>write: Completed\n    Note over read,write: Completed exits are disposed to nothing\n```\n\nThe Lab supplies `alpha\\nbeta\\n`: eleven bytes. The Operator counts them and\nforwards a nonempty value to the replacement File Connector. Empty input does\nnot overwrite the target. A directory produces `NotAFile`, routed to `failed`.\nThe `utf8` scenario counts `é\\n` as three bytes, not two characters: the\nreader's `array<byte>` port determines how the value is read. `single_byte` supplies\n`x`, exactly one byte, and checks that it reaches the writer rather than the\n`empty` output. This is the smallest input accepted by `size(data) > 0`.\n\nTo exercise real disk I/O, use a macOS or Linux shell with `mktemp`, `printf`\nand `cmp` on PATH. This creates a new temporary directory; both file operations\nare confined to that directory, and the recording uses an unused path:\n\n```sh\ndemo_root=$(mktemp -d)\nprintf 'alpha\\nbeta\\n' > \"$demo_root/input.txt\"\nprintf 'input.txt\\n' | rastok run examples/file-pipeline.rkg --file-root \"$demo_root\" --record \"$demo_root/copy.rkr\"\ncmp \"$demo_root/input.txt\" \"$demo_root/copy.txt\"\nprintf 'changed after recording\\n' > \"$demo_root/input.txt\"\nrastok replay \"$demo_root/copy.rkr\"\n```\n\nThis run printed the following values. Compare the seal from your run with\nthe seal from its replay:\n\n```text\nbytes_read: 11\nrecorded: 12 causal records · seal bfa1df6bc5ab7eaeb42419aa0203af9b5350ee0e4252f96ed4fcb2c4159f7977\n```\n\n`cmp` exited successfully without output. After changing the input file,\nreplay printed:\n\n```text\nreplay: 12 causal records · seal bfa1df6bc5ab7eaeb42419aa0203af9b5350ee0e4252f96ed4fcb2c4159f7977 · completed recording · no Driver I/O\nbytes_read: 11\n```\n\nReplay prints the same recorded output and seal without reading or replacing\neither file. It does not restore the disk to its earlier contents. Use\n`rastok replay \"$demo_root/copy.rkr\" --ui` to inspect the recorded history.\n\n## Break it\n\nChange `size(data) > 0` to `size(data) > 1`. The one-byte input is now\nrejected as empty, but the other four scenarios still pass. Run the comparison:\n\n```sh\nrastok simulate examples/file-pipeline.rkg --compare examples/traces/file-pipeline\n```\n\n```text\nPASS files.copy\nPASS files.empty\nPASS files.utf8\nPASS files.directory\nFAIL files.single_byte\n     expect app.bytes_read == 1  (file-pipeline.rkg:84)\n     nothing observed\n     expected 1 matching delivery on app.bytes_read, but observed 0\n     expect write_file.in where size(data) == 1  (file-pipeline.rkg:85)\n     nothing observed\n     where size(data) == 1 is false for 0 of 0 deliveries; count 0, expected 1\n     expect app.empty == nothing  (file-pipeline.rkg:86)\n     observed app.empty: true\n     expected no deliveries on app.empty, but observed 1\n     golden divergence: record 7: emissions(23)[0][0]; expected \"bytes_read\"; got \"empty\"; cause: TRANSACTION \"inspect\" · trigger \"p:in\" · cause_id absent\n5 scenario(s), 1 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/file-pipeline.rkg\n```\n\n## Read the golden difference\n\nThe first changed Operator transaction names its changed emission and causal\ninput. In `single_byte`, the byte count and writer assertions fail, and the\n`empty` output appears where the scenario expects none. The assertions fail\neven without `--compare`; the golden also locates the first changed record.\n\nA passing scenario tests the inputs and responses it supplies, not every\npossible value. The earlier empty, three-byte and eleven-byte cases could\nnot distinguish `> 0` from `> 1`. The one-byte case adds that boundary to the\nreviewed examples. A golden comparison does not prove two programs equivalent\nfor inputs absent from the Lab. Restore the threshold and compare again.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/file-pipeline/files.copy.rkc`\n\n```rastok-trace\na6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024c820669696e7075742e74787409636c61620a000b000d8182702e696e3e726561645f66696c652e696e824d828169726561645f66696c658000\na7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na807021169726561645f66696c6512824d828169726561645f66696c65800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000\na60703181b50f3df1105112054d397a04ed0666ca4c8181c69726561645f66696c65181e58204871ffb86d08c9280e24baa4c587dad86a9970eee2bdf74bc788acdab0e5dc1f181f011821702e696e3e726561645f66696c652e696e\na70703181b50f3df1105112054d397a04ed0666ca4c8181c69726561645f66696c65181e58204871ffb86d08c9280e24baa4c587dad86a9970eee2bdf74bc788acdab0e5dc1f181f02182082018282636f757482024e82054b616c7068610a626574610a82646578697482025082138269436f6d706c65746564820f801821702e696e3e726561645f66696c652e696e\na707021169726561645f66696c6512824d828169726561645f66696c6580001364703a696e148183702e696e3e726561645f66696c652e696e82438280800001178283636f757400a5015077caecb1cc181b62e2b991b703bb4c7f0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024e82054b616c7068610a626574610a83646578697400a50150b80b3a765394a1c849ad18cc90b9659d0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025082138269436f6d706c65746564820f80181981835077caecb1cc181b62e2b991b703bb4c7f7818726561645f66696c652e6f75743e696e73706563742e696e824b828167696e73706563748000\na807021167696e737065637412824b828167696e7370656374800013676c3a737461727414801780181a5077caecb1cc181b62e2b991b703bb4c7f1822824382808000\na807021167696e737065637412824b828167696e737065637480001364703a696e1481837818726561645f66696c652e6f75743e696e73706563742e696e824d828169726561645f66696c658000011782836a62797465735f7265616400a5015020f4693e7f501632f25c434a0371050b025077caecb1cc181b62e2b991b703bb4c7f0350f3df1105112054d397a04ed0666ca4c804010582024382020b8368616363657074656400a5015099f25f558f929e9517b51ebf3097d40a025077caecb1cc181b62e2b991b703bb4c7f0350f3df1105112054d397a04ed0666ca4c804010582024e82054b616c7068610a626574610a1818818201506da3bb6071d750c9a949a41d80aeadd2181981835099f25f558f929e9517b51ebf3097d40a781e696e73706563742e61636365707465643e77726974655f66696c652e696e824e82816a77726974655f66696c658000\na80702116a77726974655f66696c6512824e82816a77726974655f66696c65800013676c3a737461727414801780181a5099f25f558f929e9517b51ebf3097d40a1822824382808000\na60703181b5099f25f558f929e9517b51ebf3097d40a181c6a77726974655f66696c65181e5820dc84b5f65453acf1d3d8b78ee597a5f8a263f6435219c95886187dbf6d97b09b181f011821781e696e73706563742e61636365707465643e77726974655f66696c652e696e\na70703181b5099f25f558f929e9517b51ebf3097d40a181c6a77726974655f66696c65181e5820dc84b5f65453acf1d3d8b78ee597a5f8a263f6435219c95886187dbf6d97b09b181f02182082018182646578697482025082138269436f6d706c65746564820f801821781e696e73706563742e61636365707465643e77726974655f66696c652e696e\na60702116a77726974655f66696c6512824e82816a77726974655f66696c6580001364703a696e148183781e696e73706563742e61636365707465643e77726974655f66696c652e696e824b828167696e7370656374800001178183646578697400a50150e4b73bb11bac0a9dfe97fefbc0202588025099f25f558f929e9517b51ebf3097d40a0350f3df1105112054d397a04ed0666ca4c804010582025082138269436f6d706c65746564820f80\nseal 50b6357a920f562ed961f967f3fd8bc92b5e91b842e420393244291b24819721\n```\n\n</details>\n\n## Carry forward\n\nThe guide explains the same source in [Types and expressions](/guide/02-types-and-expressions.md)\nand [Connectors and outcomes](/guide/03-connectors-and-outcomes.md).\n\nThe Contract makes an effect reviewable: input, operation, bounds and outcomes\ntravel together. Your application decides what to do with each result. A\nrecording then lets you inspect what happened without repeating those effects.\n\nPrevious: [Echo](/examples/01-echo.md). Next: [Two tenants](/examples/03-two-tenants.md), where the\nnew question is who owns the state when several requests share a graph.\n\n## Limits\n\n`max_read` bounds the complete input: no partial bytes are published on a read\nrefusal. `File` does not implement recursive directory operations, append or\nwatch. Atomic replacement concerns one target and depends on the Driver's\nsupported filesystem boundary; refusals have typed outcomes.\nThe `directory` Lab scenario scripts that result; the real File tests qualify\nthe actual filesystem refusal. The example validates and copies bytes.\n"},{"path":"/getting-started","title":"Getting Started","description":"Install the current Rastok CLI, create a typed graph with a Lab scenario, and inspect a simulation without external services.","text":"---\ntitle: Getting Started\ndescription: Install the current Rastok CLI, create a typed graph with a Lab\n  scenario, and inspect a simulation without external services.\nurl: https://docs.rastok.com/getting-started\nsource_revision: v0.2.0-alpha\n---\n\n# Getting Started\n\nYou write `.rkg` programs. Rastok itself is written in Rust; you do not need\nRust to use it.\n\n## Install and run Rastok\n\n<!-- quickstart:start -->\nRastok is currently in alpha. The release job builds binaries for\n**macOS Apple silicon** and **Linux x86-64**. Windows is not supported.\nThe commands below install\n`v0.2.0-alpha` from its\n[release page](https://github.com/rastok-io/rastok/releases/tag/v0.2.0-alpha).\nCopy the command for your system below into a terminal.\nIt downloads, verifies and installs Rastok.\n\n### macOS Apple silicon\n\nFor Macs with an Apple M-series chip, running macOS 11 or later:\n\n```sh\n( cd \"$(mktemp -d)\" && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz.sha256 && shasum -a 256 -c rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz.sha256 && tar -xzf rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz rastok && mkdir -p \"$HOME/.local/bin\" && install -m 755 rastok \"$HOME/.local/bin/rastok\" ) && export PATH=\"$HOME/.local/bin:$PATH\" && rastok --version\n```\n\n### Linux x86-64\n\nFor 64-bit Intel or AMD systems with glibc 2.39 or later, such as Ubuntu 24.04.\n`uname -m` should report `x86_64`; `ldd --version` reports your glibc version.\nFor Linux ARM64, older glibc or a system using musl, use the source installation\nbelow.\n\n```sh\n( cd \"$(mktemp -d)\" && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz.sha256 && sha256sum -c rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz.sha256 && tar -xzf rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz rastok && mkdir -p \"$HOME/.local/bin\" && install -m 755 rastok \"$HOME/.local/bin/rastok\" ) && export PATH=\"$HOME/.local/bin:$PATH\" && rastok --version\n```\n\nEach command installs `rastok` in `~/.local/bin` for your user account and\nprints `rastok 0.2.0-alpha`. To use it in new terminals, add\n`export PATH=\"$HOME/.local/bin:$PATH\"` to your shell configuration:\n`~/.zshrc` for zsh (the macOS default), or `~/.bashrc` for bash.\n\n### Other platforms and source builds\n\n<details>\n<summary>Installation and contribution instructions</summary>\n\nRastok is written in Rust. You can compile it from source if your platform has\nno prebuilt binary, or if you prefer to build it yourself.\n\nFirst, follow the [official Rust installation instructions](https://rust-lang.org/tools/install/),\nincluding the build tools listed for your system. This also installs `rustup`,\nwhich selects the Rust version, and Cargo, which builds and installs Rust\nsoftware. Open a new terminal and install the version used by Rastok:\n\n```sh\nrustup toolchain install 1.97.1\n```\n\n**Install the published release.** Cargo downloads the sources and dependencies,\ncompiles them on your machine and installs the executable:\n\n```sh\ncargo +1.97.1 install rastok --version 0.2.0-alpha --locked --features hosted-ui,hosted-websocket\nrastok --version\n```\n\n**Modify the source and contribute.** Clone the repository instead, then build\nand run your local copy. For a pull request, fork the repository on GitHub\nfirst and use your fork's URL in the clone command:\n\n```sh\ngit clone https://github.com/rastok-io/rastok.git\ncd rastok\ncargo +1.97.1 run --locked -p rastok --features hosted-ui,hosted-websocket -- --help\n```\n\nCargo builds and runs the executable from your working copy. After editing,\nrepeat this command or replace `--help` with the Rastok command you want to test.\nThe [contribution guide](https://github.com/rastok-io/rastok/blob/main/CONTRIBUTING.md)\nexplains the checks and review process for a pull request.\n\nBoth installation routes include HTTP/1.1, HTTP/2, WebSocket and the debugger;\nHTTP/3 is not included.\n\n</details>\n\n### Create your first application\n\nIn a directory for your work, run:\n\n```sh\nrastok new hello\nrastok simulate hello.rkg --ui\n```\n\nOpen the loopback URL printed by the last command, including its access token.\nThe simulation starts paused. Choose **Next transition**, or **Finish** to\nreach `Hello, world`. The CLI reports `PASS hello.roundtrip_greeting` when the scenario\nfinishes. Close the viewer from its toolbar when done.\n\n### Get the examples\n\nWhether you installed Rastok from an archive or with `cargo install`, fetch\nthe example sources and reference traces at the tag of your binary. This\ncreates a `rastok-examples` checkout; it does not build or reinstall Rastok.\nRun these commands from the directory where you want to keep it (Git is required):\n\n```sh\ngit clone --depth 1 --branch v0.2.0-alpha https://github.com/rastok-io/rastok.git rastok-examples\ncd rastok-examples\nrastok simulate examples/echo.rkg\n```\n\nThe simulation prints three `PASS` lines and `3 scenario(s), 0 failed`.\nIf you already have a checkout at that tag, use it without cloning again.\n<!-- quickstart:end -->\n\nThe [version policy](https://github.com/rastok-io/rastok/blob/main/README.md#versions)\nexplains corrective releases, language changes and the independently numbered formats.\n\n## The file `rastok new hello` writes\n\nThe whole program, nineteen lines: one App graph with typed ports, one\nOperator with a handler, and a Lab with one scenario. No Connector, no\nexternal system.\n\n```rkg\ngraph hello : App {\n  input in: string\n  output out: string\n\n  operator greet {\n    input in: string\n    output out: string\n    on in { out = \"Hello, \" + data }\n  }\n\n  in -> greet -> out\n}\n\nlab hello {\n  scenario roundtrip_greeting {\n    app.in = \"world\"\n    expect app.out == \"Hello, world\"\n  }\n}\n```\n\n`rastok check hello.rkg` answers `ok: 2 node(s)` with the semantic hash;\n`rastok simulate hello.rkg` prints `PASS hello.roundtrip_greeting` and\n`1 scenario(s), 0 failed`. Start from this file rather than from the grammar;\n[Echo](/examples/01-echo.md) then adds a Connector, a mock and a recording.\n\nDebug: follow [The debugger, a guided tour](/debugger.md) for its controls,\nsource view and assertion evidence.\n\nWithout the browser, `rastok simulate hello.rkg` runs the same scenario.\n`rastok new` creates one file with a typed Operator and a Lab; it never\noverwrites an existing file. Change the source on disk, then run it again.\n\nUse `rastok --help` for the command syntax and `rastok --version` to identify\nyour build. The [Command line chapter](/guide/09-command-line.md) explains all\ncommands, options, output streams and exit statuses.\n\nFrom a checkout, continue with [echo](/examples/01-echo.md) for a real Process\nand an effect-free recorded replay. Then follow\n[webhook to partner](/examples/04-webhook-to-partner.md): its command supplies\nthe synthetic deployment profile and can open the same graph with `--ui`.\nNo real server, partner or credential is required for that simulation.\n`rastok run` prints each App output value on its own line when the App declares\none output port. An App with several output ports prints `port: value` instead.\nRead [what `run` waits for](/guide/09-command-line.md#execute-the-app-run)\nbefore using it with a listening Connector or a pending deadline.\nTwo unaided timed installation trials are still required before this\nquickstart is qualified. No elapsed-time claim is made yet.\n\n## Editor support\n\nThe 0.2.0-alpha release includes an installable syntax-highlighting package.\nInstall it in VS Code with:\n\n```sh\ncurl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-dsl-0.2.0.vsix\ncode --install-extension rastok-dsl-0.2.0.vsix\n```\n\nFor VSCodium, use `codium --install-extension rastok-dsl-0.2.0.vsix`.\nThe [editor instructions](https://github.com/rastok-io/rastok/blob/main/editors/vscode/rastok-dsl/README.md)\nexplain how to package a local checkout; they also cover the JetBrains bundle.\nFor Vim or Neovim, load the native runtime from the same checkout as the\nexamples, following the [Vim and Neovim setup](https://github.com/rastok-io/rastok/blob/main/editors/vim/README.md).\nEmacs has a [native Rastok mode](https://github.com/rastok-io/rastok/blob/main/editors/emacs/README.md)\nloaded from that checkout as well.\nThese integrations color source and detect `.rkg` files; they do not provide\ncompletion or type checking. `rastok check` validates the program.\n\n## Three ways to learn\n\nSome people read the book first; others open an example and break it; others\nhand the first step to a coding assistant and read what it wrote. All three\npaths lead to the same place.\n\nKeep [Authoring rules](/reference/authoring-rules.md) open for common refusals,\nworking alternatives and links to the corresponding Reference sections.\n\n- **By the book.** The [user guide](/guide/01-a-program.md) reads the\n  language in order: a program, types and expressions, Connectors and\n  outcomes, the Lab, running for real, instances, recurrence, data policy,\n  then the command line and what to do when a partner's answer is lost.\n- **By example.** Eight examples, each built from a question, with a graph to\n  read, a scenario to run, something to break and the first golden\n  difference to read.\n- **With a coding assistant.** Open your preferred LLM harness or coding\n  agent in an empty directory and give it a specification, for example:\n  *\"Using https://docs.rastok.com/llms.txt, develop a Rastok application and\n  its Lab that meet the following specification: \\<your spec\\>.\"* The\n  documentation tells it how to check and simulate what it wrote; read the\n  result as you would read a colleague's: the compiler and the scenarios are\n  the review.\n\n| Guide chapter | What it explains |\n|---|---|\n| [1. A program](/guide/01-a-program.md) | Graphs, Nodes, ports and wiring |\n| [2. Types and expressions](/guide/02-types-and-expressions.md) | Values and typed decisions |\n| [3. Connectors and outcomes](/guide/03-connectors-and-outcomes.md) | External boundaries and explicit dispositions |\n| [4. The Lab](/guide/04-the-lab.md) | Scenarios, mocks and golden comparisons |\n| [5. Running for real](/guide/05-running-for-real.md) | Deployment and diagnostic replay |\n| [6. Instances, state and time](/guide/06-instances-state-and-time.md) | Ownership, lifetimes and bounded waits |\n| [7. Loops and retries](/guide/07-loops-and-retries.md) | Finite progression and safe repetition |\n| [8. Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md) | Data policy and original quantities |\n| [9. Command line](/guide/09-command-line.md) | Commands, options and exit statuses |\n| [10. When the answer is lost](/guide/10-when-the-answer-is-lost.md) | Distinguishing a lost reply from a refused operation |\n\nAn Operator computes. A Connector is the only thing that touches the outside.\n[Echo](/examples/01-echo.md) shows both in one program.\n\n| Example | Your question | What you learn to keep explicit |\n|---|---|---|\n| [1. Echo: one graph, two worlds](/examples/01-echo.md) | Can I test a flow without starting its external program? | Computation, effects and the Lab |\n| [2. File pipeline: effects with a contract](/examples/02-file-pipeline.md) | What may this flow read or replace, and what happens when it cannot? | Bounded I/O and fault destinations |\n| [3. Two tenants: whose state is this?](/examples/03-two-tenants.md) | Can Alice retry while Bob is already done? | Instance ownership, finite retry and lifetime |\n| [4. Webhook to partner: put it together](/examples/04-webhook-to-partner.md) | Can I qualify an integration before the partner is available? | Admission, validation, deduplication, effects and audit |\n| [5. Sensor alarm: make time an input](/examples/05-sensor-alarm.md) | How do I test an absence, or a day of waiting? | Stateful decisions, timed joins and virtual time |\n| [6. Agent gateway: keep a conversation isolated](/examples/06-agent-gateway.md) | Can Alice and Bob share a graph without sharing a child process? | Resident Sessions, protocol adaptation and exact closure |\n| [7. Countdown: a bounded loop](/examples/07-countdown.md) | Can I prove that repeated work finishes? | Manager commands and a decreasing measure |\n| [8. HTTP model adapter](/examples/08-model-adapter.md) | What usage did the model actually report? | Typed responses, original measurements and absent versus zero |\n\nChapter 6 connects WebSockets to resident Process Sessions: Alice and Bob\nkeep distinct children and correctly addressed JSON replies. Chapter 8 sends\nindependent HTTP jobs and inspects typed usage supplied by the model. A\nscripted answer exercises the adapter; it is not evidence of a real token bill.\n\n## How to use the examples\n\nRead in order, or take the short\nroute: [echo](/examples/01-echo.md), then [webhook to partner](/examples/04-webhook-to-partner.md).\nEvery chapter runs independently from the checkout; no chapter requires files\nor state left by the previous one.\n\nRun the scenario, inspect the graph, make the suggested edit on disk, and read\nthe first golden difference. Restore the edit before continuing. Keep a new\nscenario when you discover a useful failure: it becomes a check for your next\nrevision. The debugger explains recorded execution; it does not edit the flow\nor fork an alternative world.\n\nBy the end, the same ideas apply to a file, a partner API and an agent:\nwho owns the state, where effects occur, what time means, and where each outcome\ngoes. You do not need a different testing model for each integration.\n"},{"path":"/guide/02-types-and-expressions","title":"Types and expressions","description":"Follow typed payloads through guards, narrowing and pure expressions without confusing text, bytes or decoded JSON.","text":"---\ntitle: Types and expressions\ndescription: Follow typed payloads through guards, narrowing and pure\n  expressions without confusing text, bytes or decoded JSON.\nurl: https://docs.rastok.com/guide/02-types-and-expressions\nsource_revision: v0.2.0-alpha\n---\n\n# Types and expressions\n\nAfter this chapter you can read payload types and guarded transitions,\ndistinguish business rejections from evaluation faults, and explain why\ndecoded JSON still needs shape validation.\n\n## Give the payload a shape\n\nA port carries an envelope: `data` holds its payload; `meta` holds provenance\nand application metadata. The payload has one resolved logical type,\ninferred before execution if the port declaration omits it.\n\n`type Name = ...` names a set of allowed values. `output out: Webhook`\nrequires one of those values. See the [type reference](/reference/types.md).\n\nThe webhook example names the shape it needs. This declaration is from\n`examples/webhook-to-partner.rkg`, lines 3–7:\n\n```rkg\ntype Webhook = struct {\n  event_id: string\n  email: string @personal(identifier = true)\n  amount: int\n}\n```\n\nA `Webhook` requires two strings and a signed 32-bit integer. The\nannotation on `email` adds personal-data policy without changing its type.\n\nAn assignment widens if every value fits:\n\n| From | Example destinations |\n|---|---|\n| `int` | `long`, `double`, `decimal` |\n| `uint` | `long`, `ulong`, `double`, `decimal` |\n| `long`, `ulong` | `decimal` |\n| `float` | `double` |\n\n| Peers | Common type |\n|---|---|\n| `u + 1`, unsigned `u` | `uint` |\n| `b ? i : l`, `int` and `long` arms | `long` |\n\nUse `data.d as? int` for a particular `double`: 7.0 gives 7; 7.5 gives\nnull. See the [numeric reference](/reference/types.md#numeric-types).\n\nNamed type declarations are structural aliases: their checked shape matters,\nnot their name. Tagged-union case names remain part of the value. For\n`enum { Pending, Cancelled }`, write `out = Cancelled` where that enum is\nexpected, or compare `data.status == Cancelled`. A conflicting variable name\nis refused.\n\nTypes such as `FileExit` and `ProcessExit` come from the standard library;\nuse them without copying their declarations or importing them. The\n[standard library reference](/reference/stdlib.md#types) lists\nthese names. Modules and explicit imports remain a later design discussion.\n\n## Test before projecting\n\nWith `codec = json`, the webhook listener supplies a `variant`: a decoded\nvalue whose application shape is not yet known. An Operator cannot simply\nread arbitrary members of it. It first tests and narrows the value.\n\nThe validation Operator, from the same file, lines 30–41, separates shape\nvalidation from the business rule:\n\n```rkg\noperator validate {\n  input in: variant\n  output out: Webhook\n  output failed: Failure\n  on in match {\n    data is Webhook => match {\n      data.amount > 0 && size(data.event_id) > 0 => out = data as Webhook\n      _ => failed = Rejected { reason = \"positive amount and event id required\" }\n    }\n    _ => failed = Rejected { reason = \"expected event_id, email and integer amount\" }\n  }\n}\n```\n\n`is` asks whether the value fits a type or union case. On the successful\nbranch, member access such as `data.amount` is checked with the narrower\nshape. `as` requests a conversion that succeeds only for a compatible value.\nThe final `_` branch makes the alternative visible.\n\nThese rejections emit `Rejected` on `failed`. A negative amount is a\nbusiness outcome; malformed JSON is a Connector outcome.\n\nWhen `dossier: Open?` may be absent, use `dossier.?title.orValue(\"No dossier is open\")`.\nA missing array element or map key gives null: `names[?i]`, `counts.?pending`.\nIf the payload might not fit a type, `data as? Webhook` returns the value\nor null. A plain cast needs a proof, as in the successful branch above.\n\nA string can be tested directly: `subject.startsWith(\"RE:\")` checks a\nprefix, `subject.contains(\"urgent\")` a substring, and\n`filename.endsWith(\".csv\")` a suffix. All three return a boolean.\n\n## Keep bytes and text distinct\n\nFile reads produce `array<byte>`. Its inspection Operator, from\n`examples/file-pipeline.rkg`, lines 16–25, accepts only nonempty bytes:\n\n```rkg\noperator inspect {\n  input in: array<byte>\n  output accepted: array<byte>\n  output bytes_read: int\n  output empty: bool\n  on in match {\n    size(data) > 0 => { bytes_read = size(data); accepted = data }\n    _ => empty = true\n  }\n}\n```\n\nThe successful branch emits two values, in source order: a size and the\nunchanged bytes. The alternative emits a boolean and never sends bytes to\nthe writer. `size` on bytes counts bytes. The example's UTF-8 scenario\ntherefore counts three bytes for `é` followed by a newline, not two characters.\n\nPorts can carry timestamps, durations or null alone. `string(duration(\"5s\"))`\nreturns `\"5s\"`; `\"id-\" + string(42)` returns `\"id-42\"`. A typed\n[HttpClient response](/reference/connectors/http-client.md) decodes UTC timestamps.\n\n## Understand the expression boundary\n\nExpressions are pure, deterministic and evaluated under bounds. They do\nnot read a file, contact a server or obtain randomness. Guards such as\nEcho's `on in where data != \"\"` decide whether a handler runs; `match`\nselects an explicit branch inside the transition.\n\nMalformed dynamic text passed to `duration`, `timestamp` or `decimal`\nyields null; a malformed constant is refused at check.\nDivision by zero still faults without committing a partial transaction\nor inventing an `err` output. The Lab runs the same expressions.\n\nThe authorities are [`docs/spec/types.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md), [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) and\n[`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md). This chapter covers the executable examples, not\nevery proposed frontend or codec. See\n[what is available today](/index.md#what-is-available-today) for the alpha limits.\n\n## Summary\n\n- A resolved type is different from an external encoding.\n- `is` tests a shape; `as` performs a checked conversion.\n- Expected rejection is typed application data; evaluation faults are not\n  implicit output ports.\n- Lab and App execute the same Operator expressions.\n\n## Next\n\nRead [Connectors and outcomes](/guide/03-connectors-and-outcomes.md), then try\n[File pipeline](/examples/02-file-pipeline.md). Its empty and UTF-8\nscenarios make the distinction between payload type and representation concrete.\n"},{"path":"/reference/connectors/process","title":"Process","description":"Ports, terminal outcomes, settings and qualification evidence for the Process connector.","text":"---\ntitle: Process\ndescription: Ports, terminal outcomes, settings and qualification evidence for\n  the Process connector.\nurl: https://docs.rastok.com/reference/connectors/process\nsource_revision: v0.2.0-alpha\n---\n\n# Process\n\n`std/process@1`. `job` starts one child per Call and publishes its ordered frames with the exit. `service` opens a resident child per Node instance on first input and reuses it. One exit ends that child, not each application request.\n\n## Declaration\n\nThis declaration comes from `examples/echo.rkg`. Place the Connector in a Graph\nand wire its ports; the excerpt alone is not an App.\n\n```rkg\nconnector shell : Process {\n  mode = job ; command = \"cat\"\n  codec = lines\n  idempotent = true; behavior = deterministic\n  timeout = duration(\"5s\")\n}\n```\n\nThe [contract index](/reference/contracts.md) explains shared settings, build features\nand the distinction between a Contract, a Lab model and an installed Driver.\n\nSelector: `mode` defaults to `job`.\n\nIn `job` mode, Calls on one instance are serialized and [queue time counts toward `timeout`](/reference/execution.md#instances-own-state-not-threads); `service` uses a Session instead.\n\n| Mode | Driver direction | Exchange | Lab model | Installed in this binary |\n|---|---|---|---|---|\n| `job` | outbound | call | `lab-call` | `process-job` |\n| `service` | inbound+outbound | session | `lab-process-service` | `process-service` |\n\n## Ports and completion\n\n| Mode | Port | Direction | Type rule |\n|---|---|---|---|\n| job, service | `in` | input | `codec = lines` → `string`; `codec = jsonl` → `variant`; `codec = bytes` → `array<byte>` |\n| job, service | `out` | output | `codec = lines` → `string`; `codec = jsonl` → `variant`; `codec = bytes` → `array<byte>` |\n| job, service | `err` | output | `err_codec = lines` → `string`; `err_codec = bytes` → `array<byte>` |\n| job, service | `exit` | output | ProcessExit, below |\n\n| Mode | Output cardinality |\n|---|---|\n| job | `err`: zero or more; `out`: zero or more; exactly one final `exit` per Call |\n| service | Zero or more frames and writes; exactly one `exit` per Session |\n\n## Exit union\n\n| Case | Payload | Call visibility |\n|---|---|---|\n| `CaptureFailed` | Empty | outcome_unknown |\n| `DecodeFailed` | `{ line: string?, message: string }` | outcome_unknown |\n| `Exited` | `{ exit_code: int, signal: int? }` | after_effect |\n| `OutcomeUnknown` | Empty | outcome_unknown |\n| `OutputOverflow` | `{ limit: ulong, reason: enum { Budget, Capacity } }` | outcome_unknown |\n| `SpawnFailed` | `{ message: string }` | before_effect |\n| `TimeoutExpired` | Empty | outcome_unknown |\n\n## Settings\n\nWith `codec = jsonl`, `rastok check` refuses a producer whose resolved type\ncontains a [value without a JSON form](/reference/types.md#json-request-values), using\n`E-TYPE-INVALID`. A `variant` producer is checked at execution instead; an\nunencodable request produces `DecodeFailed` before its frame is written.\nIn `service` mode, an unencodable request closes the Session.\n\n| Mode | Setting | Domain | Presence / default | Latest phase |\n|---|---|---|---|---|\n| job, service | `args` | `array<string>` | `[]` | instance |\n| job, service | `behavior` | `deterministic \\| probabilistic` | required | plan |\n| job, service | `codec` | `bytes \\| jsonl \\| lines` | required | plan |\n| job, service | `err_codec` | `bytes \\| lines` | `lines` | plan |\n| job, service | `command` | `string` | required | instance |\n| job, service | `cwd` | `string` | optional | instance |\n| job, service | `env` | `map<string,string>` | optional | instance |\n| job | `idempotent` | `bool` | `false` | plan |\n| job | `timeout` | `duration` | optional | instance |\n| job | `max_output` | `ByteSize` | `\"8MiB\"` | plan |\n| job | `on_timeout` | `kill` | `kill` | plan |\n| service | `max_frame` | `ByteSize` | `\"1MiB\"` | plan |\n\nThe shared catalogue lists framing choices for both modes; service validation further restricts `codec` to `lines | jsonl` and `err_codec` to `lines`. Service has no per-turn timeout or idempotence setting. Its mock supports input-driven `match` responses and an optional terminal; delayed/unsolicited mock frames, `now()` in Session mocks and system-close acknowledgements are not scripted. Physical unsolicited output is supported. Job mocks retain the ordinary Call timeout and terminal rules.\n\n## Qualification inventory\n\n`job`: fixture `crates/rastok/tests/conformance_process.rs`. Cases without a portable forced fixture: `CaptureFailed`, `OutcomeUnknown`. Related tests: `crates/rastok/tests/process_service.rs`, `crates/rastok/src/connector/drivers/process/mod.rs`.\n\n`service`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/tests/process_service.rs`, `crates/rastok/src/connector/drivers/process/mod.rs`.\n"},{"path":"/reference/types","title":"Types and schemas","description":"Logical types, literal forms and the loss-checked JSON Schema, Avro, Arrow and OpenAPI projections shipped in the alpha.","text":"---\ntitle: Types and schemas\ndescription: Logical types, literal forms and the loss-checked JSON Schema,\n  Avro, Arrow and OpenAPI projections shipped in the alpha.\nurl: https://docs.rastok.com/reference/types\nsource_revision: v0.2.0-alpha\n---\n\n# Types and schemas\n\nTypes describe values independently of their byte representation. A schema\nprojection produces a Rastok type; it does not install a wire codec or a\nDriver. The [types chapter](/guide/02-types-and-expressions.md) introduces\nthe notation.\n\n## Scalars\n\n### Numeric types\n\nUse the names in the first column in `.rkg` declarations. Their widths are\nfixed, not chosen by the machine. A computed value can enter another numeric\ntype without a written conversion only when every value of its type fits.\n\nAn annotation is the type you read back: `val seven: decimal = 7u`\nbinds a `decimal`, while `val seven = 7u` binds a `uint`.\n\n| Source type | Representation and bounds | Computation in this alpha |\n|---|---|---|\n| `sbyte`, `short`, `int`, `long` | Signed 8-, 16-, 32- and 64-bit integers | Arithmetic, ordering and equality. Division truncates toward zero; carrier overflow and division by zero fault. A result must fit its destination. |\n| `byte`, `ushort`, `uint`, `ulong` | Unsigned 8-, 16-, 32- and 64-bit integers | Arithmetic, ordering and equality. Carrier overflow, underflow and division by zero fault. |\n| `half`, `float`, `double` | Binary16, binary32 and binary64 | Arithmetic at the result width, ordering and equality. Results can include infinities and NaN; ordering a NaN faults. |\n| `decimal` | Exact integer or decimal, not binary floating point | Carrying, schema projection, equality and explicit narrowing; no arithmetic or ordering |\n| `decimal(p,s)` | Exact decimal128 coefficient and scale; precision `1..38`, scale `-38..38` | Carrying, schema projection and equality; exact conversion from integers or `decimal`; no arithmetic or ordering, and narrowing never rounds |\n\nAn unsigned literal chooses the first width that holds it: `7u` is `uint`,\n`4294967296u` is `ulong`. There is no separate `ulong` suffix.\nWrite `int`, not `int32`, and `half`, not `float16`. Without context, a\nfloating literal uses `double`. Where a `float` is expected, `0.1` and\n`4.099999904632568359375` both fit: the first keeps its displayed value,\nthe second is exactly representable. A literal may also fit `double` by\neither rule and then fit `float` exactly: `0.10000000149011612` fits\nand displays `0.1`. Neither `0.1000000015` nor `0.123456789` fits.\n\n| Values that meet | Type used |\n|---|---|\n| `int` and `long` | `long` |\n| `int` and `double`, or `float` and `double` | `double` |\n| An integer and `decimal` | `decimal` |\n| An integer and `decimal(p,s)`, or two fixed decimals | The smallest fixed decimal that holds both, otherwise `decimal` |\n| `int` and `uint` | `long` |\n| `long` and `double`, `int` and `ulong`, or `float` and `decimal` | No common type; convert explicitly with `as?` |\n\nA `float` widened to `double` or carried as a `variant` keeps the value its\nshortest rendering denotes. Lists, map values and struct fields can widen\nwhen their contents can.\n\nThe `%` result has the dividend's sign, including a negative zero. Floating\nremainder uses a quotient truncated toward zero. A zero divisor, infinite\ndividend or NaN operand yields NaN; a finite dividend modulo an infinite\ndivisor is unchanged. Two declared decimals compare by value: `19.90`\nat scale two equals `19.900` at scale three. Each keeps its own scale\nfor display. Two `decimal` values also compare by value: seven equals\n`decimal(\"7.00\")`. Neither comparison rounds.\n`decimal` cannot be a map or instance key. See [numeric expressions](/reference/expressions.md#numeric-operands-in-this-alpha)\nfor conversion examples and fault behavior.\n\n### Other scalars\n\n| Type | Parameters and aliases | Value rule |\n|---|---|---|\n| `bool` | No parameter | `true` or `false` |\n| `null` | No parameter | The null value |\n| `string` | No parameter | Unicode text |\n| `array<byte>` | Variable length | Compact byte sequence; `size(b)` counts bytes and `b[?i]` returns a `byte?` |\n| `array<byte,N>` | Fixed length in source | Exactly `N` bytes; `1 <= N <= 2147483647` |\n| `uuid` | No parameter | Exactly 16 network-order bytes |\n| `string(max)` | Maximum length in Unicode scalar values | `\"été\"` fits `string(3)?`, and `[\"été\"]` fits `array<string(3)>`. When the input may be longer, use `as? string(3)` and handle null. JSON Schema preserves `maxLength`; Avro and Arrow return `LossyProjection` at this field. |\n\n## Dates, times and intervals\n\nSource declarations in this version accept only the bare names `date`,\n`time`, `timestamp`, `timestamp_ntz` and `duration`. They use the defaults\nbelow. Parameterized forms and calendar intervals belong to the logical\nmodel and transported schemas; they are not source type declarations.\n`interval` is not a built-in source type, either bare or parameterized.\n\nFor logical `time`, `timestamp`, `timestamp_ntz` and `duration`, the unit is\n`second`, `millisecond`, `microsecond` or `nanosecond`. These parameterized\ntemporal declarations are refused with `E-PARSE-DEFERRED`, naming the form.\nThis does not affect value constructors such as `duration(\"2s\")` or\n`timestamp(\"2026-10-30T12:00:00Z\")`.\n\n| Logical type | Source default or logical parameters | Distinction preserved |\n|---|---|---|\n| `date(unit)` | `day` or `millisecond`; bare `date` means `day` | Date, carried as whole days |\n| `time(unit)` | Bare `time` means nanoseconds | Time of day, without a date |\n| `timestamp(unit, \"zone\")` | Bare `timestamp` means nanoseconds in UTC | Instant with a declared zone; `UTC`, `Etc/UTC` and `+00:00` normalize to UTC |\n| `timestamp_ntz(unit)` | Nanoseconds by default | Date and time without a zone; not UTC by omission |\n| `duration(unit)` | Nanoseconds by default | Signed elapsed quantity, carried in i64 nanoseconds |\n| `interval(year_month)` | Months | Calendar interval |\n| `interval(day_time)` | Days and time | Calendar interval with millisecond precision |\n| `interval(month_day_nano)` | Signed months, days and nanoseconds | Arrow interval constraints |\n| `interval(month_day_millis_unsigned)` | Unsigned 32-bit months, days and milliseconds | Avro duration constraints, distinct from the Arrow interval |\n\nTimestamp carriers contain signed i64 seconds and a nonnegative nanosecond\nfraction. The unit limits precision, not the seconds range. Arithmetic\noutside the carrier refuses. Logical execution time and civil timestamps\nare separate: `now()` observes the recorded origin plus the transaction's\nlogical instant.\n\n## Composite types\n\n`as? Record` checks the fields of either a struct or a JSON object against\nthe declared record. For example, an unsigned seven can fill a `long` field;\nan unsigned value outside the `long` range makes the whole cast return null.\n\n| Form | Meaning | Constraints |\n|---|---|---|\n| `struct { name: string, count: int }` | Named fields | Closed, unique fields; declaration order is not type identity |\n| `array<T>` | Ordered homogeneous sequence | Variable length |\n| `array<T,N>` | Fixed sequence in the logical model only | Exactly `N` elements, including `N = 0`; source declarations refuse this form with `E-PARSE-DEFERRED` |\n| `map<K,V>` | Homogeneous keyed collection | Canonical, non-null scalar or enum keys |\n| `enum { Ready, Done }` | Named unit cases | Write `Ready` or `Done` where this enum is expected, including a typed list element or opposite an enum operand of `==` or `!=`; a conflicting visible binding refuses |\n| `T?` | `T` or null | Absence and null are distinct at a boundary |\n| `A \\| B` | Structural union | Branches must be pairwise disjoint; exactly one branch matches |\n| `union { Ok { value: string }, Refused }` | Tagged union | Named cases with closed payloads; the case remains part of the value |\n| `variant` | Self-describing value tree | Test its type with `is`. To read a schemaless JSON object as a declared struct, use `as? T` and handle null. |\n\nAn optional enum `E?` resolves bare symbols wherever enum `E` does, including\ncollection values and Lab assertions; a union with several non-null branches\ndoes not select an enum for a bare symbol.\n\nIn the logical model, map keys admit booleans, fixed-width integers, strings,\nbyte arrays, fixed-scale decimals, dates, times, timestamps, durations, UUIDs and enum symbols.\nFloats, `decimal`, null, intervals, dynamic values and composite keys refuse.\nInstance keys additionally admit closed structs of valid key leaves.\n\nSource map literals accept only string keys: `{ \"id\": \"a\" }` is a map,\nwhile `{ 1: \"a\" }` is refused. For `map<string(3), long>`,\n`{\"été\": 1}` fits and `{\"abcd\": 1}` is refused at check.\nA non-string key type can still be declared,\nfor example `map<int, string>`, but only its empty literal `{:}` can be\nwritten in this version. Fixed-length arrays can be written only for `byte`.\nThe `bytes` connector codec still names a wire format. Neither a byte array\nwith a declared schema nor bytes carried in a `variant` have a JSON wire form.\n\nNamed type declarations are structural aliases. Recursive aliases refuse.\nType trees are bounded to 128 nesting levels, 4096 nodes and 256 members per\naggregate. `type Name = @struct { ... }` declares a flat, annotation-capable\nstruct; annotation use and interpretation are described in\n[Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md).\n\n## Standard types without imports\n\nThe [standard library](/reference/stdlib.md#types) lists the named types available\nwithout imports, including `FileExit` and `ProcessExit`. They use the same\ndefinitions as the Connector ports, independently of the physical Drivers\nincluded in the binary. Write `output failed: FileExit` without copying its\ndeclaration; the library reference explains name collisions and the module\nand import design still to be discussed.\n\n## Literals and constructors\n\n| Spelling | Result | Notes |\n|---|---|---|\n| `42`, `42u`, `1.5`, `true`, `null`, `\"Ada\"` | Intrinsic scalar | Ordinary expression literals retain their checked type |\n| `decimal(\"12.30\")` | `decimal` carrying an exact decimal | A declared decimal target checks precision and rescales exactly |\n| `duration(\"2h30m\")` | `duration` | Signed duration; units include `h`, `m`, `s`, `ms`, `us`, `ns` |\n| `{ room = \"kitchen\", celsius = 21 }` | Declared `struct` | Braced field assignments, `name = value`, checked against the struct type expected where the literal appears |\n| `[]`, `{:}` | Empty array, empty map | Use the expected type; without one, `array<variant>` and `map<string,variant>`; `{}` is an empty struct, not a map |\n| `timestamp(\"2026-10-30T12:00:00Z\")` | `timestamp` | Parsed civil instant |\n| `json! { \"count\": 42 }` | `variant` | Also accepts scalar JSON. Duplicate keys and numbers without a lossless `long`, `ulong` or `double` representation refuse. |\n| `string! { message }` | `string` | Verbatim reader |\n| `base64! { SGk= }` | `array<byte>` | Standard base64, padding required; ASCII whitespace ignored |\n| `asset(\"fixtures/sample.pdf\")` | `array<byte>` | Bytes read at build time and embedded in the plan |\n\nTagged frontends occupy a complete value position. Bind their result before\nusing it inside a larger expression. See [Expressions and dispatch](/reference/expressions.md).\n\nWithout an expected type, `val members = []` infers `array<variant>` and\n`val counts = {:}` infers `map<string,variant>`. The same rule applies to\n`{ items = [] }`. A destination requiring more precise elements refuses\nsuch a binding with `E-PORT-TYPE`; annotate the declaration instead:\n`val members: array<string> = []` or `var counts: map<string, int> = {:}`.\nWith elements, `val members = [\"alice\"]` infers `array<string>`; mixed\nelements such as `[1, \"a\"]` infer `array<variant>`. The type belongs on\nthe declaration: there is no `array<string> []` value prefix.\n\nA typed list checks each element against its declared element type, as a\ntyped map does for its values. With `data: string`, write\n`val names: array<string?> = [null, data]`. Without that expected type,\n`[null, \"a\"]` still infers `array<variant>`.\n\nAn optional map keeps the same value context: for `map<string,int?>?`,\n`{ \"a\": null, \"b\": 1 }` constructs the optional values before the optional map.\nLikewise, an enum symbol resolves inside an optional collection: with\n`Status = enum { Pending, Done }`, write `[Pending]` for `array<Status>?`\nor `{ \"x\": Done }` for `map<string,Status>?`. A union with several non-null\nbranches does not choose a collection branch for a bare symbol.\n\n## JSON request values\n\nA JSON-encoding Connector input refuses a known producer type containing\n`array<byte>`, `duration`, `timestamp`, `date`, `time`, `timestamp_ntz`, `interval`,\n`uuid`, a map with non-string keys, or a tagged union, at any depth.\n`E-TYPE-INVALID` names the input and the first offending field. Convert the\nvalue explicitly before sending it. Enum symbols, exact decimals, finite\nfloats, optional fields and maps with string keys have JSON forms.\n\nA `variant` producer passes this static check; a JSON value can be forwarded\ndirectly to another JSON Connector. Its value remains subject to the runtime\nencoder. A `variant` field does not hide a known non-JSON field elsewhere in\nthe producer type. See the individual\n[Contracts](/reference/contracts.md) for their runtime refusals. Response decoding is\na separate constraint: an encodable request type is not necessarily an\nadmitted JSON response type.\n\n## Schema projection rules\n\nThe schema projection adapters report a path and a named loss reason.\nReverse projection succeeds only when projecting the result back preserves\nthe logical type. Source field order, physical union indexes and layout do\nnot become type identity.\n\n| Refusal | Meaning |\n|---|---|\n| `UnsupportedSource` | Construct outside the admitted source subset |\n| `UnsupportedTarget` | No exact representation in the selected target |\n| `InvalidSchema` | Invalid schema or invalid parameters |\n| `RecursiveSchema` | Reference cycle |\n| `LossyProjection` | Conversion would discard a constraint or distinction |\n| `AmbiguousUnion` | Overlapping branches |\n| `InvalidMapKey` | Key outside the canonical-key domain |\n| `BudgetExceeded` | Resolved type exceeds a type-tree bound |\n\nA declared `decimal`, `decimal(p,s)`, `long` or `ulong` field also accepts a\nJSON string that spells an exact number in range. For example, the string\n`\"9007199254740993\"` enters a `long` unchanged; `\"01\"` is not a valid JSON\nnumber. Output uses an unquoted number.\n\n### JSON Schema 2020-12\n\n| Source or direction | Projection or refusal |\n|---|---|\n| `null`, `boolean`, `string`, `number`, `integer` | `null`, `bool`, `string`, `double`, `long` |\n| Integer with inclusive bounds exactly matching a machine width | Corresponding signed or unsigned integer |\n| Integer range `0..10` | `LossyProjection`, rather than widening to a machine integer |\n| String enum; homogeneous array; equal `minItems` and `maxItems` | Enum; variable array; fixed array |\n| Required named properties and `additionalProperties: false` | Closed struct |\n| Schema-valued additional properties without named fields | `map<string,V>` |\n| Null plus one type; disjoint `oneOf` | Optional; structural union |\n| Optional property without a fill policy; required key on a map | `LossyProjection` |\n| Boolean schema, `pattern`, conditional constraints, tuple prefixes | `UnsupportedSource` |\n| Cyclic local reference; overlapping `oneOf` | `RecursiveSchema`; `AmbiguousUnion` |\n| Invalid definition or empty type array | `InvalidSchema` |\n| Reverse bytes, decimal scale, time units or tagged discriminants without an extension profile | `UnsupportedTarget` |\n\n### Avro 1.12\n\n| Source or direction | Projection or refusal |\n|---|---|\n| Null, boolean, int, long, float, double, bytes, string | Matching types; Avro bytes gives `array<byte>` and integers retain 32/64-bit widths |\n| Fixed, record, array, string-keyed map, enum | `array<byte,N>`, closed struct, array, string-keyed map, enum |\n| Decimal logical type | Decimal128, precision up to 38, `0 <= scale <= precision`; fixed storage must fit |\n| Date, time, timestamp and local-timestamp logical types | Matching date/time constructors, including zone-free timestamps |\n| Duration; UUID | `interval(month_day_millis_unsigned)`; `uuid` |\n| Disjoint union branches | Structural union with an explicit branch-index mapping |\n| Same-shape named record branches | Tagged union using resolved names |\n| Recursive record | `RecursiveSchema` |\n| Precision 39 or unknown logical type | `UnsupportedSource` |\n| Insufficient fixed decimal storage, forward undefined name or duplicate underlying union branch | `InvalidSchema` |\n| Reverse type without an exact Avro form | `UnsupportedTarget` or `LossyProjection` |\n\n### Arrow\n\n| Source or direction | Projection or refusal |\n|---|---|\n| Integers, floats, decimal128 | Width, sign, precision and signed scale preserved |\n| Binary, large binary, binary view; UTF-8 variants | `array<byte>`; `string` |\n| Fixed binary; list variants; fixed list | `array<byte,N>`; variable array; fixed array |\n| Date, time, timestamp, duration, interval | Unit and zone preserved |\n| Struct, nullable field, map | Closed struct, optional field, canonical-key map |\n| Dictionary or run-end encoding | Decoded logical value type |\n| Dense or sparse union | Tagged union with explicit child-name/type-code mapping |\n| Extension type, decimal32/64/256 or out-of-range scale | `UnsupportedSource` |\n| Nullable or unsupported map key | `InvalidMapKey` |\n| Duplicate union type codes or child names | `InvalidSchema` |\n| Reverse tagged union with 129 cases | `UnsupportedTarget`: the flat target union cannot address that many children |\n\n### OpenAPI 3.0 and 3.1\n\n`rastok --resolve-open-api <project-dir> [--check]` discovers static HTTP\nendpoints and generates `openapi.generated.rkg`. It leaves authored sources\nuntouched. `--check` reports a missing or stale generated file without writing.\n\n| Source | Projection or refusal |\n|---|---|\n| Local component reference | Expanded alias; cycles give `RecursiveSchema` |\n| 3.0 `nullable: true`; 3.1 type array with null | `T?` |\n| Integer format `int32` or `int64` | `int` or `long`, respectively; unbounded integer gives `LossyProjection` |\n| Number, number format float/double | `decimal`, `float` or `double`, respectively |\n| String, uuid, date, date-time, binary/byte, media-type formats | `string`, `uuid`, `date`, `timestamp`, `array<byte>`, `string`, respectively |\n| Fully required closed object; pure additional-property map | Closed struct; `map<string,V>` |\n| Disjoint `oneOf` | Structural union |\n| Optional fields, open/mixed object or required map keys | `LossyProjection` |\n| Unknown format, discriminator, `readOnly` or `writeOnly` | `UnsupportedSource` |\n| Dynamic endpoint, no matching document or ambiguous document | Resolver refusal; no guessed endpoint |\n| Component name that is a standard type name | `UnrepresentableName`; no conflicting declaration is written |\n\nThe HttpClient `json_profile = projected` setting is a separate boundary policy:\nit can skip extra fields and fill omitted nullable fields with null. It\nstill rejects a wrong type or missing required field. It does not widen the\nOpenAPI schema projection above.\n\n## Specified, not shipped\n\n| Item | Specification |\n|---|---|\n| Registered extension profiles for projections that need additional schema vocabulary | [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md) §§1–4 |\n| Decoder availability resolved through an attested registry | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) §5.1 |\n\nSources: [`docs/spec/types.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md), [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md);\nexecutable projection evidence in `crates/rastok/tests/schema_projections.rs`\nand the OpenAPI projection/resolver tests. Runtime wire support remains\nspecific to each [Contract](/reference/contracts.md).\n"},{"path":"/debugger","title":"The debugger, a guided tour","description":"Read a simulation or a recorded execution through its source, transitions, envelopes and assertions.","text":"---\ntitle: The debugger, a guided tour\ndescription: Read a simulation or a recorded execution through its source,\n  transitions, envelopes and assertions.\nurl: https://docs.rastok.com/debugger\nsource_revision: v0.2.0-alpha\n---\n\n# The debugger, a guided tour\n\nThe debugger shows the program beside its recorded execution. Select a\ntransition to see the source, the graph and the inspector at the same point.\nThis tour uses the [webhook example](/examples/04-webhook-to-partner.md): a\npartner request times out, Retry schedules another attempt, and that attempt\nsucceeds.\n\n## Open the debugger\n\nInstall a binary built with `hosted-ui`, then open a scenario:\n\n```sh\nrastok simulate hello.rkg --ui\n```\n\nUse the `hello.rkg` created in [Getting Started](/getting-started.md), or supply\nthe path of your program. The [webhook example](/examples/04-webhook-to-partner.md#run)\ngives the complete command and deployment profile for the graph in the tour.\nFor an existing recording, use:\n\n```sh\nrastok replay echo.rkr --ui\n```\n\nThe CLI prints a loopback URL. Open that exact URL in your browser; it contains\nthe capability needed to access this debugger. Keep it private. The URL is\nclickable in terminals that support hyperlinks. Leave the process running\nwhile you inspect it. `--ui-port` selects a port when you need one; otherwise\nthe operating system chooses it.\n\nIn Terminal on macOS, hold Command and double-click the URL to open it,\nas listed in the [Terminal keyboard shortcuts](https://support.apple.com/guide/terminal/trmlshtcts/mac).\nOther terminals may use a different shortcut. Copying the complete URL into\nyour browser also works; do not omit its access token or share it.\n\nSimulation starts paused and can execute its Lab scenario. Diagnostic replay\nreads an existing recording without repeating external effects. These are\ndifferent modes of the same interface, not two names for the Play button.\n\n## Find your way around\n\nThe numbered view is a recorded backoff transition of\n`webhook.timeout_then_success`. The numbers were added to the running page\nbefore capture; the state and values come from that scenario. The graph is\nshown at Readable size, centered on the Node of that transition; Fit graph\nshows the complete drawing instead.\n\n![Numbered debugger regions at the webhook retry backoff](/assets/debugger-overview.png)\n\n1. **App bar and mode.** The mode and execution status distinguish a live\n   simulation, recorded history and diagnostic replay.\n2. **Transport.** Back, Next transition, Next action, Run to expect, Finish,\n   Play, Speed and Reset control which transition you see. The table below\n   explains their differences.\n3. **Timeline.** Select an already recorded transition or a simulation session.\n   Return live goes back to the current execution head. Pending lists recorded\n   obligations such as a retry deadline.\n4. **Source.** File tabs, line numbers, the current marker and Search connect\n   execution to the authored program. A selected graph element highlights its\n   definition. Fold regions to keep the relevant part visible.\n5. **Inspector.** Envelope shows data and metadata; Mailbox shows queued\n   deliveries; Instances shows state and lifetime information; History shows\n   recorded changes; Assertion explains an expectation; Compare aligns two\n   instances or sessions for inspection.\n6. **Graph and legend.** Nodes and connections show the selected transition.\n   Select a node or a port to inspect it. The legend explains the visual\n   notation; Fit and zoom change the view, not execution.\n7. **Logical clock and controller.** The clock is the execution's logical\n   time, not elapsed browser time. The controller role identifies the browser\n   allowed to advance execution; another connected browser can inspect it.\n\n## Advance deliberately\n\n| Control | What it does |\n|---|---|\n| Back | Select the preceding recorded transition. |\n| Next transition | Advance one recorded transition, executing when at the live head. |\n| Next action | In simulation, advance one authored scenario action to its effect. |\n| Run to expect | In simulation, continue to the next expectation. |\n| Finish | Continue to completion. |\n| Play / Pause | Advance through transitions at the selected playback speed, or stop. |\n| Speed | Choose the playback rate; it does not change logical deadlines. |\n| Reset | Start a clean simulation session for the selected scenario. |\n\nSelecting history does not undo a real external effect. Play is a playback\ncontrol; `rastok replay` is the CLI command that opens a recording without\nDriver I/O. Controls that do not apply in the current mode are unavailable.\n\n## Follow an identifier\n\nHover an identifier in the source, or focus it with the keyboard, to read its\nrecorded summary. When available, its link opens the corresponding inspector\ntab. Classified values and secret bindings stay redacted.\n\n![An identifier summary in the generated starter program](/assets/debugger-hover.png)\n\nSelecting `greet` in the graph highlights its source definition. Source and\ngraph are two views of the same selected transition.\n\n![The selected greet Operator highlighted in the source](/assets/debugger-selection.png)\n\n## Understand an assertion\n\nIn the starter, change only `app.in = \"world\"` to `app.in = \"monde\"`, leaving\nthe expectation unchanged. Open the changed program and choose Finish. The\nheader shows the Lab's verdict. A pass includes the number of expectations;\non failure, click the first failed expectation to open its recorded\ntransition in Assertion. It may not be the last action. If only the\nreference trace differs, the header reports that instead: no expectation\nfailed. Return live takes you back to the completed scenario.\n\nThe Assertion tab shows the authored expectation, its observation window and the\nobserved value beside the expected value. Here the Operator produced\n`\"Hello, monde\"`, not `\"Hello, world\"`.\n\n![The starter assertion shows Hello, monde against Hello, world](/assets/debugger-assertion.png)\n\nAn expectation inspects observations since the preceding injection or time\nadvance. Successive expectations can inspect the same window. The debugger\ndoes not infer a missing observation or invent a comparison when a predicate\ncannot be explained field by field.\n\n## Keyboard shortcuts\n\n| Key | Action |\n|---|---|\n| Left / Right | Select the preceding or following transition. |\n| `n` or F10 | Next transition. |\n| `a` | Next authored action. |\n| Space or F8 | Play / Pause. |\n| Enter | Open the selected envelope. |\n| Escape | Dismiss an overlay or selection. |\n| `/` | Search for a node, port or id. |\n\nTab moves between controls, source identifiers and graph elements. Inputs and\ntab controls keep their own keys. Function keys work when the browser delivers\nthem to the page; Space and `n` provide alternatives.\n\n## What you cannot edit here\n\nThis is not a development environment. It is read-only: values, source and\nscenarios cannot be edited in the debugger in this version. Inputs come from\nthe scenario source, and there are no breakpoints. Edit the `.rkg` file in\nyour editor and restart the simulation to test a different program or input.\n\nContinue with [the Lab](/guide/04-the-lab.md),\n[journal and replay](/guide/05-running-for-real.md), or the\n[command-line reference](/guide/09-command-line.md).\n"},{"path":"/examples/03-two-tenants","title":"Two tenants: whose state is this?","description":"Watch Bob finish once while Alice alone times out, waits for backoff and retries in an isolated keyed instance.","text":"---\ntitle: \"Two tenants: whose state is this?\"\ndescription: Watch Bob finish once while Alice alone times out, waits for\n  backoff and retries in an isolated keyed instance.\nurl: https://docs.rastok.com/examples/03-two-tenants\nsource_revision: v0.2.0-alpha\n---\n\n# Two tenants: whose state is this?\n\nIn `examples/keyed-retry.rkg`, Bob's request completes while Alice's waits for a retry. The reference traces for this example are filed under `two-tenants`.\n\nA file pipeline is easy to follow one request at a time. What happens when\nAlice's partner stalls while Bob's request is ready? This chapter adds\ninstance ownership and finite retry to the same graph-and-Lab model.\n\nThe versioned goldens cover native Retry: the failed attempt remains visible\nin the journal, while only the final outcome reaches the graph.\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root, with `rastok` installed:\n\n```sh\nrastok simulate examples/keyed-retry.rkg --compare examples/traces/two-tenants\n```\n\n```text\nPASS ui_tour.two_tenants\nPASS ui_tour.lifetime\n2 scenario(s), 0 failed\n```\n\nAdd `--ui` to follow the same checked scenario in the debugger.\n\n```sh\nrastok simulate examples/keyed-retry.rkg --compare examples/traces/two-tenants --ui\n```\n\nThis requires `hosted-ui`. Open the private loopback URL printed by the CLI.\n\nFor the controls and source view, see [the debugger tour](/debugger.md).\n\n## Read the program\n\nThe file starts with `type Request = struct { ... }`. This names a payload\nshape with two `string` fields, `tenant` and `prompt`; it does not create a\nrequest. `input in: Request` then uses that type on a port. The\n[type reference](/reference/types.md) explains structs and other type forms.\n\nStart with `instance = { key = data.tenant }`: it selects independent state\nfor Alice and Bob. `Retry.attempts = 2` bounds Calls for one retained request,\nincluding the first; `lifetime` bounds how long an idle instance lives. They\nsolve different problems.\n\nAn instance is not a thread or a process. The current runtime executes\nOperator transactions one at a time, but an outstanding external Call does\nnot prevent another instance from progressing. Bob can finish while Alice\nwaits; this does not demonstrate parallel Operator execution. See\n[Instances, state and time](/guide/06-instances-state-and-time.md) for\nownership and lifetime, and [Execution and concurrency](/reference/execution.md)\nfor the current runtime and the planned worker pool.\n\nThen read `model : Process + Retry`, using the [Process contract](/reference/connectors/process.md): `Retry.on = [TimeoutExpired]` selects\nthe terminal that permits another attempt. Retry retains the original request\nacross attempts. `answer` decodes the final Process frame after the Retry\nmanager has selected it. The nested `audit` Graph composes another branch.\n\nThe [Lab reference](/reference/lab.md) explains mock responses, expectations\nand observation windows. `advance` supplies virtual time; a mock's terminal\nresponse ends its simulated exchange, not the whole scenario.\n\n<a id=\"graph\"></a>\n\nSource: `examples/keyed-retry.rkg`\n\n```rkg\n// Two tenants send requests: Bob finishes while Alice waits to retry.\n// The Lab checks that Alice's retry never starts a second request for Bob.\n\ntype Request = struct {\n  tenant: string\n  prompt: string\n}\n\ntype Answer = struct {\n  tenant: string\n  prompt: string\n}\n\ngraph agent_retry : App {\n  input in: Request\n  output done: Answer\n  output failed: ProcessExit\n\n  instance = { key = data.tenant }\n  lifetime = { kind = idle; max = duration(\"10s\") }\n  closing = { drain_for = duration(\"1s\"); settle_for = duration(\"1s\") }\n\n  graph audit {\n    input in: Request\n\n    operator observe {\n      input in: Request\n      output out: string\n\n      on in { out = data.tenant }\n    }\n\n    in -> observe\n    observe.out -> nothing\n  }\n\n  connector model : Process + Retry {\n    mode = job\n    command = \"cat\"\n    codec = jsonl\n    idempotent = true\n    behavior = probabilistic\n    timeout = duration(\"1s\")\n    max_output = \"1 MiB\"\n    Retry.attempts = 2\n    Retry.on = [TimeoutExpired]\n    Retry.delay = { kind = fixed; after = duration(\"1s\") }\n  }\n\n  operator answer {\n    input in: variant\n    output out: Answer\n    on in {\n      val decoded = data as? Answer\n      match {\n        decoded is Answer => out = decoded\n        _ => nothing\n      }\n    }\n  }\n\n  in -> { audit; model }\n  model.out -> answer -> done\n  model.err -> nothing\n  model.exit -> match {\n    Exited -> nothing\n    CaptureFailed | DecodeFailed | OutcomeUnknown | OutputOverflow\n      | SpawnFailed | TimeoutExpired -> failed\n  }\n}\n\nlab ui_tour {\n  mock model {\n    on in where data is Request && data.tenant == \"alice\" && now() == timestamp(\"1970-01-01T00:00:00Z\") {\n      out = nothing\n    }\n    on in {\n      out = data\n      exit = Exited { exit_code = 0; signal = null }\n    }\n  }\n\n  scenario two_tenants {\n    app.in = { tenant = \"alice\"; prompt = \"Explain causal replay\" }\n    expect app.done == nothing\n\n    app.in = { tenant = \"bob\"; prompt = \"Explain typed envelopes\" }\n    expect app.done where data.tenant == \"bob\"\n\n    advance duration(\"1s\")\n    expect app.done == nothing\n    expect model.in == nothing\n\n    advance duration(\"1s\")\n    expect app.done where data.tenant == \"alice\"\n    expect answer.in == { \"tenant\": \"alice\", \"prompt\": \"Explain causal replay\" }\n    expect 0 model.in where data is Request && data.tenant == \"bob\"\n    expect audit.observe.in == nothing\n    expect 0 app.done where data.tenant == \"bob\"\n    expect app.failed == nothing\n  }\n\n  scenario lifetime {\n    app.in = { tenant = \"bob\"; prompt = \"First generation\" }\n    expect app.done where data.prompt == \"First generation\"\n    advance duration(\"10s\")\n    expect model.in == nothing\n    app.in = { tenant = \"bob\"; prompt = \"Next generation\" }\n    expect app.done where data.prompt == \"Next generation\"\n    expect app.failed == nothing\n  }\n}\n```\n\n## Expected result\n\nThis cut of `ui_tour.two_tenants` follows `model` and `answer`; the separate\n`audit.observe` branch runs once per input and is omitted here.\n\n```mermaid\nsequenceDiagram\n    participant lab as Lab: ui_tour.two_tenants\n    participant app as agent_retry\n    participant model as model: Process + Retry\n    participant answer as answer\n    lab->>app: in = Alice's request\n    app->>model: Alice, attempt 1\n    model->>lab: Scripted Call: no response\n    lab->>app: in = Bob's request\n    app->>model: Bob, attempt 1\n    model->>lab: Scripted Call\n    lab-->>model: Bob's data, then Exited(0)\n    model->>answer: Bob's data\n    answer-->>app: done = Bob's answer\n    lab->>lab: advance 1s\n    Note over model: Alice: TimeoutExpired is Held, not delivered\n    lab->>lab: advance 1s\n    model->>lab: Alice, attempt 2: the same request\n    lab-->>model: Alice's data, then Exited(0)\n    model->>answer: Alice's data\n    answer-->>app: done = Alice's answer\n    Note over model: No second Call for Bob\n```\n\nAlice enters first and waits. Bob enters a separate instance and finishes\nimmediately. Advancing one second expires Alice's Call;\nthe next second admits her retry, which finishes. Bob\nreceives no second Call. The `lifetime` scenario advances through ten seconds\nof silence, then proves that a new admission uses a fresh instance generation.\n\n`⧉` counts instances. The Instances tab's Retry table shows Bob's one attempt\nand Alice's two distinct Calls. Alice's timeout is recorded as **Held**, not\ndelivered to the `failed` output; the final attempt is **Published**. The audit\nruns once per incoming request, not again for an internal retry.\n\n## Break it\n\nChange `Retry.attempts = 2` to `Retry.attempts = 1`. Alice can no longer be\nreadmitted: her original `TimeoutExpired` reaches `failed`, and the assertion\nexpecting Alice's answer fails. Bob still finishes once. There is no new\n`RetryExpired` error type.\n\n```sh\nrastok simulate examples/keyed-retry.rkg --compare examples/traces/two-tenants\n```\n\n```text\nFAIL ui_tour.two_tenants\n     expect app.done where data.tenant == \"alice\"  (keyed-retry.rkg:95)\n     nothing observed\n     where data.tenant == \"alice\" is false for 0 of 0 deliveries; count 0, expected 1\n     expect answer.in == { \"tenant\": \"alice\", \"prompt\": \"Explain causal replay\" }  (keyed-retry.rkg:96)\n     nothing observed\n     expected 1 matching delivery on answer.in, but observed 0\n     golden divergence: record 6: retry_protocol(43) . parent_id(2)[0][4]; expected 98f50438c7e3285a…(32 bytes); got 639236b28503f36b…(32 bytes); cause: TRANSACTION \"model\" · trigger \"l:retry\" · cause_id f3df1105112054d3…(16 bytes)\nFAIL ui_tour.lifetime\n     golden divergence: record 6: retry_protocol(43) . parent_id(2)[0][4]; expected 98f50438c7e3285a…(32 bytes); got 639236b28503f36b…(32 bytes); cause: TRANSACTION \"model\" · trigger \"l:retry\" · cause_id f3df1105112054d3…(16 bytes)\n2 scenario(s), 2 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/keyed-retry.rkg\n```\n\n## Read the golden difference\n\nAdd `--compare examples/traces/two-tenants` to compare every\nrecord. The unedited example matches. After your edit, the CLI names the first\ndifference and recorded context, which can precede the final missing answer.\nRestore the attempt bound afterward.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/two-tenants/ui_tour.two_tenants.rkc`\n\n```rastok-trace\na6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c69636509636c61620a000b000d8282742e696e3e61756469742e6f6273657276652e696e82581e8282656175646974676f627365727665818380018207820665616c69636500826c2e696e3e6d6f64656c2e696e82568281656d6f64656c818380018207820665616c69636500\na7070211601282508280818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na80702116561756469741282568281656175646974818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282508280818380018207820665616c69636500\na80702116d61756469742e6f6273657276651282581e8282656175646974676f627365727665818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282568281656175646974818380018207820665616c69636500\na8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282508280818380018207820665616c69636500\na60702116d61756469742e6f6273657276651282581e8282656175646974676f627365727665818380018207820665616c696365001364703a696e148183742e696e3e61756469742e6f6273657276652e696e82508280818380018207820665616c6963650001178183636f757400a50150242f04840e2b7276f46b18be463a760e0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820248820665616c696365\na8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a726574727914801780181a50f3df1105112054d397a04ed0666ca4c8182ba10282870150961dad6a19ad6dc36464a3b337506d5c509046c8137b2b3d115dfb05d17181057962696e582098f50438c7e3285ad952d34f94123cf760a8e4f60f14f6ef9446ad9ccc373b1d6d7374642f70726f6365737340318450f3df1105112054d397a04ed0666ca4c8582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d780f6850250961dad6a19ad6dc36464a3b337506d5c01a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c696365509046c8137b2b3d115dfb05d171810579\na70703181b50f3df1105112054d397a04ed0666ca4c8181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f0118216c2e696e3e6d6f64656c2e696e182ba1018250961dad6a19ad6dc36464a3b337506d5c01\na6070108a40150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025833820f82826670726f6d70748206774578706c61696e20747970656420656e76656c6f706573826674656e616e74820663626f6209636c61620a010b000d8282742e696e3e61756469742e6f6273657276652e696e82581c8282656175646974676f627365727665818380018207820663626f6200826c2e696e3e6d6f64656c2e696e82548281656d6f64656c818380018207820663626f6200\na70702116012824e8280818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd\na80702116561756469741282548281656175646974818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824e8280818380018207820663626f6200\na80702116d61756469742e6f6273657276651282581c8282656175646974676f627365727665818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd182282548281656175646974818380018207820663626f6200\na8070211656d6f64656c1282548281656d6f64656c818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824e8280818380018207820663626f6200\na60702116d61756469742e6f6273657276651282581c8282656175646974676f627365727665818380018207820663626f62001364703a696e148183742e696e3e61756469742e6f6273657276652e696e824e8280818380018207820663626f620001178183636f757400a50150f98c7c092a53d6d1a7989ec1f6b52b630250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd040105820246820663626f62\na8070211656d6f64656c1282548281656d6f64656c818380018207820663626f620013676c3a726574727914801780181a50e6c20d6146234b74a33da1c709e86efd182ba10282870150b1c68415b421d87951425a4853e66f5650a08358e94753b1beccc9a14b211f98ca62696e582098f50438c7e3285ad952d34f94123cf760a8e4f60f14f6ef9446ad9ccc373b1d6d7374642f70726f6365737340318450e6c20d6146234b74a33da1c709e86efd5820e2c35b0b29e096536129210ebbf03f76743c3c01adec1d83f308c8d62115d3ef80f6850250b1c68415b421d87951425a4853e66f5601a40150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025833820f82826670726f6d70748206774578706c61696e20747970656420656e76656c6f706573826674656e616e74820663626f6250a08358e94753b1beccc9a14b211f98ca\na70703181b50e6c20d6146234b74a33da1c709e86efd181c656d6f64656c181e5820e2c35b0b29e096536129210ebbf03f76743c3c01adec1d83f308c8d62115d3ef181f0118216c2e696e3e6d6f64656c2e696e182ba1018250b1c68415b421d87951425a4853e66f5601\na80703181b50e6c20d6146234b74a33da1c709e86efd181c656d6f64656c181e5820e2c35b0b29e096536129210ebbf03f76743c3c01adec1d83f308c8d62115d3ef181f02182082018282636f7574820258378210828282066670726f6d70748206774578706c61696e20747970656420656e76656c6f7065738282066674656e616e74820663626f628264657869748202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618216c2e696e3e6d6f64656c2e696e182ba1018250b1c68415b421d87951425a4853e66f5601\na8070211656d6f64656c1282548281656d6f64656c818380018207820663626f62001364703a696e1481836c2e696e3e6d6f64656c2e696e824e8280818380018207820663626f620001178283636f757400a501502f3afb52c023c8407761929204189d5b0250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd040105820258378210828282066670726f6d70748206774578706c61696e20747970656420656e76656c6f7065738282066674656e616e74820663626f6283646578697400a5015021e0d24451d2373d0490524464f3fd210250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd0401058202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618198183502f3afb52c023c8407761929204189d5b736d6f64656c2e6f75743e616e737765722e696e8255828166616e73776572818380018207820663626f6200182ba2018250b1c68415b421d87951425a4853e66f56010282850650b1c68415b421d87951425a4853e66f56015061c7816a4b547232f22e62ea101f1c6b82502f3afb52c023c8407761929204189d5b5021e0d24451d2373d0490524464f3fd21840750b1c68415b421d87951425a4853e66f560101\na807021166616e73776572128255828166616e73776572818380018207820663626f620013676c3a737461727414801780181a502f3afb52c023c8407761929204189d5b1822824e8280818380018207820663626f6200\na607021166616e73776572128255828166616e73776572818380018207820663626f62001364703a696e148183736d6f64656c2e6f75743e616e737765722e696e82548281656d6f64656c818380018207820663626f620001178183636f757400a501506057c95cde89e87685a95298350240f702502f3afb52c023c8407761929204189d5b0350e6c20d6146234b74a33da1c709e86efd04010582025833820f82826670726f6d70748206774578706c61696e20747970656420656e76656c6f706573826674656e616e74820663626f62\na9070318188182045048a92fbc727f4d7ed69005b9f745d4ce181b50f3df1105112054d397a04ed0666ca4c8181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f021820810218216c2e696e3e6d6f64656c2e696e182ba1018250961dad6a19ad6dc36464a3b337506d5c01\na7070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013696c3a74696d656f75741481836c2e696e3e6d6f64656c2e696e82508280818380018207820665616c6963650001178183646578697400a50150d5b3406cdffd7e099c4c3694fd0293b90250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202558213826e54696d656f757445787069726564820f80182ba2018250961dad6a19ad6dc36464a3b337506d5c010281850350961dad6a19ad6dc36464a3b337506d5c015001c6fbc51564f0a3ccf04ad9bc0e8bb08150d5b3406cdffd7e099c4c3694fd0293b9\na8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a726574727914801780181a50d5b3406cdffd7e099c4c3694fd0293b9182ba10282850450961dad6a19ad6dc36464a3b337506d5c015001c6fbc51564f0a3ccf04ad9bc0e8bb08150d5b3406cdffd7e099c4c3694fd0293b9850550961dad6a19ad6dc36464a3b337506d5c01025001c6fbc51564f0a3ccf04ad9bc0e8bb0\naa070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a72657472791480178018188182015003260119a3813e2ae8426b064bdc8699181981835048a92fbc727f4d7ed69005b9f745d4ce782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e82568281656d6f64656c818380018207820665616c69636500181a50d5b3406cdffd7e099c4c3694fd0293b9182ba10281850250961dad6a19ad6dc36464a3b337506d5c02a5015048a92fbc727f4d7ed69005b9f745d4ce0250d5b3406cdffd7e099c4c3694fd0293b90350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c6963655003260119a3813e2ae8426b064bdc8699\na70703181b5048a92fbc727f4d7ed69005b9f745d4ce181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f011821782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e182ba1018250961dad6a19ad6dc36464a3b337506d5c02\na80703181b5048a92fbc727f4d7ed69005b9f745d4ce181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f02182082018282636f7574820258378210828282066670726f6d70748206754578706c61696e2063617573616c207265706c61798282066674656e616e74820665616c6963658264657869748202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f61821782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e182ba1018250961dad6a19ad6dc36464a3b337506d5c02\na8070211656d6f64656c1282568281656d6f64656c818380018207820665616c696365001364703a696e148183782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e82568281656d6f64656c818380018207820665616c6963650001178283636f757400a501505c3c5de80a70aba7a6912e427b7718b0025048a92fbc727f4d7ed69005b9f745d4ce0350f3df1105112054d397a04ed0666ca4c8040105820258378210828282066670726f6d70748206754578706c61696e2063617573616c207265706c61798282066674656e616e74820665616c69636583646578697400a5015031ee0198f4f892c3e741eed100a13b98025048a92fbc727f4d7ed69005b9f745d4ce0350f3df1105112054d397a04ed0666ca4c80401058202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618198183505c3c5de80a70aba7a6912e427b7718b0736d6f64656c2e6f75743e616e737765722e696e8257828166616e73776572818380018207820665616c69636500182ba2018250961dad6a19ad6dc36464a3b337506d5c020282850650961dad6a19ad6dc36464a3b337506d5c025090dcc4a4031912c5809a3209963216e082505c3c5de80a70aba7a6912e427b7718b05031ee0198f4f892c3e741eed100a13b98840750961dad6a19ad6dc36464a3b337506d5c0201\na807021166616e73776572128257828166616e73776572818380018207820665616c6963650013676c3a737461727414801780181a505c3c5de80a70aba7a6912e427b7718b0182282508280818380018207820665616c69636500\na607021166616e73776572128257828166616e73776572818380018207820665616c696365001364703a696e148183736d6f64656c2e6f75743e616e737765722e696e82568281656d6f64656c818380018207820665616c6963650001178183636f757400a501507e8bba5f41e34f6dd8c6326184317c3f02505c3c5de80a70aba7a6912e427b7718b00350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c696365\nseal 1edd9d70d157cdac9a426e4b84934e0cd1b77792f9e23eba7cad434db11d358f\n```\n\n</details>\n\n## Carry forward\n\nAsk two separate questions in every stateful flow: \"whose state?\" and \"for\nhow long?\" A key answers the first, a lifetime the second. Neither alone\nmeans that a duplicate request will be ignored. The next chapter will make\nthat policy an explicit piece of state.\n\nPrevious: [File pipeline](/examples/02-file-pipeline.md). Next:\n[Webhook to partner](/examples/04-webhook-to-partner.md), combining these mechanisms\ninto an integration you can qualify before its partner is ready.\n\n## Limits\n\nThe Process mock is stateless: the admitted request and explicit logical time\nselect its reply. Only Alice's request at time zero is silent.\nNo real language model or paid API is used. The instance key isolates state but\ndoes not guarantee deduplication or persistence across a deployment restart.\nThe fixed backoff is one second.\n"},{"path":"/guide/03-connectors-and-outcomes","title":"Connectors and outcomes","description":"Read a Connector Contract, choose a supported mode, and route data and terminal outcomes explicitly.","text":"---\ntitle: Connectors and outcomes\ndescription: Read a Connector Contract, choose a supported mode, and route data\n  and terminal outcomes explicitly.\nurl: https://docs.rastok.com/guide/03-connectors-and-outcomes\nsource_revision: v0.2.0-alpha\n---\n\n# Connectors and outcomes\n\nAfter this chapter you can distinguish a Connector declaration from its\nDriver, find the supported modes in your binary, and route both useful\ndata and terminal outcomes. You can explain why admission, completion and\nbusiness success are different facts.\n\n## Ask the catalogue first\n\nRun this command from the checkout or an installed CLI:\n\n```sh\nrastok connectors\n```\n\nIt lists compiled capabilities without starting a Driver. Read the exact\nContract id, mode, port types, required attributes, checker support, Lab\nsupport and installed implementations separately. A Contract known to the\ncompiler does not imply that your binary includes its physical Driver.\nLikewise, listing a conformance fixture does not mean the command ran it.\n\nThe executable standard families are Process, File, HttpClient, HttpServer,\nWebSocketClient and WebSocketServer. The catalogue also describes deferred\nfamilies or modes. A File `watch` entry is not permission to use it today.\nThe [current status](/index.md#what-is-available-today) remains the starting\npoint for the alpha's limits.\n\n## One Contract, different operations\n\nThe reader in `examples/file-pipeline.rkg`, lines 10–15, declares one\nbounded operation per input:\n\n```rkg\nconnector read_file : File {\n  mode = read\n  path = data as string\n  max_read = \"64KiB\"\n  timeout = duration(\"2s\")\n}\n```\n\n`path` is resolved for the invocation from its input. It is a logical path\nrelative to the root supplied to the physical File Driver, not permission\nto read an arbitrary host path. That root is a resolution base, not a\nportable security sandbox. The read publishes the complete bytes or no\n`out` value; exceeding `max_read` produces `ReadLimitExceeded`.\n\nThe writer, lines 26–30, selects another mode of the same Contract:\n\n```rkg\nconnector write_file : File {\n  mode = replace\n  path = \"copy.txt\"\n  timeout = duration(\"2s\")\n}\n```\n\nIt consumes bytes and reports a terminal outcome. Replacement is atomic\nwhere the platform supports the promised operation; otherwise the result\nis `AtomicReplaceUnavailable`, not an in-place fallback. Atomic visibility\ndoes not promise crash durability. Directories are refused by name rather\nthan traversed as an implicit collection of files.\n\nA mode resolves the operation's direction, exchange and port behavior.\nThe physical Driver and the Lab model implement the same checked Contract.\nSimulation substitutes the external work while preserving request validation\nand the declared ports. Driver selection is a deployment choice.\n\n## Data is not the terminal outcome\n\nFor File `read`, `out` carries bytes and `exit` closes the Call. For File\n`replace`, successful `out` is impossible; completion is still reported\non `exit`. Process uses `err` for stderr. HTTP Contracts have no implicit\n`err`. The names are conventions whose actual meaning comes from the\nresolved Contract, not three universal success and fault channels.\n\nThe file Graph names each outcome on both exits. Here is the reader at lines 37–41:\n\n```rkg\nread_file.exit -> match {\n  Completed -> nothing\n  AtomicReplaceUnavailable | InvalidPath | IoFailed | NotAFile | NotFound\n    | OutcomeUnknown | PermissionDenied | ReadLimitExceeded | TimeoutExpired -> failed\n}\n```\n\nSuccessful terminals are deliberately discarded. Other cases cross the\nApp's `failed` output. These emissions remain observable in the journal\neven when their destination is `nothing`. An invocation's `exit` does not\nstop the whole Node instance; an instance may serve further invocations.\n\nWhen joining a Call's body and `exit`, route every terminal that accompanies\na body to that join. Otherwise a retained body can pair with another Call's\nterminal: `W-JOIN-UNPAIRED` warns about this. A streamed port cannot pair\nzero or more frames with one terminal. To isolate Calls, use a correlation\nkey shared by the body and terminal of just that Call. Declare the joining\nOperator's lifetime and bound the join with `within` or `last`, with `expired` routed.\nA join bound neither separates Calls nor closes their instances.\nSee [joins and expiry](/guide/06-instances-state-and-time.md).\n\n## Admission is not business success\n\nThe webhook listener, from `examples/webhook-to-partner.rkg`, lines 23–28,\nuses the default `ack` mode:\n\n```rkg\nconnector listener : HttpServer {\n  listen = \"127.0.0.1:8080\"\n  path = \"/events\"\n  codec = json\n  max_body = \"16 KiB\"\n}\n```\n\nA successful accepting commit precedes the HTTP 202 response. That response\nmeans admitted, not processed. Decoded but business-invalid data can then\nreach the validation Operator and be rejected. Malformed JSON refused\nbefore admission creates no invented graph Call or `exit` to assert on.\nA decoded Lab injection therefore cannot qualify the physical JSON decoder.\n\nFor an outbound HttpClient, a usable decoded 500–599 response produces\n`ServerError` and a response body, not a transport fault. Other decoded\nstatuses use `Completed`; the graph still decides which mean business\nsuccess. An incompatible response body produces `DecodeFailed`. A timeout\ndoes not establish that the remote side did nothing.\n\nBefore asking an outbound Driver to act, the runtime commits the operation's\nobligation. Its completion then returns through the typed boundary and\njournal. In this alpha that journal is in memory; ordering before an effect\nis not a claim of durable recovery after process loss.\n\nThe normative descriptions are [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md),\n[`docs/spec/delivery-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/delivery-semantics.md) and [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md). Checking rejects\nunknown settings, incompatible port types and missing possible-output\ndestinations before execution. Real-world compliance still needs separate\nDriver and integration evidence.\n\n## Summary\n\n- Contract, mode and physical implementation answer different questions.\n- Payload outputs and the terminal `exit` are independently typed.\n- Explicit dispositions account for every possible result.\n- Admission and a decoded HTTP response are not business success.\n\n## Next\n\nContinue with [The Lab](/guide/04-the-lab.md). Use\n[File pipeline](/examples/02-file-pipeline.md) to inspect named file\nrefusals, then [Webhook to partner](/examples/04-webhook-to-partner.md)\nto follow admission, validation and the partner's terminal outcome together.\n"},{"path":"/reference/connectors/http-client","title":"HttpClient","description":"Ports, terminal outcomes, settings and qualification evidence for the HttpClient connector.","text":"---\ntitle: HttpClient\ndescription: Ports, terminal outcomes, settings and qualification evidence for\n  the HttpClient connector.\nurl: https://docs.rastok.com/reference/connectors/http-client\nsource_revision: v0.2.0-alpha\n---\n\n# HttpClient\n\n`std/http-client@1`. One HTTP request per Call. Usable response bodies include non-success statuses. Decoded 500–599 responses use `ServerError`; other final statuses use `Completed`. A body decoding fault takes precedence over status classification.\n\n## Declaration\n\nFor an `http://` URL, the default is HTTP/1.1. To contact a server that\nrequires cleartext HTTP/2, set `versions = [\"http/2\"]`. An HTTPS URL\ncontinues to use the declared order.\n\nThis declaration comes from `crates/rastok/src/lab.rs`. Place the Connector in a Graph\nand wire its ports; the excerpt alone is not an App.\n\n```rkg\nconnector network : HttpClient {\n  url = \"https://example.test/v1\"\n  timeout = duration(\"5s\")\n  codec = json\n  idempotent = true; behavior = deterministic\n}\n```\n\nThe [contract index](/reference/contracts.md) explains shared settings, build features\nand the distinction between a Contract, a Lab model and an installed Driver.\n\nCalls on one instance are serialized; [queue time counts toward `timeout`](/reference/execution.md#instances-own-state-not-threads).\n\n| Mode | Driver direction | Exchange | Lab model | Installed in this binary |\n|---|---|---|---|---|\n| No selector | outbound | call | `lab-call` | Not compiled |\n\n## Ports and completion\n\n| Mode | Port | Direction | Type rule |\n|---|---|---|---|\n| all | `in` | input | `codec = bytes` → `array<byte>`; `codec = json` → `variant`; `codec = string` → `string` |\n| all | `out` | output | `codec = bytes` → `array<byte>`; `codec = json` → `variant`; `codec = string` → `string`; explicit JSON response type admitted |\n| all | `exit` | output | HttpClientExit, below |\n\n| Mode | Output cardinality |\n|---|---|\n| all | Status 204 or 205: `Completed` with no `out`. Other `Completed` and `ServerError`: one `out`. Every Call ends with one `exit`. |\n\n## Exit union\n\n| Case | Payload | Call visibility |\n|---|---|---|\n| `BodyTooLarge` | `{ limit: ulong }` | outcome_unknown |\n| `Completed` | `{ status: int }` | after_effect |\n| `ConnectFailed` | Empty | before_effect |\n| `DecodeFailed` | `{ message: string }` | outcome_unknown |\n| `DnsFailed` | Empty | before_effect |\n| `OutcomeUnknown` | Empty | outcome_unknown |\n| `ProtocolFailed` | Empty | outcome_unknown |\n| `ServerError` | `{ status: int }` | after_effect |\n| `TimeoutExpired` | Empty | outcome_unknown |\n| `TlsFailed` | Empty | before_effect |\n\n## Settings\n\nWith `codec = json`, `rastok check` refuses a producer whose resolved type\ncontains a [value without a JSON form](/reference/types.md#json-request-values), using\n`E-TYPE-INVALID`. A `variant` producer is checked at execution instead: an\nunencodable request ends the Call with `DecodeFailed` before it is sent.\nIts message names `in` and the required codec representation. The JSON\ninput is a `variant`; its object keys are not declared field names.\n\nFor a typed JSON **response**, a `timestamp` field reads a UTC string such\nas `\"2026-01-05T08:30:00.25Z\"`. A `timestamp?` also admits `null`.\nAn invalid or offset date ends the Call with `DecodeFailed` and no `out`\ndelivery. In a `data is DecodeFailed` branch, `data.message` identifies\nthe response field and what it expected. If the body is not JSON it names\n`out` instead. The message contains neither the rejected value nor a\npeer-supplied map key. To inspect the original value, receive it as a string or leave\nthe response untyped.\n\nA request URL can include a numeric identifier: `url = \"https://example.test/jobs/\" + string(data.id)`.\nThe number becomes a string explicitly; the JSON request codec does not change.\n\n| Mode | Setting | Domain | Presence / default | Latest phase |\n|---|---|---|---|---|\n| all | `auth_bearer` | `string` | optional | invocation |\n| all | `behavior` | `deterministic \\| probabilistic` | required | plan |\n| all | `codec` | `bytes \\| json \\| string` | required | plan |\n| all | `json_profile` | `projected` | optional | plan |\n| all | `idempotent` | `bool` | `false` | plan |\n| all | `headers` | `HTTP headers` | optional | invocation |\n| all | `custom_headers` | `map<string,array<string>>` | optional | invocation |\n| all | `idempotency_key` | `string` | optional | invocation |\n| all | `max_body` | `ByteSize` | `\"8MiB\"` | plan |\n| all | `method` | `string` | `\"GET\"` | invocation |\n| all | `timeout` | `duration` | required | instance |\n| all | `tls_ca` | `array<byte>` | optional | instance |\n| all | `tls_certificate` | `array<byte>` | optional | instance |\n| all | `tls_private_key` | `array<byte>` | optional | instance |\n| all | `url` | `string` | required | invocation |\n| all | `versions` | `array<http/1.1 \\| http/2 \\| http/3>` | `[\"http/3\", \"http/2\", \"http/1.1\"]` | plan |\n| all | `zero_rtt` | `disabled` | `disabled` | plan |\n\n`codec = json` permits an explicit `output out: Response`. `json_profile = projected` additionally skips extra members and fills absent nullable fields, while rejecting malformed required values. `auth_bearer = secret(...)` and `url = env(...)` use the declared boot-reference seam even though the table lists each setting's latest general phase. Those references are resolved from deployment configuration at startup, not from an input envelope. There is no automatic redirect or Retry: the graph declares its Retry policy.\n\n## Qualification inventory\n\nfixture `crates/rastok/tests/conformance_http_client.rs`. Cases without a portable forced fixture: `DnsFailed`, `OutcomeUnknown`. Related tests: `crates/rastok/src/connector/drivers/network/http_client.rs`.\n"},{"path":"/reference/expressions","title":"Expressions and dispatch","description":"Operator precedence, built-in functions, narrowing, transaction dispatch and envelope writes accepted by the compiler.","text":"---\ntitle: Expressions and dispatch\ndescription: Operator precedence, built-in functions, narrowing, transaction\n  dispatch and envelope writes accepted by the compiler.\nurl: https://docs.rastok.com/reference/expressions\nsource_revision: v0.2.0-alpha\n---\n\n# Expressions and dispatch\n\nAn expression reads its declared inputs and returns a value. Dispatch selects\nthe statements of an Operator transaction. Neither performs external I/O;\nConnectors own that boundary.\n\n## Operators\n\nRows are ordered from highest to lowest precedence. Parentheses select an\nexplicit grouping. Operators at the same arithmetic or comparison level\nassociate left to right; the conditional's false branch associates right.\n\n| Level | Syntax | Rule |\n|---|---|---|\n| Access and narrowing | `data.name`, `(flag ? left : right).name`, `items[index]`, `value as T` | A named or computed receiver exposes the same declared fields; indexes require a checked collection |\n| Unary | `!value`, `-value` | Boolean negation; numeric or duration negation |\n| Multiplication | `*`, `/`, `%` | Numeric operations in the operands' common integer or floating type |\n| Addition | `+`, `-` | Numeric operations in the common type, string concatenation, supported timestamp/duration arithmetic |\n| Comparison | `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `is T` | Equality, ordering, membership and type/case tests |\n| Conjunction | `a && b` | Short-circuits when `a` is false |\n| Disjunction | `a \\|\\| b` | Short-circuits when `a` is true |\n| Conditional | `test ? yes : no` | Evaluates only the selected branch |\n\n`\"red\" in [\"red\", \"blue\"]` is true: an array tests its elements.\n`\"red\" in {\"color\": \"red\"}` is false: a map tests its keys, so\n`\"color\" in {\"color\": \"red\"}` is true. Neither form introduces an iteration variable.\n\nAn unsupported operand combination reports the written operator and types,\nfor example `` `+` does not accept array<string> and array<string> ``. List\nconcatenation with `+` is not available in this version. Optional element\ntypes appear as `array<string?>` in type refusals.\n\nFor an optional input carrying null, `data == null` is true and\n`data != null` is false. Whole inputs, optional fields and state cells\nfollow the same comparison rule, including in guards and conditionals.\n\n### Numeric operands in this alpha\n\nThe [numeric type table](/reference/types.md#numeric-types) lists source names,\nrepresentations and the operations each family supports. A literal first\ntries the other operand's type. Otherwise both values need a common type:\n`int + double` computes in `double`, but `long + double` is refused because\nnot every `long` fits. Arithmetic and ordering on `decimal` and\n`decimal(p,s)` are not defined. For money, compute in integer minor units\n(cents) and keep the exact decimal for carrying and projection.\n\nEach operation on two `float` values rounds its result to binary32 before\nthe next operation. A `double` uses binary64.\n\nIf `u` is a `uint` holding 7, `u == 7` is true and `3 < u` is true:\nthe literal takes the other operand's integer type if it fits. The rule\nalso applies across the arms of a conditional: for a `long` named `n`,\n`ready ? n : 1` and `ready ? 1 : n` both return a `long`. Comparing a\ncalculated `int` or `long` with a `uint` uses `long`. A signed integer and\nan `ulong` have no common integer type. With `u: uint?`, `u == 7` still tests for\nseven; it is false when `u` is null. An `int` compares with a `double`\nas a `double`, and every integer compares with a `decimal` as a `decimal`.\nA `long` or `decimal` and a `double` have no common type. Use a checked\nconversion (`as?`) and handle absence to compare a particular value.\nIn a `decimal` position, `(7u as decimal) == decimal(\"7.00\")` is true.\nLists, records, map values and Lab expectations use the same rule.\nComparing does not change what you see: `string(decimal(\"7.0\"))`\nreturns `\"7.0\"` and `string(decimal(\"7.00\"))` returns `\"7.00\"`.\n\n`value as T` with `T` a declared `decimal(p,s)` (for example\n`type Price = decimal(18,2)`) accepts an exact integer or `decimal` that fits.\n`7 as Price` produces exactly `7.00`; exceeding the declared precision or\ndiscarding non-zero digits is a narrowing fault, never rounding. A\n`decimal(\"…\")` literal is itself a `decimal`, so a Lab expectation against\na `Price` port can use `expect app.out == { b = decimal(\"2.50\") as Price }`.\n\nNumbers carried by `variant` compare by value: a signed seven, an unsigned\nseven and an exact decimal `7.00` are equal. A binary floating value meets\nan exact number through its shortest decimal rendering, not a tolerance.\n\nFor a JSON number in a `variant`, `as?` checks the carried value: seven\nconverts to `double`, and 19.99 converts to `decimal(10,2)`. `is` tests\nthe carrier and never performs the conversion.\n\nInteger overflow and integer division by zero are evaluation faults. An index,\nmap key or narrowing that can fail refuses at check; `[?i]`, `.?k` and `as?`\nreturn an optional value to test or default. A fault commits no input consumption,\nstate change or emission from that transaction. Expected domain rejection\nmust be represented by an authored branch and output.\n\nExpressions are limited to 128 nesting levels. The serialized plan has a\nseparate 256-level reader bound; nested values can reach it even when the\nexpression itself fits.\n\n## Functions and contextual references\n\nEmpty collections use the type expected at their position. Without one,\n`[]` is `array<variant>` and `{:}` is `map<string,variant>`, including in a\nbinding or an inferred struct field. A destination requiring more precise\nelements refuses that binding with `E-PORT-TYPE`: declare\n`val members: array<string> = []` or `var counts: map<string, int> = {:}`.\nNonempty collections infer their type from their elements. Numeric elements\nmeet at their common type; when the elements have no common type, they\ninfer `variant`. `{}` is a struct, never an empty map.\n\nAt a typed position, each list element and each map value is checked\nindividually. For example, `[null, data]` fits `array<string?>` when `data`\nis `string`. A declared `array<decimal>` can hold a whole decimal and a\nfraction even when their precisions do not fit in a single fixed decimal.\nThe same rule applies to both arms of a conditional and to the present\nvalue and the fallback of `.orValue()`. Without an expected type,\n`[null, \"a\"]` remains `array<variant>`.\n\n`{:}` also works inside expressions: `size({:})` is `0`, and map values\nand list elements may contain an empty map.\n\n| Signature | Result | Availability and constraints |\n|---|---|---|\n| `s.contains(t)` | `bool` | Tests whether the string `t` occurs in the string `s` |\n| `s.startsWith(t)` | `bool` | Tests the exact prefix, including an empty one |\n| `s.endsWith(t)` | `bool` | Tests the exact suffix, without case folding |\n| `size(string \\| array<byte> \\| array<T> \\| map<K,V> \\| variant)` | `int` | Unicode character count for strings, byte count for byte arrays, entry count otherwise |\n| `has(object.member)` | `bool` | Final-member presence on a closed struct or string-keyed map; present null is true; only dotted selection |\n| `now()` | `timestamp` | One transaction-fixed civil instant, derived from the run origin and logical time; handler context only |\n| `duration(string)` | `duration?` for runtime text, `duration` for a valid constant | Units `h`, `m`, `s`, `ms`, `us`, `ns`, with an optional leading minus. Components can be combined and fractional, but each must resolve to whole nanoseconds. No `min`, `d` or `w`. |\n| `timestamp(string)` | `timestamp?` for runtime input | RFC 3339 UTC spelling ending in `Z`; an unsupported offset or invalid date yields null |\n| `decimal(string)` | `decimal?` for runtime input | Exact decimal at its written scale, with no binary-float conversion |\n| `string(x)` | `string` | Renders a string, bool, integer, exact number, float, UTC timestamp, duration or enum symbol. Narrow optional and variant values first. |\n| `asset(path)` or `asset(path, content_type)` | `array<byte>` | Build-time file contents; the second argument is for a whole-payload position and sets its content type |\n| `env(name)` | Boot reference | Admitted at the HttpClient URL setting, resolved by the deployment profile |\n| `secret(name)` | Boot reference | Admitted at HttpClient `auth_bearer`; no raw secret value in graph data |\n\n`duration(\"4.1ms\")` and `duration(\"4100us\")` are equal. A fraction such as\n`0.1ns` is refused at check for a constant and yields null for a runtime string.\nFor all four string constructors a valid constant keeps the ordinary result\ntype. A malformed constant is an error even inside a reaction.\nFor a declared decimal type `Price`, use `decimal(string(x)) as? Price` to\nrecover the same value and type.\n\n`env` and `secret` are references, not evaluator functions. Other sites refuse.\n`has` does not establish the value's type: use `is` before reading it as a\nnumber or another narrower type. The receiver still has to be evaluable.\n`now` has no arguments and is unavailable in keys, settings or boot values.\n\n## Narrowing and dispatch\n\n| Form | Selection | Requirement |\n|---|---|---|\n| `value is T` | Tests a type or tagged case | A positive fact narrows the right side of `&&`, a conditional's true branch, a guarded handler or a guarded match arm; the narrowed value can be used directly, without repeating `as T`. Assigning its state cell or the cell containing its path ends the fact for subsequent statements, which see the declared type again |\n| `value as T` | Proven conversion | The types fit, a constant converts exactly, or an `is` or closed-case arm proves this path |\n| `value as? T` | Optional conversion | A mismatch returns null; an ambiguous or malformed discriminator is still a fault |\n| `rows[?i]`, `entries[?key]`, `entries.?name` | Optional lookup | Returns null for an absent receiver, an out-of-range index or a missing key |\n| `row.?name` | Optional struct field | The field must be declared; a null receiver gives null |\n| `result.orValue(default)` | Default for `T?` | Both numeric choices must fit a declared result type; otherwise their common type is inferred. The default runs only when the result is absent. For a `uint?`, `.orValue(3)` and `.orValue(3u)` are equivalent. |\n| `match value { Case => ... }` | Closed match | Tagged union, enum or bool; exhaustive, disjoint case sets. A single-case arm exposes the matched path's payload fields; the whole value keeps its case |\n| `match { predicate => ...; _ => ... }` | Ordered predicates | First true predicate wins; fallback is mandatory |\n| `on in where predicate { ... }` | Single-input filter | False consumes the input and emits nothing |\n| `on (a, b) where predicate ...` | Join candidate selection | False consumes nothing; bounded waiting is covered in [Instances, state and time](/guide/06-instances-state-and-time.md) |\n\nA positive `data is Line` branch can construct an output record with\n`{ id = data.id }`: the field keeps the type that `Line` declares.\n\nA dynamic string may be too long for `string(3)?`. Use\n`data as? string(3)` and handle null. For a narrower array element,\ncheck the element before constructing the array.\n\nWith an `array<long>?` destination, `data.c ? [1] : null` yields the\ndeclared list or null. The same rule applies to a map literal.\n\nBetween numeric types, `as?` returns null if the value would change. A\nbinary float is worth the number shown by its shortest rendering:\n`0.1 as? decimal` gives the exact number 0.1, while `7.5 as? int` gives\nnull. A float also accepts an exactly representable value even if it displays\nfewer digits: `4.099999904632568359375 as float` displays `4.1`. A literal\nthat fits `double` and whose resulting binary64 value is exact in `float`\nalso fits: `0.10000000149011612 as float` displays `0.1`. A declared\ndecimal can be the target directly: `n as? decimal(5,2)`.\n\nFor a `map<string,variant>`, `m[?k]` returns the stored value or null.\nUse `(m[?k] as? string).orValue(\"missing\")` if you need a string even\nwhen the key is missing or the stored value is not a string.\n\nA match is the final control form of its block or arm. Only pure `val`\ndeclarations precede it. Dispatch permits at most 32 nested decisions,\nincluding a single-port `where`. A `variant` must be narrowed before member\nor index access. A negative test or disjunction supplies no inferred positive\ntype fact.\n\nInside `Stored => { ... }`, a match on `data` permits `data.name` when\n`Stored` declares that field. `out = data` and `out = .` still emit the\ncomplete `Stored { ... }` value. Several cases in one arm do not expose\ncase-specific fields. Assigning the matched state cell ends the selection.\n\nLater `is` tests can read paths narrowed by earlier tests, for example\n`data is Booked && data.receipt is Receipt && data.receipt.note is string`.\nEach test is evaluated only after the preceding tests succeed.\n\nAfter a type test, fields, indexes and `has` read the selected value of an\ninput just as they read a state cell. This also applies after `val copy = data`.\nCopying or passing the value without reading its structure does not decode\nit; type tests and conversions still use its retained union branch.\n\nFor a tagged union `Event` with cases `Opened` and `Closed`, an `Event?`\nvalue satisfies `value is Event` whenever either case is present. It\nsatisfies `value is Opened` only for that case. Both tests are false for\nnull. After a successful case test, its payload fields can be read.\n\nA struct assigned to a declared type also constructs any optional fields\nthat the destination requires. You can bind an inferred struct first and\nthen use it in a typed field or output; the original binding keeps its type.\n\nRoute selection is separate: `source -> match { Case -> target }` chooses\namong declared destinations using a tag, enum or bool. Its arms contain\ndestinations, not expressions. A simple route may coexist with a match,\nbut duplicate destinations for one case refuse.\n\n## Fan-out and emission\n\nThe shipped fan-out is bounded by the graph and the selected match arm.\nThere is no collection-iteration statement in that arm.\n\n| Form | Result |\n|---|---|\n| `source -> { left; right }` | One emitted envelope delivered along two declared edges |\n| `(left, right) = data` | Evaluate once, then emit a distinct ordered envelope on each output |\n| `(left, right) = (first, second)` | One value per named output, committed together |\n| `out = .` | Re-emit the exact single input envelope |\n| `out = nothing` or `nothing` | No emission |\n| `out = { count = 1 }` | New structured data, inherited metadata |\n| `out = { data = replacement, meta.app.label = \"checked\" }` | New payload plus explicit metadata writes |\n\nEmission order within each port and transaction contributes to identity.\nAn edge fan-out does not duplicate the emission itself. Iteration over state\nuses [Loop](/guide/07-loops-and-retries.md), whose manager admits subsequent\napplications outside the spatial DAG.\n\n## Envelope fields and bindings\n\nOn a struct port, `out = { data = data; meta.app.tag = \"copy\" }` copies\nthe input payload and sets metadata. A field named `data` inside a\npayload struct is written under the outer `data` root.\n\n| Surface | Read | Write |\n|---|---|---|\n| `data` | Payload of the current single input | Construct a new output payload or checked patch |\n| `meta.sys.id`, `parent_id`, `origin_id`, `graph_version` | Runtime identity and version fields | Runtime only, including in the Lab |\n| `meta.app.*` | A required read has the field type inferred from graph-authored writes; no cast is needed | Declared-by-use application metadata; conflicting types refuse |\n| `meta.ext.*` | Contract-declared boundary context | Declared fields only; the payload/content-type coupling remains enforced |\n| `instance.key` | Selected key of this owner, with fields for a struct key | Read-only in handlers, owner bindings and instance-bound settings; not in its own definition or an unkeyed child |\n| `Loop.state` | Envelope admitted to the current Loop application | Replaced through a manager command, not mutated directly |\n| `<port>.data`, `<port>.meta` | Named inputs in a join | Emissions select a named source explicitly |\n\nIn this build a metadata leaf is a scalar (`int`, not `uint`; no duration\nor timestamp) or an array of scalars.\nThe `app` and `ext` namespaces have prefix-free field names. Heavy or nested\npayload structures belong in `data`. A Lab cannot introduce application\nmetadata fields absent from the production graph.\n\n`val name = value` is immutable and lexical. Unit/App constants can be\nreferenced by Lab declarations; instance-level values can use that owner's\nkey and enclosing immutable values.\n\n`var name: Type = value` is mutable Operator state for one instance\ngeneration. Its initial value is required, even when the type allows null.\nInside a handler an assignment takes effect at once: later\nstatements read the new value. The change is committed with the\ntransaction; a faulted transaction keeps the previous value. Children do\nnot inherit it.\n\n## Tagged frontends\n\n| Form | Result | Boundary |\n|---|---|---|\n| `json! <JSON value>` | `variant` | One complete JSON value; duplicate keys refuse. A number must fit `long`, `ulong` or `double` without loss. |\n| `string! { ... }` | `string` | Verbatim text, closing-delimiter margin, no interpolation |\n| `base64! { ... }` | `array<byte>` | Padded standard base64; whitespace ignored |\n\nThe name and `!` are adjacent. A frontend fills a complete value position,\nnot an expression atom. Bind its result before combining it with arithmetic.\n`base64!(\"image/png\") { ... }` may also declare content type in a whole-payload\nposition.\n\n## Specified, not shipped\n\n| Item | Specification |\n|---|---|\n| Regular expression matching (`s.matches(pattern)`) | Not part of the three string predicates in D-2026-11-28-1 |\n| Per-item fan-out (`foreach` is reserved); `for item in` is not accepted | [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), reserved-keyword section |\n| Expression macros `exists`, `exists_one`, `all`, `map` and `filter` | [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), expression production; current subset in [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1.1 |\n| Array concatenation with `+` | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1.1; use a list literal for known elements. |\n| jq, SQL and additional registered guest-language implementations | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §§2–3 |\n| `map<string, array<scalar>>` metadata leaves | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) §0 |\n| Unit/App boot values using `env` or `secret` outside the declared settings | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1 |\n\nSources: [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md), [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md),\n[`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) and [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §1.1.\n"},{"path":"/examples/04-webhook-to-partner","title":"Webhook to partner: put it together","description":"Admit a webhook, validate and deduplicate it, then exercise bounded partner retries with privacy, secret and cost evidence.","text":"---\ntitle: \"Webhook to partner: put it together\"\ndescription: Admit a webhook, validate and deduplicate it, then exercise bounded\n  partner retries with privacy, secret and cost evidence.\nurl: https://docs.rastok.com/examples/04-webhook-to-partner\nsource_revision: v0.2.0-alpha\n---\n\n# Webhook to partner: put it together\n\nThis program accepts a webhook, rejects invalid or duplicate events and sends accepted events to a partner.\n\nYou know how to replace an effect, route its outcomes and isolate state. Now\nuse those ideas for a familiar integration: receive a webhook and deliver it\nto a partner that is not always available. Build the flow and its fault\nscenarios together, before you need a live partner environment.\n\nAll six scenarios have versioned goldens. The captures below show native\nRetry retaining a failed attempt and publishing the final outcome.\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root:\n\n```sh\nenv RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential \\\n    RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 \\\n    rastok simulate examples/webhook-to-partner.rkg \\\n      --deployment examples/webhook-to-partner.deployment.json \\\n      --compare examples/traces/webhook-to-partner\n```\n\n```text\nPASS webhook.nominal\nPASS webhook.timeout_then_success\nPASS webhook.partner_dead\nPASS webhook.duplicate\nPASS webhook.invalid_payload\nPASS webhook.http_500\n6 scenario(s), 0 failed\n```\n\nAdd `--ui` to inspect the same graph.\n\n```sh\nenv RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 rastok simulate examples/webhook-to-partner.rkg --deployment examples/webhook-to-partner.deployment.json --compare examples/traces/webhook-to-partner --ui\n```\n\nThis requires `hosted-ui`. Open the private loopback URL printed by the CLI. No HTTP listener, real partner or paid\nAPI is started. The value above is a **fictional fixture**, not a credential.\nFor real deployments, supply secret material out of band, never in source,\nprofile JSON or shell command text. The profile contains only its coordinate\nand version. The same Contract is used with a scripted or physical Driver.\n\nFor the controls and source view, see [the debugger tour](/debugger.md).\n\n## Read the program\n\nFollow the main path first: `listener`, an [HttpServer](/reference/connectors/http-server.md), admits, `validate` checks the business\ndata, `deduplicate` owns a `seen` flag per event, and `deliver` contains the\nbounded partner retry. Open that scope to find `request`,\n`partner : HttpClient + Retry` ([HttpClient](/reference/connectors/http-client.md)) and `decide`. The response type `Receipt`\nannotates the charge where the Connector retains it, before any decision to\nhold or publish the attempt.\n`decide` classifies the final business outcome; it contains no retry logic.\n\n`var seen: bool = false` declares mutable state inside `deduplicate`.\nEach `data.event_id` selects an Operator instance with its own flag,\ninitialized to `false` when that instance is created. The first event sets\nit to `true` and is forwarded; a later arrival with the same key reads that\ncommitted value and takes the duplicate branch. The assignment and emission\ncommit together. This is not a global variable or durable deduplication:\nafter the instance closes, a new generation starts with `false` again.\nSee [Values and mutable state](/guide/06-instances-state-and-time.md#values-and-mutable-state)\nbefore changing the handler.\n\nThe `deliver` Graph is also keyed by event id. Like `deduplicate`, it closes\nafter five minutes without an admission. A Retry can finish within that\nwindow, but the App does not keep a delivery instance for every event forever.\n\nThen read the declarations that constrain the path: the idle lifetime, the\npartner's idempotency key, the exhaustive destinations, `@personal` and the\nsecret reference. These are reviewable parts of the program and deployment,\nnot separate conventions the reader must guess from the happy path.\n\nThe [Lab reference](/reference/lab.md) explains mock responses, expectations\nand observation windows. `advance` supplies virtual time; a mock's terminal\nresponse ends its simulated exchange, not the whole scenario.\n\n<a id=\"graph\"></a>\n\nSource: `examples/webhook-to-partner.rkg`\n\n```rkg\n// A webhook acknowledges requests, skips repeat deliveries and retries a partner call.\n// The Lab supplies fictional requests and partner replies without opening a socket.\ntype Webhook = struct {\n  event_id: string\n  email: string @personal(identifier = true)\n  amount: int\n}\ntype Delivered = struct { event_id: string, status: int }\ntype Failure = union {\n  Rejected { reason: string }\n  PartnerFailed { event_id: string, terminal: HttpClientExit }\n}\ntype Receipt = struct {\n  charge: decimal(38,18) @measure(id = amount, unit = \"USD\")\n}\ntype Charge = decimal(38,18)\n\ngraph webhook_to_partner : App {\n  output done: Delivered\n  output failed: Failure\n  output duplicate: string\n\n  connector listener : HttpServer {\n    listen = \"127.0.0.1:8080\"\n    path = \"/events\"\n    codec = json\n    max_body = \"16 KiB\"\n  }\n\n  operator validate {\n    input in: variant\n    output out: Webhook\n    output failed: Failure\n    on in match {\n      data is Webhook => match {\n        data.amount > 0 && size(data.event_id) > 0 => out = data as Webhook\n        _ => failed = Rejected { reason = \"positive amount and event id required\" }\n      }\n      _ => failed = Rejected { reason = \"expected event_id, email and integer amount\" }\n    }\n  }\n\n  operator deduplicate {\n    input in: Webhook\n    output out: Webhook\n    output duplicate: string\n    instance = { key = data.event_id }\n    lifetime = { kind = idle; max = duration(\"5m\") }\n    var seen: bool = false\n    on in match {\n      seen => duplicate = data.event_id\n      _ => {\n        seen = true\n        out = data\n      }\n    }\n  }\n\n  graph deliver {\n    input in: Webhook\n    output done: Delivered\n    output failed: Failure\n    instance = { key = data.event_id }\n    lifetime = { kind = idle; max = duration(\"5m\") }\n    closing = { drain_for = duration(\"1s\"); settle_for = duration(\"1s\") }\n\n    operator request {\n      input in: Webhook\n      output out: variant\n      on in {\n        // JSON erases the field schema: retain personal-data policy on the\n        // opaque body, while the non-personal event id remains a typed key.\n        out = {\n          data = data as variant\n          meta.app.event_id = data.event_id\n        }\n      }\n    }\n\n    connector partner : HttpClient + Retry {\n      url = env(\"PARTNER_URL\")\n      auth_bearer = secret(\"showcase/partner/token\")\n      method = \"POST\"\n      codec = json\n      output out: Receipt\n      timeout = duration(\"1s\")\n      max_body = \"16 KiB\"\n      idempotency_key = meta.app.event_id\n      // Required partner contract: honour this key for the identical request.\n      // This declaration does not prove that a real service honours that contract.\n      idempotent = true\n      behavior = deterministic\n      Retry.attempts = 2\n      Retry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed]\n      Retry.delay = { kind = fixed; after = duration(\"1s\") }\n    }\n\n    operator decide {\n      input in: HttpClientExit\n      output done: Delivered\n      output failed: Failure\n      on in match {\n        data is Completed && data.status >= 200 && data.status < 300 => done = {\n          event_id = meta.app.event_id as string\n          status = data.status\n        }\n        _ => failed = PartnerFailed {\n          event_id = meta.app.event_id as string\n          terminal = data\n        }\n      }\n    }\n\n    in -> request -> partner\n    partner.out -> nothing\n    // On a lost answer, decide keeps the terminal case in the failure it reports.\n    partner.exit -> match {\n      BodyTooLarge | DecodeFailed | OutcomeUnknown | ProtocolFailed | TimeoutExpired -> decide\n      Completed | ConnectFailed | DnsFailed | ServerError | TlsFailed -> decide\n    }\n    decide.done -> done\n    decide.failed -> failed\n  }\n\n  listener.out -> validate -> deduplicate -> deliver\n  listener.exit -> nothing\n  validate.failed -> failed\n  deduplicate.duplicate -> duplicate\n  deliver.done -> done\n  deliver.failed -> failed\n}\n\nlab webhook {\n  mock deliver.partner {\n    on in where data is Webhook && data.event_id == \"dead\" {\n      out = nothing\n    }\n    on in where data is Webhook && data.event_id == \"retry\" && now() == timestamp(\"1970-01-01T00:00:00Z\") {\n      out = nothing\n    }\n    on in where data is Webhook && data.event_id == \"http-500\" && now() == timestamp(\"1970-01-01T00:00:00Z\") {\n      out = { charge = decimal(\"0.01\") as Charge }\n      exit = ServerError { status = 500 }\n    }\n    on in {\n      out = { charge = decimal(\"0.02\") as Charge }\n      exit = Completed { status = 201 }\n    }\n  }\n\n  scenario nominal {\n    listener.out = { event_id = \"ok\"; email = \"alice@example.test\"; amount = 12 }\n    expect listener.exit == Completed { status = 202 }\n    expect app.done == { event_id = \"ok\", status = 201 }\n    expect deliver.partner.in\n    expect deliver.partner.out where data.charge == (decimal(\"0.02\") as Charge)\n    expect app.failed == nothing\n  }\n\n  scenario timeout_then_success {\n    listener.out = { event_id = \"retry\"; email = \"alice@example.test\"; amount = 12 }\n    expect listener.exit == Completed { status = 202 }\n    expect app.done == nothing\n    advance duration(\"1s\")\n    expect deliver.partner.exit == TimeoutExpired {}\n    expect deliver.partner.in == nothing\n    expect deliver.decide.in == nothing\n    advance duration(\"1s\")\n    expect deliver.decide.in where data is Completed\n    expect app.done == { event_id = \"retry\", status = 201 }\n    expect app.failed == nothing\n  }\n\n  scenario partner_dead {\n    listener.out = { event_id = \"dead\"; email = \"alice@example.test\"; amount = 12 }\n    advance duration(\"1s\")\n    advance duration(\"1s\")\n    advance duration(\"1s\")\n    expect app.failed where data is PartnerFailed\n    expect app.done == nothing\n    advance duration(\"10s\")\n    expect deliver.partner.in == nothing\n    expect app.failed == nothing\n  }\n\n  scenario duplicate {\n    listener.out = { event_id = \"same\"; email = \"alice@example.test\"; amount = 12 }\n    expect app.done\n    listener.out = { event_id = \"same\"; email = \"alice@example.test\"; amount = 12 }\n    expect listener.exit == Completed { status = 202 }\n    expect app.duplicate == \"same\"\n    expect deliver.partner.in == nothing\n    expect app.done == nothing\n    advance duration(\"5m\")\n    listener.out = { event_id = \"same\"; email = \"alice@example.test\"; amount = 12 }\n    expect app.done\n    expect app.duplicate == nothing\n  }\n\n  scenario invalid_payload {\n    listener.out = json! { \"unexpected\": true }\n    expect listener.exit == Completed { status = 202 }\n    expect app.failed where data is Rejected\n    expect deliver.partner.in == nothing\n    listener.out = { event_id = \"invalid\"; email = \"alice@example.test\"; amount = -1 }\n    expect listener.exit == Completed { status = 202 }\n    expect app.failed where data is Rejected\n    expect deliver.partner.in == nothing\n  }\n\n  scenario http_500 {\n    listener.out = { event_id = \"http-500\"; email = \"alice@example.test\"; amount = 12 }\n    expect deliver.partner.exit == ServerError { status = 500 }\n    expect deliver.partner.out where data.charge == (decimal(\"0.01\") as Charge)\n    expect deliver.decide.in == nothing\n    expect app.done == nothing\n    advance duration(\"1s\")\n    expect app.done == { event_id = \"http-500\", status = 201 }\n    expect app.failed == nothing\n  }\n}\n```\n\n## Expected result\n\nIn `webhook.nominal`, admission produces the ACK before business validation;\nthe scripted partner then completes the first attempt.\n\n```mermaid\nsequenceDiagram\n    participant lab as Lab: webhook.nominal\n    participant listener as listener: HttpServer\n    participant validate as validate\n    participant dedup as deduplicate\n    participant request as deliver.request\n    participant partner as deliver.partner: HttpClient + Retry\n    participant decide as deliver.decide\n    participant app as webhook_to_partner\n    lab->>listener: Decoded request: event_id = ok\n    Note over listener: Admission ACK: Completed(202), disposed to nothing\n    listener->>validate: out = decoded payload\n    validate->>dedup: out = validated Webhook\n    dedup->>request: First event_id: set seen, forward\n    request->>partner: Body and meta.app.event_id\n    partner->>lab: Scripted POST with idempotency key\n    lab-->>partner: Receipt charge 0.02 USD, then Completed(201)\n    Note over partner: Receipt measured in journal, out disposed to nothing\n    partner->>decide: exit = Completed(201)\n    decide-->>app: done = event_id ok, status 201\n```\n\n`6 scenario(s), 0 failed` covers:\n\n- `nominal`: one `202` ACK and one partner Call ending with `201`;\n- `timeout_then_success`: one second to timeout, one second of backoff,\n  then success on the second attempt;\n- `partner_dead`: two timed-out Calls, then the final `TimeoutExpired`\n  inside the business `PartnerFailed` response, with\n  no further Call even after another ten seconds;\n- `duplicate`: an explicit `seen` state suppresses a second request with\n  the same event id; after five minutes idle, a fresh instance admits it again;\n- `invalid_payload`: decoded JSON with the wrong shape, then a negative\n  amount, both rejected after ACK and without contacting the partner;\n- `http_500`: `ServerError { status: 500 }` is a decoded response; the\n  static `Retry.on` policy selects it, and the second response is `201`.\n\nThe email field is `@personal`. The deployment must attest the in-memory\nprocessing before admission; having a valid secret binding alone is not\nenough. Debugger views redact before formatting. Personal data can remain in\nthe in-memory causal journal: presentation masking is not erasure. The bearer\nis different: its clear bytes never enter the journal at all.\n\nThe declared `output out: Receipt` interprets the fictional partner's `charge`\nfield as an exact amount with `@measure(id = amount, unit = \"USD\")`.\nThat declaration names a quantity and its unit, not a billing policy. No downstream accounting\nOperator is run or replayed to extract it. The nominal reply reports\n`0.02`; the `500` and successful replies retain two separate samples, `0.01`\nand `0.02`, with their causal references. The first is Held by Retry and\nnever reaches `decide`; it remains inspectable in the journal. M1 computes no\ntotal or price and the debugger displays the original DATA, not a cost report. A timed-out Call\nsupplies no charge: missing evidence is **unknown cost, not a zero bill**.\n\n## Break it\n\nChange the single `Retry.attempts = 2` to `Retry.attempts = 1`. The timeout and\n`500` scenarios can no longer succeed on a second attempt. Run the comparison below.\n\n```sh\nenv RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 rastok simulate examples/webhook-to-partner.rkg --deployment examples/webhook-to-partner.deployment.json --compare examples/traces/webhook-to-partner\n```\n\n```text\nFAIL webhook.nominal\n     golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED]\nFAIL webhook.timeout_then_success\n     expect [REDACTED]  (webhook-to-partner.rkg:167)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     expect [REDACTED]  (webhook-to-partner.rkg:169)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     expect [REDACTED]  (webhook-to-partner.rkg:170)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED]\nFAIL webhook.partner_dead\n     expect [REDACTED]  (webhook-to-partner.rkg:179)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED]\nFAIL webhook.duplicate\n     golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED]\nPASS webhook.invalid_payload\nFAIL webhook.http_500\n     expect [REDACTED]  (webhook-to-partner.rkg:215)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     expect [REDACTED]  (webhook-to-partner.rkg:218)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED]\n6 scenario(s), 5 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/webhook-to-partner.rkg\n```\n\n## Read the golden difference\n\nAdd\n`--compare examples/traces/webhook-to-partner`.\nThe CLI names the first differing record and field, expected versus actual,\nand recorded causal context. This classified graph deliberately redacts\nvalues in divergence messages. Recorded operation facts can differ before\nthe final answer does.\nThe versioned goldens contain **only the synthetic fixture data**; they are\nnot sanitized exports suitable for real personal data.\n\n### Why five attempts also fail this comparison\n\n`Retry.attempts` is a maximum including the first Call, not a promise that\nthe partner eventually answers. The `partner_dead` mock stays silent on\nevery attempt. Its scenario expects the final failure after two one-second\ntimeouts and one second of backoff, then expects no further activity.\nWith five attempts, the operation is still waiting at that first assertion:\nthe additional attempts move the final failure into the later observation\nwindow. The scenario no longer describes the configured policy.\n\nThere is a separate reason for a golden divergence. Retry facts record the\noriginal plan's semantic hash. Changing the attempt bound changes that hash,\neven in a scenario whose final business value stays the same. A golden\ncomparison checks those facts, not just the last value on `app.done`.\n\nWith `Retry.attempts = 5`, this command checks only the scenario assertions:\n\n```sh\nenv RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 rastok simulate examples/webhook-to-partner.rkg --deployment examples/webhook-to-partner.deployment.json\n```\n\n```text\nPASS webhook.nominal\nPASS webhook.timeout_then_success\nFAIL webhook.partner_dead\n     expect [REDACTED]  (webhook-to-partner.rkg:179)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\n     expect [REDACTED]  (webhook-to-partner.rkg:183)\n     observed: [REDACTED]\n     Assertion evidence is redacted because this program carries classified data.\nPASS webhook.duplicate\nPASS webhook.invalid_payload\nPASS webhook.http_500\n6 scenario(s), 1 failed\n```\n\nAdding `--compare examples/traces/webhook-to-partner` also detects changed\nRetry facts in every scenario that opens a partner operation. Restore the\nreviewed two-attempt policy after this experiment:\n\n```sh\ngit checkout -- examples/webhook-to-partner.rkg\n```\n\nIf five attempts are an intended policy change, update the exhaustion\nscenario's time advances and expectations, review the changed journal,\nthen save the new reference. Do not overwrite references just to remove a\ndivergence. [Loops and retries](/guide/07-loops-and-retries.md) explains\nthe attempt bound and closure-based delay.\n\n### Inspect the recorded retry\n\nThe following 30-second sequence visits recorded states of\n`webhook.timeout_then_success`: admission, timeout, backoff and successful\nsecond attempt. During the backoff, Retry retains the failed batch without\ndelivering it to `decide`; only the final result is published. These are real\ndebugger views of a simulation, not live HTTP requests or an edited branch.\nThe graph is shown at Readable size, where the view follows the Node of each\ntransition; Fit graph shows the complete drawing.\n\n![Thirty seconds through the recorded timeout and retry transitions](/assets/webhook-tour.png)\n\nThree stills make the checkpoints easier to inspect:\n\n- [Before admission, transition 0](/assets/webhook-before.png).\n- [Retry backoff scheduled, transition 20](/assets/webhook-backoff.png).\n- [Success after two attempts, transition 34](/assets/webhook-completed.png).\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/webhook-to-partner/webhook.nominal.rkc`\n\n```rastok-trace\na9070108a40150f09d9a552439b865d3e4c81c1d1153130350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b09686c697374656e65720a000b000c636f75740d818278186c697374656e65722e6f75743e76616c69646174652e696e824c82816876616c696461746580000f81686c697374656e6572108250f09d9a552439b865d3e4c81c1d115313824c8281686c697374656e65728000\na7070211601282438280800013676c3a737461727414801780181a50f09d9a552439b865d3e4c81c1d115313\na8070211686c697374656e657212824c8281686c697374656e6572800013676c3a737461727414801780181a50f09d9a552439b865d3e4c81c1d1153131822824382808000\na80702116876616c696461746512824c82816876616c6964617465800013676c3a737461727414801780181a50f09d9a552439b865d3e4c81c1d1153131822824382808000\na8070211686c697374656e657212824c8281686c697374656e6572800013676c3a7265706c791480178183646578697400a501503fafcc12ed987e27f9b7b5d1f8f4478d0250f09d9a552439b865d3e4c81c1d1153130350f09d9a552439b865d3e4c81c1d1153130401058202581c82138269436f6d706c65746564820f818266737461747573820218ca181a50f09d9a552439b865d3e4c81c1d115313182650f09d9a552439b865d3e4c81c1d115313\na70702116876616c696461746512824c82816876616c696461746580001364703a696e14818378186c697374656e65722e6f75743e76616c69646174652e696e824c8281686c697374656e6572800001178183636f757400a5015017381d0576454a378d6103ff771e6d060250f09d9a552439b865d3e4c81c1d1153130350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b181981835017381d0576454a378d6103ff771e6d06781b76616c69646174652e6f75743e64656475706c69636174652e696e82582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b00\na80702116b64656475706c69636174651282582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b0013676c3a737461727414801780181a5017381d0576454a378d6103ff771e6d061822824382808000\na80702116b64656475706c69636174651282582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b001364703a696e148183781b76616c69646174652e6f75743e64656475706c69636174652e696e824c82816876616c6964617465800001168182647365656e8201f5178183636f757400a5015037374515af1bad8312f98b4daa42b538025017381d0576454a378d6103ff771e6d060350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b181981835037374515af1bad8312f98b4daa42b538782264656475706c69636174652e6f75743e64656c697665722e726571756573742e696e82582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b00\na80702116764656c697665721282581d82816764656c697665728183816764656c697665720182078206626f6b0013676c3a737461727414801780181a5037374515af1bad8312f98b4daa42b5381822824382808000\na80702116f64656c697665722e726571756573741282582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b0013676c3a737461727414801780181a5037374515af1bad8312f98b4daa42b538182282581d82816764656c697665728183816764656c697665720182078206626f6b00\na80702116f64656c697665722e726571756573741282582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b001364703a696e148183782264656475706c69636174652e6f75743e64656c697665722e726571756573742e696e82582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b0001178183636f757400a601508123dbaa681417af92bf1d659477f59e025037374515af1bad8312f98b4daa42b5380350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b06818363617070686576656e745f69648206626f6b181881820150f68b7eb0b2ef76045c336f9390debc9218198183508123dbaa681417af92bf1d659477f59e782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e82582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b00\na80702116f64656c697665722e706172746e65721282582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b0013676c3a737461727414801780181a508123dbaa681417af92bf1d659477f59e182282581d82816764656c697665728183816764656c697665720182078206626f6b00\na80702116f64656c697665722e706172746e65721282582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b0013676c3a726574727914801780181a508123dbaa681417af92bf1d659477f59e182ba10282870150c8fa3674c4ed0eab3192771f1392030850f68b7eb0b2ef76045c336f9390debc9262696e58204583fb2221dac2d4c535ef23eb79b2682fb02d8aafe91e8ace4e365738c854aa717374642f687474702d636c69656e74403184508123dbaa681417af92bf1d659477f59e58208c3c3e457b61b7ba324420aa9ea838dd5667bdbdb36420401e19becaab3ba2f281826f6964656d706f74656e63795f6b65798206626f6bf6850250c8fa3674c4ed0eab3192771f1392030801a601508123dbaa681417af92bf1d659477f59e025037374515af1bad8312f98b4daa42b5380350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b06818363617070686576656e745f69648206626f6b50f68b7eb0b2ef76045c336f9390debc92\na70703181b508123dbaa681417af92bf1d659477f59e181c6f64656c697665722e706172746e6572181e58208c3c3e457b61b7ba324420aa9ea838dd5667bdbdb36420401e19becaab3ba2f2181f011821782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e182ba1018250c8fa3674c4ed0eab3192771f1392030801\na80703181b508123dbaa681417af92bf1d659477f59e181c6f64656c697665722e706172746e6572181e58208c3c3e457b61b7ba324420aa9ea838dd5667bdbdb36420401e19becaab3ba2f2181f02182082018282636f7574820257820f81826663686172676582088247470de4df820000128264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c91821782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e182ba1018250c8fa3674c4ed0eab3192771f1392030801\na80702116f64656c697665722e706172746e65721282582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b001364703a696e148183782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e82582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b0001178283636f757400a60150827242f9de6b67f5bfcf5d6f6462d6f702508123dbaa681417af92bf1d659477f59e0350f09d9a552439b865d3e4c81c1d115313040105820257820f81826663686172676582088247470de4df8200001206818363617070686576656e745f69648206626f6b83646578697400a6015018b1f25dbecdd81fc5ac7139611721e502508123dbaa681417af92bf1d659477f59e0350f09d9a552439b865d3e4c81c1d1153130401058202581c82138269436f6d706c65746564820f818266737461747573820218c906818363617070686576656e745f69648206626f6b181981835018b1f25dbecdd81fc5ac7139611721e5782664656c697665722e706172746e65722e657869743e64656c697665722e6465636964652e696e82582482826764656c69766572666465636964658183816764656c697665720182078206626f6b00182ba2018250c8fa3674c4ed0eab3192771f13920308010282850650c8fa3674c4ed0eab3192771f1392030801501ec22e92983fdfaa9c62b22b6d57acba8250827242f9de6b67f5bfcf5d6f6462d6f75018b1f25dbecdd81fc5ac7139611721e5840750c8fa3674c4ed0eab3192771f139203080101\na80702116e64656c697665722e6465636964651282582482826764656c69766572666465636964658183816764656c697665720182078206626f6b0013676c3a737461727414801780181a5018b1f25dbecdd81fc5ac7139611721e5182282581d82816764656c697665728183816764656c697665720182078206626f6b00\na60702116e64656c697665722e6465636964651282582482826764656c69766572666465636964658183816764656c697665720182078206626f6b001364703a696e148183782664656c697665722e706172746e65722e657869743e64656c697665722e6465636964652e696e82582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b000117818364646f6e6500a60150d041f8468dc1be645ee0473d4b2d292d025018b1f25dbecdd81fc5ac7139611721e50350f09d9a552439b865d3e4c81c1d1153130401058202581e820f8282686576656e745f69648206626f6b8266737461747573820218c906818363617070686576656e745f69648206626f6b\nseal 15ab14a07ba6e7bd0b44195b6da8f7c9aae3b23d44b36e9f508e3936aae7db48\n```\n\n</details>\n\n## Carry forward\n\nRead [Connectors and outcomes](/guide/03-connectors-and-outcomes.md) for the\nadmission boundary and [Running for real](/guide/05-running-for-real.md)\nfor deployment settings, secrets and diagnostic evidence.\n\nThis is the central exercise: one integration, several possible worlds, and\na recorded explanation when a revision changes behavior. Keep the timeout,\nduplicate and 500 scenarios alongside the nominal one. Each describes a case\nthe next change must still handle; passing them is evidence under their stated\nworld assumptions, not proof that every real partner will behave that way.\n\nPrevious: [Two tenants](/examples/03-two-tenants.md). Next:\n[Sensor alarm](/examples/05-sensor-alarm.md). The same approach can test an event that\nnever arrives, without making the test wait in real time.\n\n## Limits\n\nMalformed JSON, failed authentication and an excessive wire body are refused\nbefore a root or ACK exists. A decoded Lab injection cannot exercise that\ndecoder. The separate physical loopback proof is:\n\n```sh\ncargo test -p rastok --lib --features hosted-http12 auth_codec_and_body_refusals_never_invent_an_inbound_call\n```\n\nThe filtered test result was:\n\n```text\ntest connector::drivers::network::http_server::tests::auth_codec_and_body_refusals_never_invent_an_inbound_call ... ok\n```\n\nAn instance key isolates state; `seen` does the deduplication. This is\naccept-once within an **idle** retention window: duplicates extend that\nwindow, and a permanently failed job is still considered seen until expiry.\nIt is not exactly-once delivery, a durable outbox, or automatic resubmission\nafter a fault. A restart loses that state. The partner must honor the stable\nidempotency key, upsert by `event_id`; the request and key remain identical\nbetween attempts. Both retry paths rely on that external property. The example\ndoes not test a real partner's idempotence.\n\nThe supplied privacy profile describes a local synthetic demonstration, not\nlegal authority for production processing. Real purposes, recipients,\ntransfers and retention require deployment-specific review. No persistent\npersonal-data journal or `run --record` is admitted by this example. A message broker\nand SQL are not shown. Modify the scenario on disk to try another world;\nthere is no debugger branch or payload editor.\n"},{"path":"/guide/04-the-lab","title":"The Lab: scenarios, mocks and time","description":"Describe inputs, boundary outcomes and elapsed time as executable scenarios while keeping the application graph unchanged.","text":"---\ntitle: \"The Lab: scenarios, mocks and time\"\ndescription: Describe inputs, boundary outcomes and elapsed time as executable\n  scenarios while keeping the application graph unchanged.\nurl: https://docs.rastok.com/guide/04-the-lab\nsource_revision: v0.2.0-alpha\n---\n\n# The Lab: scenarios, mocks and time\n\nAfter this chapter you can read a Lab, override a mock, assert absence,\nadvance virtual time, and distinguish simulation evidence from physical tests.\n\n## Keep the program, supply its world\n\nThe real world (App) uses physical Drivers; the virtual world (Lab) supplies\nscripted outcomes and time to the same graph. `lab smoke` contains shared\nmocks and scenarios directly. Its name need not match the App name. The Lab\nis not deployed and does not enter the program's semantic hash.\n\nHere is the entire Lab from `examples/echo.rkg`, lines 24–52:\n\n```rkg\nlab smoke {\n  mock shell {\n    on in {\n      out = .\n      exit = Exited { exit_code = 0, signal = null }\n    }\n  }\n\n  scenario roundtrip {\n    app.in = \"hello\"\n    expect app.out == \"hello\"\n    expect shell.err == nothing\n  }\n\n  scenario filtered {\n    app.in = \"\"\n    expect shell.in == nothing\n    expect app.out == nothing\n  }\n\n  scenario silence_expires {\n    mock shell {\n      on in { out = nothing }\n    }\n    app.in = \"hello\"\n    advance duration(\"5s\")\n    expect shell.exit == TimeoutExpired {}\n  }\n}\n```\n\nThe mock supplies the Process response, not the Operator's decision. The\nreal `relay` handler still filters the input. In `roundtrip`, the script\nreturns the request data and one successful terminal. That response passes\nthrough the normal Contract and journal machinery, which creates its records.\n\n## Group another mock world when needed\n\nAn optional `simulation alternate { ... }` inside the Lab groups scenarios\nthat share another set of mocks. It defaults to the unit's App; `: App`\nspells that target explicitly. A Lab mock applies to every group unless\nthe group replaces it, and a scenario can replace either inherited mock.\nThe replacement is the whole mock, never a merge of its branches.\n\n## Silence must be explicit\n\nThe `silence_expires` scenario replaces the whole shared mock for `shell`.\nIts `out = nothing` is deliberate silence, not an omitted response that\nthe simulator guesses. The Call remains open until the explicit time\nadvance reaches its five-second deadline. The runtime then produces the\ntyped `TimeoutExpired` terminal. No child process was started.\n\nFor an outbound Call, an uncovered request fails the scenario rather than\nsilently timing out. A missing mock and an authored silent mock are\ndifferent tests. Within a mock, the first matching clause in source order\nsupplies the response.\n\n## Read expectations in their action window\n\nAn input injection or an `advance` starts an observation window. Subsequent\nexpectations read that window without consuming it. They do not scan all\nearlier actions in the scenario. Ready work settles before those assertions\nare evaluated, so an expectation does not race a half-finished transition.\n\n`expect app.out == \"hello\"` checks exactly one matching value.\n`expect 3 app.out` checks three deliveries; omitting the number means one.\n`expect shell.in == nothing` asserts absence. The empty-input scenario therefore\nproves more than an empty App output: it proves that the Process was never\ncalled. Assertions observe ports, not an Operator's private state directly.\n\nAn emission can be observed at its source even when the graph routes it to\n`nothing`. That is why the timeout can be asserted on `shell.exit` although\nEcho discards that output. `app.out`, in contrast, observes an actual crossing\nof the App boundary, not every child output.\n\n## Advance to a deadline, not through a sleep\n\nThe sensor example has a five-minute join window between a probe and a\nheartbeat. Its `virtual_day` scenario in `examples/sensor-alarm.rkg`, lines 73–78,\nsupplies no heartbeat:\n\n```rkg\nscenario virtual_day {\n  app.probe = { sensor = \"pump-a\" }\n  advance duration(\"24h\")\n  expect app.silent where data is JoinExpired\n  expect app.alarm == nothing\n}\n```\n\nThe advance visits the five-minute expiry before reaching its twenty-four-hour target.\n\n```mermaid\nflowchart LR\n    probe[\"t = 0: app.probe\"] --> advance[\"advance: target 24 hours\"]\n    advance --> expiry[\"t = 5 minutes: JoinExpired\"]\n    expiry --> expect[\"t = 24 hours: expect app.silent\"]\n```\n\nReady computations take no virtual time. The simulator processes due\nobligations in order, settling Call and resident Process Session mock\nreplies and their consequences before the next deadline, without another\n`advance` or real sleep.\n\n## Inspect source\n\nFollow [the debugger tour](/debugger.md): source left, inspector and Graph right.\n**Next transition** (`F10` or `n`) follows recorded transitions. Hover or focus\nruntime identifiers for redacted, read-only summaries and inspector links;\nEscape closes them. **Fit graph** shows everything; **Readable size** restores\ninterface-sized text. Choose scenarios; click progress to select their source.\n\n## Know the evidence boundary\n\nRun `rastok simulate examples/echo.rkg` to check its three scenarios.\nAdd `--compare examples/traces/echo` to compare their\ncausal traces as well. Expectations express selected requirements; the\ngolden comparison can reveal other changed facts. `--save` writes new\nreferences and is a separate, reviewed action.\n\nA scripted outcome proves how the checked graph responds to that outcome.\nIt does not prove a real partner obeys the Contract. In particular, a\ndecoded HttpServer Lab injection cannot test malformed wire JSON or\nauthentication before admission. Automatic incident-to-scenario conversion\nand authored crash/restart actions are not executable Lab features today;\nsee [the current limits](/index.md#what-is-available-today).\n\nSee [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md), [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) section 8,\nand `WHITEPAPER.md` sections 5 and 6 for the normative rules and context.\n\n## Summary\n\n- A mock substitutes the external response, not the graph's computation.\n- Silence and absence are authored, observable test cases.\n- Expectations read the latest action window.\n- Virtual time resolves real graph obligations without waiting in real time.\n\n## Next\n\nRead [Running for real](/guide/05-running-for-real.md). Experiment with\n[Echo](/examples/01-echo.md) and\n[Sensor alarm](/examples/05-sensor-alarm.md) to compare ordinary replies,\nsilence and time-dependent outcomes.\n"},{"path":"/migration","title":"Migrating from 0.1 to 0.2","description":"Port a 0.1 graph, handle missing values and check its scenarios against your existing reference traces.","text":"---\ntitle: Migrating from 0.1 to 0.2\ndescription: Port a 0.1 graph, handle missing values and check its scenarios\n  against your existing reference traces.\nurl: https://docs.rastok.com/migration\nsource_revision: v0.2.0-alpha\n---\n\n# Migrating from 0.1 to 0.2\n\nStart with the `.rkg` source and keep your 0.1 binary, recordings and reference\ntraces. Change the spellings first. Then run `rastok check`: some diagnostics\nask you to make a decision, such as when a keyed instance should stop or what\nto do when a list is empty. The [authoring rules](/reference/authoring-rules.md)\npair these refusals with working 0.2 code.\n\n## Rename the spellings, not the data\n\n| In 0.1 | In 0.2 | What to keep in mind |\n|---|---|---|\n| Type `text` | `string` | Change declarations, type tests and casts. Do not edit the text inside string literals. You can declare `type text = string` in your own unit; it covers type positions only. |\n| Verbatim block `text! { received }` | `string! { received }` | Change only the reader name. The spaces inside the braces are part of the value. |\n| `codec = text` | `codec = string` | Applies to HttpClient, HttpServer, WebSocketClient and WebSocketServer. The wire encoding stays the same. The codec word is part of the plan's identity. |\n| Process overflow reason `budget` or `capacity` | `Budget` or `Capacity` | These are enum symbols. Update matches, mocks and JSON consumers: JSON carries the exact spelling. |\n| `@sensitive(level = confidential)` | `@sensitive(level = Confidential)` | Use `Internal`, `Confidential` or `Restricted`. The protection level keeps its identity. Configuration words such as `codec = json` and `kind = age` stay lowercase. |\n\nThe old type without an alias, and the old reader with or without one,\nproduce `E-RESOLVE-UNKNOWN`. The old network codec produces `E-CONTRACT-ATTR`.\n\n## Choose when an instance closes\n\nGive every `var` an initial value. Write `var last: string = \"\"` for an\nempty string, or `var last: string? = null` if it starts absent. If you omit\nthe initializer, `check` points to the declaration and suggests a fix.\n\n| In 0.1, inside `lifetime` | In 0.2 | When the instance closes |\n|---|---|---|\n| `kind = fixed; after = D` | `kind = age; max = D` | After the elapsed time measured from creation. |\n| `kind = tumbling; every = D` | `kind = slot; max = D` | At the end of its processing-time slot. |\n| `kind = single_pass` | `kind = once` | After one admission. |\n| `kind = idle; after = D` | `kind = idle; max = D` | After no admissions for the specified duration. |\n\nHere `D` stands for a positive duration such as `duration(\"5m\")`. The old\nkinds and fields produce `E-INSTANCE`. Do not rename `every` on a Timer\nor change a Retry delay.\n\nA Graph, Operator or Connector that declares an instance key must also\ndeclare a lifetime (`E-LIFETIME-REQUIRED`). Add\n`lifetime = { kind = persistent }` to keep the old behavior and hash.\nThat also keeps every key alive until explicitly stopped. If a keyed\nOperator can finish its first reaction without retaining state or stopping,\n`check` warns with `W-EMPTY-INSTANCE`: that empty instance has no deadline.\nFor a session\nthat should expire after two hours of silence, use\n`lifetime = { kind = idle; max = duration(\"2h\") }` instead. Without a key,\nomitting the lifetime still gives a persistent singleton. See\n[Instances, state and time](/guide/06-instances-state-and-time.md) for closure\nbudgets: every finite owner containing an outbound Connector has to declare\nboth budgets, including the App. This is not specific to Process.\n\n## Handle a value that may be missing\n\n| In 0.1 | In 0.2 |\n|---|---|\n| `xs[i]` with no proof the index exists | Use `xs[?i]`; an out-of-range index gives null. |\n| `m[k]` or `m.name` with no proof the key exists | Use `m[?k]` or `m.?name`. Mark each step that can be absent. |\n| `x as T` when the conversion can fail | Test `x is T` before using it, or use `x as? T` and handle null. |\n| `timestamp(s)`, `duration(s)` or `decimal(s)` on runtime text | The same call yields an optional value. For example, sending `timestamp(s)` straight to a `timestamp` port gives `E-PORT-TYPE`. Test the value, match it or supply a meaningful default with `.orValue(default)`. |\n| A malformed constant such as `timestamp(\"not a date\")` | Correct the literal: `check` rejects it with `E-EXPR`, including inside a reaction. |\n| `meta.app.id` when some incoming routes write `id` and others do not | Write it on every route, or use `meta.app.?id` and handle absence. The required read reports `E-META-ZONE` and names the route's origin. If the graph never writes `id`, even the optional read is refused. |\n\nPlain lookups and casts still work when the type, a constant or a type\ntest in scope proves they succeed. Otherwise they report `E-EXPR`. A\ntest such as `size(xs) > 0` is not an index proof. If the result type is\n`variant`, it already includes null: for a string fallback on a variant map,\nwrite `(m[?k] as? string).orValue(\"unknown\")`.\n\nHere an empty list really does mean “unassigned”. Save this as `labels.rkg`\nand run `rastok simulate labels.rkg` to check both paths:\n\n```rkg\ngraph labels : App {\n  input in: array<string>\n  output out: string\n  operator first {\n    input in: array<string>\n    output out: string\n    on in { out = data[?0].orValue(\"unassigned\") }\n  }\n  in -> first -> out\n}\nlab labels {\n  scenario has_label {\n    app.in = [\"blue\"]\n    expect app.out == \"blue\"\n  }\n  scenario no_label {\n    app.in = []\n    expect app.out == \"unassigned\"\n  }\n}\n```\n\nThe Lab prints:\n\n```text\nPASS labels.has_label\nPASS labels.no_label\n2 scenario(s), 0 failed\n```\n\nIf absence should reject a request instead, keep the optional value and\nroute that case explicitly. The ternary, scenario, mock and expectation\nsyntax has not changed. See [Expressions and dispatch](/reference/expressions.md).\n\n## Check numeric and boundary types\n\n| In 0.1 | In 0.2 |\n|---|---|\n| `uint` for an unsigned 64-bit field | Use `ulong` to preserve its range. Keep `uint` only if 32 bits are intended. The suffix `u` chooses the first width that fits: `7u` is a `uint`, `4294967296u` a `ulong`. |\n| `number` for an exact value | Use `decimal` for an exact value with free scale, or keep `decimal(p,s)` for a declared scale. For a binary floating result from a `variant`, use `as? double` and handle null. |\n| `bytes` or `bytes(n)` as a type | Use `array<byte>` or `array<byte, n>`. The compact encoding and the `bytes` codec stay the same. JSON does not implicitly convert bytes to base64. |\n| `media_type` or `media_type(s)` | Use `string` and the string value itself. The reserved `meta.ext.content_type` is a `string(255)`: the entire value, including parameters, must still be a valid MIME Content-Type. Other strings have no MIME requirement. |\n| HttpClient `DecodeFailed {}` in a mock or exact expectation | `DecodeFailed { message = \"…\" }` |\n\nA numeric literal can take the expected type if it fits. A calculated value\nwidens implicitly only if its whole type fits. For example, an `int` and a\n`uint` can meet at `long`. A `long` does not always fit a `double`: use\n`as? double` when the conversion depends on the value. Schemaless JSON reads\na number as `long`, `ulong` or `double`, in that order, and rejects it if\nnone preserves its value. Declare an exact decimal at the boundary when\nthat is what the protocol requires. See [Types and schemas](/reference/types.md).\n\n**HttpClient.** For `http://`, the default works with an HTTP/1.1 server.\nSelect only `\"http/2\"` when the server expects cleartext HTTP/2.\nFor a response with status 204 or 205, handle `Completed` on `exit`.\nDo not wait for a body on `out` or supply one in the corresponding mock.\nFor a typed JSON response, declare a `timestamp` field to\nread an RFC 3339 UTC string ending in `Z`. If a declared field cannot be\nread, the Call ends with `DecodeFailed` and delivers nothing on `out`.\nThe message names the declared field and the expected type. If the body is\nnot JSON, it names `out` instead. For a request that cannot be encoded, it\nnames `in` and the expected representation; no request is sent. Neither\nmessage includes a rejected value or a key supplied by the peer.\n\nKeep a case test such as `data is DecodeFailed`. In that branch you can\nread `data.message`. Supply a message when constructing the case: in a\nmock, `exit = DecodeFailed {}` now gives this diagnostic:\n\n```text\nerror[E-PORT-TYPE]: `DecodeFailed` requires field `message: string`\n```\n\nThe [HttpClient contract](/reference/connectors/http-client.md) stays at\n`@1`. This change does not affect WebSocket cases or make timestamps\nwritable as JSON.\n\n## Recompile and compare\n\nA schemaless JSON codec delivers an object as a map, including when a mock\nwrites a record. If all sources of an input deliver schemaless JSON,\nreplace `data is Receipt` with `val receipt = data as? Receipt` and handle\nnull. The mock still receives the graph's typed request.\n\nThe format 2 plan reader rejects a format 1 `.rkp`: recompile the\nported `.rkg` source. Diagnostic recordings (`.rkr`) keep format 1, but\nreplay also checks the plan embedded in the recording. Keep the 0.1 binary\nto replay recordings with a format 1 plan.\n\nRun `rastok check` and then `rastok simulate` before using real Drivers.\nCompare against the existing `.rkc` references first. For example, from\nthe repository root:\n\n```sh\nrastok check examples/echo.rkg\nrastok simulate examples/echo.rkg --compare examples/traces/echo\n```\n\nA different plan hash is not by itself a different delivery. Review the\nfirst differing record, including whether only a recorded Retry plan hash\nchanged. If you intend to change the reference, use `--save` in a separate\ndirectory and review the differences before replacing the old files.\n"},{"path":"/reference/connectors/http-server","title":"HttpServer","description":"Ports, terminal outcomes, settings and qualification evidence for the HttpServer connector.","text":"---\ntitle: HttpServer\ndescription: Ports, terminal outcomes, settings and qualification evidence for\n  the HttpServer connector.\nurl: https://docs.rastok.com/reference/connectors/http-server\nsource_revision: v0.2.0-alpha\n---\n\n# HttpServer\n\n`std/http-server@1`. An inbound HTTP Call. `ack` sends 202 after admission; `respond` waits for the graph response. A malformed body or failed authentication can refuse before admission, without inventing a request envelope or an exit.\n\n## Declaration\n\nThis declaration comes from `crates/rastok/src/lab.rs`. Place the Connector in a Graph\nand wire its ports; the excerpt alone is not an App.\n\n```rkg\nconnector network : HttpServer {\n  listen = \"127.0.0.1:8080\"\n  codec = json\n}\n```\n\nThe [contract index](/reference/contracts.md) explains shared settings, build features\nand the distinction between a Contract, a Lab model and an installed Driver.\n\nSelector: `mode` defaults to `ack`.\n\nSee [inbound admission and backpressure](/reference/execution.md#instances-own-state-not-threads): pending requests are retained within bounds, and the outbound Call queue rule does not apply to this Contract.\n\n| Mode | Driver direction | Exchange | Lab model | Installed in this binary |\n|---|---|---|---|---|\n| `ack` | inbound | call | `lab-http-server` | Not compiled |\n| `respond` | inbound | call | `lab-http-server` | Not compiled |\n\n## Ports and completion\n\n| Mode | Port | Direction | Type rule |\n|---|---|---|---|\n| ack, respond | `in` | input | `codec = bytes` → `array<byte>`; `codec = json` → `variant`; `codec = string` → `string` |\n| ack, respond | `out` | output | Same as `in` |\n| ack, respond | `exit` | output | HttpServerExit, below |\n\n| Mode | Output cardinality |\n|---|---|\n| ack | One admitted request `out`; exactly one request `exit`; no graph response |\n| respond | One admitted request `out`; exactly one request `exit`; at most one response `in` |\n\n## Exit union\n\n| Case | Payload | Call visibility |\n|---|---|---|\n| `Completed` | `{ status: int }` | Not an outbound Call |\n| `OutcomeUnknown` | Empty | Not an outbound Call |\n| `Overloaded` | Empty | Not an outbound Call |\n| `PeerDisconnected` | Empty | Not an outbound Call |\n| `RequestExpired` | Empty | Not an outbound Call |\n\n## Settings\n\nIn `mode = respond` with `codec = json`, `rastok check` refuses a graph\nresponse whose resolved type contains a\n[value without a JSON form](/reference/types.md#json-request-values), using\n`E-TYPE-INVALID`. A `variant` response is checked at execution instead; if\nits value cannot be encoded, the Driver sends HTTP 500 and reports\n`OutcomeUnknown`, without sending that value.\n\n| Mode | Setting | Domain | Presence / default | Latest phase |\n|---|---|---|---|---|\n| ack, respond | `auth_bearer` | `string` | optional | instance |\n| ack, respond | `behavior` | `deterministic` | `deterministic` | plan |\n| ack, respond | `codec` | `bytes \\| json \\| string` | required | plan |\n| ack, respond | `headers` | `HTTP headers` | optional | instance |\n| ack, respond | `custom_headers` | `map<string,array<string>>` | optional | instance |\n| ack, respond | `listen` | `string` | required | instance |\n| ack, respond | `max_body` | `ByteSize` | `\"8MiB\"` | plan |\n| ack, respond | `path` | `string` | `\"/\"` | plan |\n| ack, respond | `tls_certificate` | `array<byte>` | optional | instance |\n| ack, respond | `tls_private_key` | `array<byte>` | optional | instance |\n| ack, respond | `versions` | `array<http/1.1 \\| http/2 \\| http/3>` | `[\"http/3\", \"http/2\", \"http/1.1\"]` | plan |\n| ack, respond | `zero_rtt` | `disabled` | `disabled` | plan |\n| respond | `correlate` | `expression path` | optional | invocation |\n| respond | `timeout` | `duration` | required | instance |\n\nThe Lab scripts decoded `ack` requests through `listener.out = value`, then a successful 202. It does not exercise wire decoding or authentication. A `respond` Node can bind silently beside another simulated flow; authored source injection and graph-response scripting for that mode are deferred.\n\n## Qualification inventory\n\n`ack`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/http_server.rs`, `crates/rastok/tests/lab_http_source.rs`.\n\n`respond`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/http_server.rs`, `crates/rastok/tests/lab_http_source.rs`.\n"},{"path":"/reference/contracts","title":"Standard contracts","description":"Contract identities, modes, ports, terminal cases, settings and Lab support from the executable Connector catalogue.","text":"---\ntitle: Standard contracts\ndescription: Contract identities, modes, ports, terminal cases, settings and Lab\n  support from the executable Connector catalogue.\nurl: https://docs.rastok.com/reference/contracts\nsource_revision: v0.2.0-alpha\n---\n\n# Standard contracts\n\nThis inventory follows `rastok connectors --json` in its emitted order.\nContract availability, Lab models and installed physical Drivers are separate\nfacts. A binary built with default features (no networking) lists File and Process\nDrivers; networking requires the hosted networking features. Run the command\non the binary you deploy to inspect that assembly.\n\nThe [standard exit types](/reference/stdlib.md#types) are available\nby name without imports. The physical Driver selection does not change those\ntype definitions.\n\nA finite owner of an outbound Connector declares the drain and settlement\nbudgets in `closing`. This applies to the App as well as nested owners.\n\nA setting's latest phase is its evaluation ceiling: plan, boot, instance or\ninvocation. A setting may depend on values available by that phase, but\nnot on values that become available later. The compiler selects the earliest phase where its expression\ncloses. Omitted defaults become effective settings. Optional means absent,\nnot null. Byte sizes use `B`, `KiB`, `MiB` or `GiB`.\n\nHTTP-derived Contracts share `headers` (a sparse typed record containing\n`content_type: string(255)`) and `custom_headers`\n(`map<string,array<string>>`). Driver-owned headers cannot be overridden.\nCertificate and private-key settings must be supplied together.\nDeclared version preferences are HTTP/3, HTTP/2, HTTP/1.1; the Driver uses\nonly compiled backends. `hosted-http12`, `hosted-http3` and\n`hosted-websocket` select those capabilities. `hosted-network` enables the\nhosted networking group.\n\n`idempotent` is a repetition guarantee. `behavior` describes whether equal\nrequests in equal external state yield equal answers. They are distinct;\n[Retry](/guide/07-loops-and-retries.md) also checks terminal visibility.\nSessions have no per-message Call exit or Retry attribute.\n\n## Connectors\n\n- [File](/reference/connectors/file.md): Read or atomically replace a file.\n- [Process](/reference/connectors/process.md): Start a job or keep a resident process.\n- [HttpClient](/reference/connectors/http-client.md): Send a request and receive its response and terminal outcome.\n- [HttpServer](/reference/connectors/http-server.md): Admit a request and acknowledge it or await the graph's response.\n- [WebSocketClient](/reference/connectors/websocket-client.md): Open a peer Session and exchange messages.\n- [WebSocketServer](/reference/connectors/websocket-server.md): Accept peer Sessions and route their messages.\n\n## Specified, not shipped\n\n| Item | Specification |\n|---|---|\n| File `watch`: listed as checker deferred; attributes only, no Driver, Lab model, fixture or example | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.7 |\n| Timer: elapsed-time source | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.4 |\n| Calendar: civil schedule source | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.5 |\n| Memory: bounded append/snapshot store | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.6 |\n| HttpServer `respond` source scripting in the Lab | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §2 |\n| Streaming HttpServer responses and seeded behavior | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §8 |\n\nFixture names describe the evidence corpus, not checks performed by the\ncatalogue command. Source authority: [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md), resolved\nstandard definitions and the current binary's catalogue. For authoring,\nsee [Connectors and outcomes](/guide/03-connectors-and-outcomes.md).\n"},{"path":"/examples/05-sensor-alarm","title":"Sensor alarm: make time an input","description":"Isolate hysteresis state by sensor, detect a missed heartbeat with a bounded join, and advance through a virtual day without waiting a day.","text":"---\ntitle: \"Sensor alarm: make time an input\"\ndescription: Isolate hysteresis state by sensor, detect a missed heartbeat with\n  a bounded join, and advance through a virtual day without waiting a day.\nurl: https://docs.rastok.com/examples/05-sensor-alarm\nsource_revision: v0.2.0-alpha\n---\n\n# Sensor alarm: make time an input\n\nThis program tracks each sensor's readings, emits alarm changes and reports a missing heartbeat.\n\nThe partner example tested a response and a timeout. Now ask a harder\nquestion: how do you test silence? Keep state per sensor, distinguish a\nthreshold crossing from noise, and make the waiting period an explicit input\nto your scenario.\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root, with `rastok` installed:\n\n```sh\nrastok simulate examples/sensor-alarm.rkg --compare examples/traces/sensor-alarm\n```\n\n```text\nPASS sensors.hysteresis\nPASS sensors.silent_sensor\nPASS sensors.virtual_day\n3 scenario(s), 0 failed\n```\n\nThe four lines above are stdout. The same command writes two warnings to stderr:\n\n```text\nwarning[W-EMPTY-INSTANCE]: `hysteresis` can open an instance that retains nothing on `in`\n  --> examples/sensor-alarm.rkg:31:7\n   |\n31 |       _ => nothing\n   |       ^^^^^^^^^^^^\n  = owner: hysteresis\n  = trigger: in\n  = help: give the instance a delay, or add `stop` if that branch ends its work\n\nwarning[W-EMPTY-INSTANCE]: `watchdog` can keep an instance that retains nothing after `on (probe, heartbeat)`\n  --> examples/sensor-alarm.rkg:41:49\n   |\n41 |     on (probe, heartbeat) within duration(\"5m\") {\n   |                                                 ^\n  = owner: watchdog\n  = trigger: (probe, heartbeat)\n  = help: give the instance a delay, or add `stop` if that branch ends its work\n```\n\nA first reading can leave `hysteresis` unchanged, and `watchdog` keeps no\nstate after consuming a pair. Both Operators intentionally keep the sensor\ninstance for later messages; neither warning changes the trace.\n\n## Read the program\n\nFirst follow the readings into the keyed stateful Operator: its two thresholds\nprevent an alarm from oscillating around one limit. Then find the `watchdog`\njoin. A probe and heartbeat rendezvous within a bounded interval; a missing\npartner produces `JoinExpired`, whose route is as explicit as a normal output.\nRead `advance` in the Lab last: time comes from the scenario, not from sleeps\nhidden in the application.\n\n`var tripped: bool = false` is the memory behind that behavior: a boolean\ncell initialized to `false` for each sensor's Operator instance. At 121,\npump-a sets it to `true` and emits `tripped`; at 100, it keeps that state\nand emits nothing; at 79, it resets the cell and emits `normal`. Pump-b's\ncell is independent and starts at `false`, so its reading of 100 produces\nno alarm. Each state change commits together with its emission, not as a\nseparate shared assignment. The preceding webhook example uses `var seen`\nfor the same kind of private memory. See\n[Values and mutable state](/guide/06-instances-state-and-time.md#values-and-mutable-state)\nfor the difference between `var`, `val` and an instance key.\n\nThere is no Connector in this program. The [Lab reference](/reference/lab.md)\nexplains expectations and observation windows; `advance` supplies virtual time.\n\n<a id=\"graph\"></a>\n\nSource: `examples/sensor-alarm.rkg`\n\n```rkg\n// Hysteresis per sensor and a bounded probe/heartbeat rendezvous.\n// The Lab supplies clock advances, not a real periodic sensor Driver.\ntype Reading = struct { sensor: string, value: int }\ntype Sensor = struct { sensor: string }\ntype Alarm = struct { sensor: string, state: string }\ntype MissedHeartbeat = union { JoinExpired {} }\n\ngraph sensor_alarm : App {\n  input reading: Reading\n  input probe: Sensor\n  input heartbeat: Sensor\n  output alarm: Alarm\n  output alive: string\n  output silent: MissedHeartbeat\n\n  operator hysteresis {\n    input in: Reading\n    output out: Alarm\n    instance = { key = data.sensor }\n    lifetime = { kind = persistent }\n    var tripped: bool = false\n    on in match {\n      !tripped && data.value > 120 => {\n        tripped = true\n        out = { sensor = data.sensor; state = \"tripped\" }\n      }\n      tripped && data.value < 80 => {\n        tripped = false\n        out = { sensor = data.sensor; state = \"normal\" }\n      }\n      _ => nothing\n    }\n  }\n  operator watchdog {\n    input probe: Sensor\n    input heartbeat: Sensor\n    output out: string\n    output expired: MissedHeartbeat\n    instance = { key = data.sensor }\n    lifetime = { kind = persistent }\n    on (probe, heartbeat) within duration(\"5m\") {\n      out = probe.data.sensor\n    }\n  }\n\n  reading -> hysteresis -> alarm\n  probe -> watchdog.probe\n  heartbeat -> watchdog.heartbeat\n  watchdog.out -> alive\n  watchdog.expired -> silent\n}\n\nlab sensors {\n  scenario hysteresis {\n    app.reading = { sensor = \"pump-a\"; value = 121 }\n    expect app.alarm where data.sensor == \"pump-a\" && data.state == \"tripped\"\n    app.reading = { sensor = \"pump-a\"; value = 100 }\n    expect app.alarm == nothing\n    app.reading = { sensor = \"pump-b\"; value = 100 }\n    expect app.alarm == nothing\n    app.reading = { sensor = \"pump-a\"; value = 79 }\n    expect app.alarm where data.state == \"normal\"\n  }\n  scenario silent_sensor {\n    app.probe = { sensor = \"pump-a\" }\n    app.probe = { sensor = \"pump-b\" }\n    app.heartbeat = { sensor = \"pump-b\" }\n    expect app.alive == \"pump-b\"\n    advance duration(\"5m\")\n    expect app.silent where data is JoinExpired\n    expect app.alive == nothing\n  }\n  scenario virtual_day {\n    app.probe = { sensor = \"pump-a\" }\n    advance duration(\"24h\")\n    expect app.silent where data is JoinExpired\n    expect app.alarm == nothing\n  }\n}\n```\n\n## Expected result\n\nThe golden's `sensors.virtual_day` follows one unanswered probe, not the\nseparate hysteresis scenario; the advance visits its five-minute deadline.\n\n```mermaid\nsequenceDiagram\n    participant lab as Lab: sensors.virtual_day\n    participant app as sensor_alarm\n    participant watchdog as watchdog\n    lab->>app: probe = pump-a\n    app->>watchdog: probe = pump-a\n    Note over watchdog: Wait for heartbeat within 5m\n    lab->>lab: advance 24h\n    Note over watchdog: At 5m: no matching heartbeat\n    watchdog-->>app: expired to silent = JoinExpired\n    Note over lab,app: Advance completes at 24h, no alarm emitted\n```\n\nPump-a trips above 120, stays tripped at 100, and clears below 80. Pump-b has\nindependent state. A keyed join pairs a probe with a heartbeat within five\nminutes; only the unanswered probe expires in the silent-sensor scenario.\nThe final scenario advances twenty-four virtual hours in one authored action.\n\nWith Ruby and the built `target/debug/rastok` available, this command measures\nprocess wall time on your machine; it does not change the scenario's logical time:\n\n```sh\nruby -e '3.times { t = Process.clock_gettime(Process::CLOCK_MONOTONIC); ok = system(*ARGV); puts format(\"elapsed_cli_seconds=%.6f\", Process.clock_gettime(Process::CLOCK_MONOTONIC) - t); exit 1 unless ok }' target/debug/rastok simulate examples/sensor-alarm.rkg\n```\n\n## Break it\n\nRaise the trip threshold from 120 to 130. The sample at 121 no longer trips,\nand the original assertion and golden fail. Alternatively, remove the route\nfrom `watchdog.expired`: the checker refuses `E-UNWIRED-OUTPUT` before execution.\n\n```sh\nrastok simulate examples/sensor-alarm.rkg --compare examples/traces/sensor-alarm\n```\n\n```text\nFAIL sensors.hysteresis\n     expect app.alarm where data.sensor == \"pump-a\" && data.state == \"tripped\"  (sensor-alarm.rkg:56)\n     nothing observed\n     where data.sensor == \"pump-a\" && data.state == \"tripped\" is false for 0 of 0 deliveries; count 0, expected 1\n     expect app.alarm where data.state == \"normal\"  (sensor-alarm.rkg:62)\n     nothing observed\n     where data.state == \"normal\" is false for 0 of 0 deliveries; count 0, expected 1\n     golden divergence: record 3: emissions(23).len; expected 1; got 0; cause: TRANSACTION \"hysteresis\" · trigger \"p:in\" · cause_id absent\nPASS sensors.silent_sensor\nPASS sensors.virtual_day\n3 scenario(s), 1 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/sensor-alarm.rkg\n```\n\n## Read the golden difference\n\nThe threshold edit changes a recorded Operator transaction, including its\nstate delta and emitted alarm. The diff gives the first changed record,\nexpected/actual values and causal trigger. The missing expiry route is a\nstatic error, not a runtime golden difference.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/sensor-alarm/sensors.virtual_day.rkc`\n\n```rastok-trace\na7070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820254820f81826673656e736f7282066670756d702d6109636c61620a000b000c6570726f62650d8182752e70726f62653e7761746368646f672e70726f62658258238281687761746368646f67818381687761746368646f6701820782066670756d702d6100\na7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na8070211687761746368646f67128258238281687761746368646f67818381687761746368646f6701820782066670756d702d610013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000\na7070211687761746368646f67128258238281687761746368646f67818381687761746368646f6701820782066670756d702d610013676c3a6576696374148183752e70726f62653e7761746368646f672e70726f626582438280800001178183676578706972656400a50150354e01026e2d3e4214fc54f4c1b6c8900250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202528213826b4a6f696e45787069726564820f80181a50f3df1105112054d397a04ed0666ca4c8\nseal 9de2f8f4a2c1ad627873679b88408b9d90f101d99ba146d4e2362cd30ae4af75\n```\n\n</details>\n\n## Carry forward\n\n[The Lab](/guide/04-the-lab.md) explains this example's virtual clock and\nthe observation window used by its expectations.\n\nTime, like an external response, is something you can supply deliberately.\nYou can retain a missed heartbeat as a small regression scenario instead of\nwaiting for the fault to recur on equipment. Types, state ownership and the\nsame causal comparison still apply; the device domain needs no special Lab.\n\nThe core evaluating this graph has no clock, network access or randomness;\ntime and external outcomes enter as explicit inputs. CI compiles `rastok-core`\nfor targets without an operating system: `thumbv8m.main-none-eabihf`,\n`thumbv7m-none-eabi` and `riscv32imac-unknown-none-elf`. It also runs the\nRP2350 spike under QEMU's Cortex-M33 emulation. Running this sensor example\non a physical board is not part of the alpha.\n\nPrevious: [Webhook to partner](/examples/04-webhook-to-partner.md).\nNext: [Agent gateway](/examples/06-agent-gateway.md): keep a separate resident process\nfor each conversation and interleave several turns. Before moving on, try\nwriting a second silent-sensor scenario and explaining its first expiry from\nthe journal.\n\n## Limits\n\nThis is a requested probe/heartbeat rendezvous, not automatic periodic polling.\nNo sensor protocol, process or paid model runs. An unmatched value on either\njoin input can produce `JoinExpired`; the scenarios explicitly control which\nside is silent. Expiry DATA has no sensor field: its keyed instance and causal\nhistory supply that context. The benchmark tasks informed the example, but\nno claim is made that a published model wave authored it.\n"},{"path":"/guide/05-running-for-real","title":"Running for real","description":"Move from scripted outcomes to physical Drivers while keeping deployment settings, secrets, evidence and alpha limits explicit.","text":"---\ntitle: Running for real\ndescription: Move from scripted outcomes to physical Drivers while keeping\n  deployment settings, secrets, evidence and alpha limits explicit.\nurl: https://docs.rastok.com/guide/05-running-for-real\nsource_revision: v0.2.0-alpha\n---\n\n# Running for real\n\nAfter this chapter you can choose between simulation, a real run and\ndiagnostic replay. You can identify the deployment information that a\ngraph needs, keep credentials out of source, and distinguish a reviewed\ngolden from a recording of one real execution.\n\n## Change the world, not the graph\n\n`rastok run` compiles the App and uses physical Drivers. Its inputs and\nexternal responses are no longer supplied by Lab scenarios. Before trying\na network integration, inspect `rastok connectors` in the binary you will\nuse: checker support and an installed physical implementation are separate\nrequirements. Getting Started installs the documented hosted features.\n\nEcho is a small local first run. From the repository root, with a new\nrecording filename:\n\n```sh\nprintf 'hello\\n' | rastok run examples/echo.rkg --record echo.rkr\nrastok replay echo.rkr\n```\n\nThe first command starts the real `cat` process and prints its echoed\nline. Replay prints the recorded App output and the same causal seal\nwithout starting `cat` again. The original source file is not needed by\nthe recording reader. An existing recording path is refused rather than\noverwritten.\n\n## Supply deployment facts explicitly\n\nThe webhook example needs more than a command name. Its partner Connector,\nfrom `examples/webhook-to-partner.rkg`, lines 80–96, separates a URL\nbinding and a secret reference from the application logic:\n\n```rkg\nconnector partner : HttpClient + Retry {\n  url = env(\"PARTNER_URL\")\n  auth_bearer = secret(\"showcase/partner/token\")\n  method = \"POST\"\n  codec = json\n  output out: Receipt\n  timeout = duration(\"1s\")\n  max_body = \"16 KiB\"\n  idempotency_key = meta.app.event_id\n  // Required partner contract: honour this key for the identical request.\n  // This declaration does not prove that a real service honours that contract.\n  idempotent = true\n  behavior = deterministic\n  Retry.attempts = 2\n  Retry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed]\n  Retry.delay = { kind = fixed; after = duration(\"1s\") }\n}\n```\n\nIn the alpha, `env()` is admitted at `HttpClient.url`, and `secret()` at\n`HttpClient.auth_bearer`. They are not general environment-reading functions\navailable in every expression. The deployment JSON names non-secret values\nand the secret's provider coordinate and version. Actual secret material\nis supplied out of band; the provider version must match the attestation.\nDo not paste a credential into the graph, profile JSON or a shell command.\n\n`examples/webhook-to-partner.deployment.json` is a synthetic Lab profile,\nnot production authorization. The example's Run section supplies an\nexplicitly fictional token and its matching version. The same profile also\nattests the personal-data policy required by the annotated email field.\nMissing or contradictory coverage refuses before effects. Redaction is\nnot permission to persist that data indefinitely.\n\n## Repeat only under a real guarantee\n\n`Retry.attempts = 2` includes the first attempt. The manager retains the\nsame request, waits the declared delay after a selected terminal, then\ntries again within that bound. Intermediate attempt facts remain in the\njournal; only the final attempt is delivered downstream.\n\nThe partner must actually honor the idempotency key for the identical\noperation. Declaring `idempotent = true` cannot make an arbitrary remote\naction safe to repeat. A timeout alone does not prove that it did nothing.\n`Loop` instead advances application state, and keyed instances own isolated\nstate and lifetime. Their detailed protocols belong to later chapters;\n[Two tenants](/examples/03-two-tenants.md) already demonstrates isolation.\n\n## Choose the evidence you need\n\nA golden is a reviewed canonical trace of a Lab scenario. `simulate\n--compare` checks stored references without changing them and names the\nfirst divergence in each differing scenario. `--save` creates or replaces\nreferences, so review the semantic reason before saving. Neither option\nsupplies mock responses; those remain in the Lab.\n\nA diagnostic recording contains the real run's plan and journal evidence.\nReplay reconstructs that evidence, not a fresh execution or a generated\nscenario. The journal is currently in memory. A recording is bounded local\ndiagnostic storage, not a durable deployment journal, automatic restart\nmechanism or share-safe export.\n\nDo not apply the Echo recording command indiscriminately to the webhook\ngraph. The current recorder refuses personal-data plans, nonempty deployment\nattestations and boot-dependent Connector settings before file creation or\neffects. Ordinary unclassified payloads can still be sensitive. Protect the\nfile rather than assuming the debugger's masking rewrites its stored bytes.\n\n`simulate --ui` opens paused and executes the scenario forward under your\ncontrol. Its history controls inspect recorded transitions. `replay --ui`\nonly navigates recorded prefixes, with no Driver I/O. Neither edits the\ngraph or forks a new world, and `run --ui` is not supported.\n\nThe webhook's typed response also retains original annotated measurements\nbefore Retry decides whether to hold or publish an attempt. Missing usage\nis not zero. The alpha does not calculate a bill, aggregate costs or enforce\na Budget Extension. These limits are listed with the other\n[current capabilities](/index.md#what-is-available-today).\n\nThe normative reading is [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md),\n[`docs/spec/observability.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/observability.md), [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md) and [`docs/spec/ui.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/ui.md).\nThe recording contract is `docs/architecture/diagnostic-recording.md`.\n\n## Summary\n\n- Real execution needs compatible physical Drivers and explicit deployment facts.\n- A secret reference is not its material; an attestation is not a source literal.\n- Goldens compare scenarios; recordings reconstruct one captured run.\n- Retry safety and privacy still require real external guarantees.\n\n## Next\n\nContinue with [Instances, state and time](/guide/06-instances-state-and-time.md) for\nstate ownership, lifetimes and bounded closure. [Command line](/guide/09-command-line.md) lists every command and its\noptions, or try [Webhook to partner](/examples/04-webhook-to-partner.md).\nRun its synthetic scenarios, inspect the bounded retry, then review what a\nreal partner and deployment must supply. Return to\n[Getting Started](/getting-started.md#three-ways-to-learn) to choose another example.\n"},{"path":"/reference/connectors/websocket-client","title":"WebSocketClient","description":"Ports, terminal outcomes, settings and qualification evidence for the WebSocketClient connector.","text":"---\ntitle: WebSocketClient\ndescription: Ports, terminal outcomes, settings and qualification evidence for\n  the WebSocketClient connector.\nurl: https://docs.rastok.com/reference/connectors/websocket-client\nsource_revision: v0.2.0-alpha\n---\n\n# WebSocketClient\n\n`std/websocket-client@1`. Opens a peer Session. Each complete message is one value; each graph write is journaled before I/O. One terminal ends the Session, not a message.\n\n## Declaration\n\nThis declaration comes from `crates/rastok/src/lab.rs`. Place the Connector in a Graph\nand wire its ports; the excerpt alone is not an App.\n\n```rkg\nconnector network : WebSocketClient {\n  url = \"wss://example.test/socket\"\n  handshake_timeout = duration(\"5s\")\n  codec = json\n   behavior = deterministic\n}\n```\n\nThe [contract index](/reference/contracts.md) explains shared settings, build features\nand the distinction between a Contract, a Lab model and an installed Driver.\n\nSee [instance ownership and bounded admission](/reference/execution.md#instances-own-state-not-threads); this Contract uses Sessions, not the outbound Call queue rule.\n\n| Mode | Driver direction | Exchange | Lab model | Installed in this binary |\n|---|---|---|---|---|\n| No selector | inbound+outbound | session | `lab-websocket` | Not compiled |\n\n## Ports and completion\n\n| Mode | Port | Direction | Type rule |\n|---|---|---|---|\n| all | `in` | input | `codec = bytes` → `array<byte>`; `codec = json` → `variant`; `codec = string` → `string` |\n| all | `out` | output | Same as `in` |\n| all | `exit` | output | WebSocketExit, below |\n\n| Mode | Output cardinality |\n|---|---|\n| all | Zero or more frames and writes; exactly one `exit` per Session |\n\n## Exit union\n\n| Case | Payload | Call visibility |\n|---|---|---|\n| `Closed` | `{ code: int, reason: string }` | Not an outbound Call |\n| `ConnectFailed` | Empty | Not an outbound Call |\n| `DecodeFailed` | Empty | Not an outbound Call |\n| `DnsFailed` | Empty | Not an outbound Call |\n| `HandshakeRejected` | `{ status: int }` | Not an outbound Call |\n| `MessageTooLarge` | `{ limit: ulong }` | Not an outbound Call |\n| `OutcomeUnknown` | Empty | Not an outbound Call |\n| `ProtocolFailed` | Empty | Not an outbound Call |\n| `TimeoutExpired` | Empty | Not an outbound Call |\n| `TlsFailed` | Empty | Not an outbound Call |\n| `TransportLost` | Empty | Not an outbound Call |\n\n## Settings\n\nWith `codec = json`, `rastok check` refuses a producer whose resolved type\ncontains a [value without a JSON form](/reference/types.md#json-request-values), using\n`E-TYPE-INVALID`. A `variant` producer is checked at execution instead: an\nunencodable message ends the Session with `DecodeFailed` before it is sent.\n\n| Mode | Setting | Domain | Presence / default | Latest phase |\n|---|---|---|---|---|\n| all | `auth_bearer` | `string` | optional | instance |\n| all | `behavior` | `deterministic \\| probabilistic` | required | plan |\n| all | `codec` | `bytes \\| json \\| string` | required | plan |\n| all | `handshake_timeout` | `duration` | required | instance |\n| all | `headers` | `HTTP headers` | optional | instance |\n| all | `custom_headers` | `map<string,array<string>>` | optional | instance |\n| all | `max_message` | `ByteSize` | `\"8MiB\"` | plan |\n| all | `subprotocols` | `array<string>` | optional | instance |\n| all | `tls_ca` | `array<byte>` | optional | instance |\n| all | `tls_certificate` | `array<byte>` | optional | instance |\n| all | `tls_private_key` | `array<byte>` | optional | instance |\n| all | `url` | `string` | required | instance |\n| all | `versions` | `array<http/1.1 \\| http/2 \\| http/3>` | `[\"http/3\", \"http/2\", \"http/1.1\"]` | plan |\n| all | `zero_rtt` | `disabled` | `disabled` | plan |\n\nThe Lab has an effectless Session binding, but authored WebSocket Session\nmocks are not executable. `rastok check` refuses a `mock` on this Connector\nwith `E-CHECK-DEFERRED`; a declaration without a mock still checks. Driver\ntests cover Session opening, frames, writes and terminal outcomes separately.\nInput after a terminal may open a successor Session; old writes are not resent\nautomatically.\n\n## Qualification inventory\n\nNo dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/websocket.rs`.\n"},{"path":"/reference/lab","title":"The Lab","description":"Executable Lab declarations, mock responses, scenario actions, observation windows and golden-trace commands.","text":"---\ntitle: The Lab\ndescription: Executable Lab declarations, mock responses, scenario actions,\n  observation windows and golden-trace commands.\nurl: https://docs.rastok.com/reference/lab\nsource_revision: v0.2.0-alpha\n---\n\n# The Lab\n\nThe real world (App) supplies external observations through Drivers. The\nvirtual world (Lab) supplies scripted observations and logical time to the\nsame graph. Operators and Contract checks execute in both.\n\n## Declarations\n\nSave this complete program as `lab-reference.rkg`, then run\n`rastok check lab-reference.rkg` and `rastok simulate lab-reference.rkg`.\nThe mock replaces the HTTP partner; simulation makes no network request.\n\n```rkg\ngraph lab_reference : App {\n  input in: string\n  output out: string\n  output exit: HttpClientExit\n\n  connector partner : HttpClient {\n    url = \"https://partner.example.test/messages\"\n    method = \"POST\"\n    codec = string\n    behavior = deterministic\n    timeout = duration(\"5s\")\n  }\n\n  in -> partner\n  partner.out -> out\n  partner.exit -> exit\n}\n\nlab replies {\n  // Direct scenarios and simulations inherit this mock.\n  mock partner {\n    on in {\n      out = .\n      exit = Completed { status = 200 }\n    }\n  }\n\n  scenario echoes_the_request {\n    app.in = \"hello\"\n    expect app.out == \"hello\"\n    expect app.exit == Completed { status = 200 }\n  }\n\n  // An optional group can replace the inherited mock for all its scenarios.\n  simulation silent_partner {\n    mock partner {\n      on in { out = nothing }\n    }\n    scenario times_out_without_a_reply {\n      app.in = \"hello\"\n      expect app.out == nothing\n      advance duration(\"5s\")\n      expect app.exit == TimeoutExpired {}\n    }\n  }\n}\n```\n\n| Declaration | Scope and rule |\n|---|---|\n| `lab <name>` | Verification corpus for the unit's App; same-named fragments merge across source files |\n| Direct `scenario <name>` | Runs in the implicit simulation named after its Lab |\n| `simulation <name>` | Optional group with shared mocks; omission of a target selects the App |\n| `simulation <name> : App` | Explicit App target; `app` and the App graph's declared name also work |\n| `mock <connector-path>` | Names an actual Connector: a child of the App root directly, or a top-level declaration by its name |\n| `scenario <name>` | Independent run with its own mocks, origin and actions; the name carries its intent |\n| Mock override | Replaces the whole mock for that Connector: scenario, then simulation, then Lab |\n| Unit-level `val` | Available in mocks, injections, expectations and durations; Graph-local bindings do not escape into the Lab |\n\nA unit has one logical Lab. Duplicate scenarios or mocks at one level refuse. An explicit simulation\ncannot use its Lab's name when the Lab also contains direct scenarios.\nThe Lab is absent from the production package and semantic hash. Mocks do\nnot add ports, change Contracts or supply application metadata fields that\nthe graph never writes.\n\n## Mock responses\n\n| Form | Meaning |\n|---|---|\n| `on in where predicate { ... }` | First matching request clause in source order |\n| `on in { ... }` | Catch-all request clause |\n| Closed or predicate `match` | Select one checked response branch, using the same dispatch rules as the graph |\n| Local `val` | Pure response computation |\n| `out = value`, `err = value` | Emit a frame only on a port that the resolved Contract exposes |\n| `exit = Case { ... }` | Emit the Contract's typed terminal; unique and last |\n| `out = nothing` with no terminal | Explicit silence: leave the Call awaiting its deadline |\n\nEach non-silent Call response has exactly one final `exit` and exactly the\nframes that terminal requires. `rastok check` refuses a branch that omits\na required frame or adds a forbidden one when its terminal is a case\nconstructor. A computed terminal keeps the same check at execution.\nA Session response can emit frames without ending\nthe resource; an optional exit remains last. For Process service, that\nterminal closes the mock child, not an individual conversation turn.\nAn uncovered request or mock evaluation fault fails the scenario.\n\nMocks are request-driven and stateless. Call mocks can select responses from\nthe request and `now()`: [Two tenants](/examples/03-two-tenants.md) selects\nsilence for Alice at the epoch, then responds after the time advance.\nFor each Call, including a Retry attempt, `now()` is the civil timestamp at\nthat Call's opening: the scenario's origin plus its logical opening instant,\nnot the target of the surrounding `advance` or the first attempt's time.\nThere is no authored mock invocation counter.\n`now()` is unavailable in Session mock bodies. Mock metadata writes,\nmulti-emission statements and Loop commands refuse.\n\n## Secrets in the Lab\n\nA mock replaces the external response, not request preparation. A Connector\nwith `secret(\"logical/reference\")` still needs a resolved deployment binding\nto seal its request. Use synthetic material for a simulation, not a production\ncredential. The profile names the variable and its attested version, never\nthe secret value. For example, the secret entry in\n`examples/webhook-to-partner.deployment.json` is:\n\n```json\n{\n  \"reference\": \"showcase/partner/token\",\n  \"environment\": \"RASTOK_SHOWCASE_PARTNER_TOKEN\",\n  \"version\": \"fixture-v1\"\n}\n```\n\nThis entry belongs in the profile's `secrets` array. The example's complete\nprofile also supplies its URL and data-policy declarations. From the repository\nroot, run it with a synthetic value and the matching `_VERSION` variable:\n\n```sh\nRASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential \\\nRASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 \\\nrastok simulate examples/webhook-to-partner.rkg \\\n  --deployment examples/webhook-to-partner.deployment.json\n```\n\nA missing binding names the Connector setting and asks for `--deployment`.\nA missing environment value names its variable; a missing or different\nattested version keeps the version-mismatch refusal. Secret material is not\nprinted in either message.\n\n## Actions\n\n| Action | Effect |\n|---|---|\n| `app.in = value` | Admit an input through a declared App input |\n| `listener.out = value` | Supply a decoded HttpServer `ack` request through its source model |\n| Injection followed by `seq N` | Choose the explicit nonnegative ingress sequence instead of the fixture counter |\n| `advance duration(\"5s\")` | Move the logical timeline and process due obligations without sleeping five seconds |\n| `origin = timestamp(\"2026-10-30T12:00:00Z\")` | Set the immutable civil anchor for this scenario; it is a declaration, not an action |\n\nTime starts at logical zero; the default civil origin is the Unix epoch.\nThe origin affects `now()` and conversion of epoch-aligned slot bounds,\nnot the graph hash. An advance uses a constant duration and cannot move time\nbackwards. Each action settles ready work before the next expectation.\nReady Call mock replies settle at the Call's opening instant. Resident\nProcess Session mock replies settle at the instant of the input they answer.\nTheir consequences run before the next deadline, so one large advance and\nseveral smaller advances deliver the same responses at the same instants.\n\nInjection targets are not arbitrary intermediate ports. Source injection\nmodels a decoded request, not malformed wire bytes or failed bearer\nauthentication. Those refusals need Driver tests. WebSocket and Process\nSession test fixtures use their declared Session model and correlation\nmetadata; they do not fabricate a Call per frame. Authored WebSocket Session\nmocks are not executable and refuse at check with `E-CHECK-DEFERRED`.\nSee the capability distinctions in\n[Standard contracts](/reference/contracts.md).\n\n## Expectations and windows\n\n| Form | Assertion |\n|---|---|\n| `expect target.port` | Exactly one observation |\n| `expect N target.port` | Exactly `N` observations, including zero |\n| `expect target.port == nothing` | No observations |\n| `expect [N] target.port == value` | Exactly `N` observations equal to the value; default one |\n| `expect [N] target.port where predicate` | Exactly `N` matching observations; default one |\n\nSquare brackets in this table denote an optional count, not literal syntax.\nCounts are nonnegative integers. A nonzero count with `== nothing` refuses;\nzero with any other equality value also refuses. Use\n`expect 0 target.port where predicate` to require no matching observation.\n\nEquality uses the ordinary value grammar: scalars, records, tagged cases,\nmaps, frontends and envelope fields. Values are checked against the observed\nport type. A complete data value compares structurally; an envelope pattern\nwithout a whole `data` assignment compares only its written fields.\nIf a port or field has type `decimal`, an expectation of `7` matches\n`7u` and `decimal(\"7.00\")` as well. The journal keeps the value as received.\nPredicates are checked over the observed port type; narrow a `variant`\nbefore reading its fields. An evaluation fault is a scenario fault, not a\nnon-match. A newline after the port ends the expectation.\n\nAn injection or time advance opens a new observation window. All following\nexpectations inspect that window without consuming it; earlier windows are\nexcluded. An emission appears once at its source, even if routed to\n`nothing`. `app.<output>` observes an actual App-boundary crossing.\nExpectations do not inspect private Operator state or a mailbox.\n\nWith Retry, an expectation on the Connector's own `exit` observes the\nterminal of every attempt, because each attempt is a journal fact. The\ngraph downstream receives only the last one: assert the delivered\noutcome on the consumer's port. A repeated attempt does not appear on\n`<connector>.in`; the request is admitted once.\n\n## Golden traces\n\n```sh\nrastok simulate examples/echo.rkg\nrastok simulate examples/echo.rkg --compare examples/traces/echo\nrastok simulate examples/echo.rkg --save examples/traces/echo\n```\n\n| Option | Result |\n|---|---|\n| Neither | Run scenario expectations without consulting reference traces |\n| `--compare <dir>` | Compare with stored traces, without modifying them |\n| `--save <dir>` | Write or replace reference traces for intentional review |\n| Both | Usage error |\n| `--ui` | Inspect simulation boundaries and run them step by step in the debugger (requires a `hosted-ui` build) |\n\nEach file is `<simulation>.<scenario>.rkc`. The stored format is\ndeterministic CBOR rendered as one lowercase hexadecimal line per causal\nrecord, followed by `seal <BLAKE3 digest>`. The seal covers concatenated\nrecord bytes. It excludes unsealed observations, such as host timing, but\nincludes a handler's explicit observation of `now()`.\n\nA comparison reports the first divergent record, expected and obtained\nvalues, and causal context. For classified data, displayed details are\nmasked while the comparison still uses the canonical bytes. A golden trace\nis distinct from the diagnostic recording produced by `run --record`:\n`replay` reconstructs recorded facts without calling a Driver again.\n\nA timestamp, duration or null can already travel as a whole payload in the\nLab. For example, `expect app.wait == duration(\"5s\")` compares the duration,\nnot its printed spelling. A mock receives the value the graph sent. On a\nProcess JSONL output or an untyped HttpClient JSON response, its output\ncrosses the same JSON boundary as the Driver's: an object arrives as a map.\nUse `data as? Receipt` to read that object as a declared struct. A typed HttpClient mock supplies the decoded\nvalue. To model an invalid response body, write, for example,\n`exit = DecodeFailed { message = \"response field out.due expects timestamp\" }`.\nA handler can read `data.message` after testing `data is DecodeFailed`.\n\n## Specified, not shipped\n\n| Item | Specification |\n|---|---|\n| Sub-graph simulation targets other than `app` | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §2 |\n| Delayed mock `after` actions | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§3, 5.1; [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), mock grammar |\n| Scenario `crash node` and `restart node` | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §5.4 |\n| HttpServer `respond` source scripting; delayed/unsolicited Process service scripts | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§2, 5.1 |\n| Mocks for WebSocket Sessions (refused at check with `E-CHECK-DEFERRED`) | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §2 |\n| Positive `expect fault` and assertions on private state | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §5.2 |\n| Automatic outcome coverage, generated scenarios and tags | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§7–8 |\n| Production-to-scenario extraction | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §9 |\n| Experiments and theorems | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§10–11 |\n\nSources: [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md), [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), the\nchecked scenario tree and the CLI trace writer. The guided walkthrough is\n[The Lab: scenarios, mocks and time](/guide/04-the-lab.md).\n"},{"path":"/examples/06-agent-gateway","title":"Agent gateway: keep a conversation isolated","description":"Connect WebSocket conversations to resident JSONL processes, simulate interleaved app-server requests, and close one child without interrupting the other.","text":"---\ntitle: \"Agent gateway: keep a conversation isolated\"\ndescription: Connect WebSocket conversations to resident JSONL processes,\n  simulate interleaved app-server requests, and close one child without\n  interrupting the other.\nurl: https://docs.rastok.com/examples/06-agent-gateway\nsource_revision: v0.2.0-alpha\n---\n\n# Agent gateway: keep a conversation isolated\n\nThis program connects each conversation to its own resident process and routes its replies to the right client.\n\nThe sensor chapter kept state while time passed. A conversation adds state\noutside the graph: the memory of a child process. Alice and Bob should each\nkeep their own child across several turns. Ending Alice's child must not\ninterrupt Bob, and sending a message must not be mistaken for receiving an\nanswer.\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root, with `rastok` built with `hosted-ui` for the\nbrowser command (the non-browser command below does not need that feature):\n\n```sh\nrastok simulate examples/agent-gateway.rkg --compare examples/traces/agent-gateway --ui\n```\n\nThe debugger starts paused in the source view. Follow one input with\n**Next transition** and watch the source marker. Hover a port identifier, or\nfocus it with Tab, to inspect its recorded value and open the full object in\nthe inspector. The instance and Session tables show the recorded ownership.\nThe **Graph** pane below the inspector follows connections while the source\nstays visible on the left. Selecting a node selects its source definition and\ninspector context. Both dividers are adjustable. **Fit graph** shows the complete\ndrawing; **Readable size** restores interface-sized text with panning. Instance\nsections show counts and keep empty sections folded. For the reproducible CLI check:\n\n```sh\nrastok simulate examples/agent-gateway.rkg --compare examples/traces/agent-gateway\n```\n\n```text\nPASS app_server.two_conversations\nPASS app_server.unknown_method\n2 scenario(s), 0 failed\n```\n\nFor the controls and source view, see [the debugger tour](/debugger.md).\n\n## Read the program\n\nStart at `clients.out` on the [WebSocketServer](/reference/connectors/websocket-server.md): each message enters `conversation`, where\n`instance = { key = meta.ext.session_id }` scopes its children. The first\nmessage opens [Process](/reference/connectors/process.md) with `mode = service`; later messages write to the same\nchild. Each `route_reply` instance remembers its socket address and restores\nit on that child's responses.\n\nThe real command is `codex app-server --listen stdio://`. The client, not\nProcess, speaks its JSON-RPC protocol: initialize, acknowledge initialization,\nstart a thread, send a turn. Requests, replies and notifications pass through\nas JSON, including client replies without a `method` field. The Lab's `match`\nreplaces the child; it never launches Codex. Its `peer` input supplies the\nscenario's incoming messages.\n\nFollow `finish.out -> model.instance.stop` last. An authored `close` input\nrequests that exact child generation's Closing, not every Process or the\nwhole conversation Graph. Socket closure has its own `session_exit` output.\n\nThe [Lab reference](/reference/lab.md) explains mock responses, expectations\nand observation windows. `advance` supplies virtual time; a mock's terminal\nresponse ends its simulated exchange, not the whole scenario.\n\n<a id=\"graph\"></a>\n\nSource: `examples/agent-gateway.rkg`\n\n```rkg\n// One local WebSocket conversation owns one resident JSONL process.\n// Clients speak the Codex app-server protocol: initialize, initialized,\n// thread/start, then turn/start. The Lab never launches Codex.\nval alice_session = \"11111111111111111111111111111111\"\nval bob_session = \"22222222222222222222222222222222\"\nval thread_id = \"thread-1\"\n\ntype JsonObject = map<string,variant>\n\ngraph agent_gateway : App {\n  // Public fixture ingress; real clients enter through clients.out instead.\n  input peer: variant\n  input close: variant\n  output reply: variant\n  output process_exit: ProcessExit\n  output session_exit: variant\n\n  connector clients : WebSocketServer {\n    listen = \"127.0.0.1:8443\"\n    path = \"/agent\"\n    codec = json\n    handshake_timeout = duration(\"5s\")\n    max_message = \"1MiB\"\n    correlate = meta.ext.session_id\n    versions = [\"http/1.1\"]\n  }\n\n  graph conversation {\n    input in: variant\n    input close: variant\n    output out: variant\n    output exit: ProcessExit\n    instance = { key = meta.ext.session_id }\n    lifetime = { kind = idle; max = duration(\"5m\") }\n    closing = { drain_for = duration(\"1s\"); settle_for = duration(\"1s\") }\n\n    connector model : Process {\n      mode = service\n      command = \"codex\"\n      args = [\"app-server\", \"--listen\", \"stdio://\"]\n      codec = jsonl\n      max_frame = \"1MiB\"\n\n      behavior = probabilistic\n      closing = { drain_for = duration(\"1s\"); settle_for = duration(\"1s\") }\n    }\n\n    operator route_reply {\n      input remember: variant\n      input in: variant\n      output out: variant\n      var socket: string = \"\"\n      // Admission queues remember before child replies can be routed here.\n      // This state belongs to this conversation, not a global last-request slot.\n      on remember { socket = meta.ext.session_id as string }\n      on in { out = { data = data; meta.ext.session_id = socket } }\n    }\n\n    operator finish {\n      input in: variant\n      output out: variant\n      on in { out = . }\n    }\n\n    in -> model\n    in -> route_reply.remember\n    close -> finish\n    finish.out -> model.instance.stop\n    model.out -> route_reply -> out\n    model.err -> nothing\n    model.exit -> exit\n  }\n\n  clients.out -> conversation\n  peer -> conversation\n  close -> conversation.close\n  conversation.out -> { clients.in; reply }\n  conversation.exit -> process_exit\n  // Closing a socket is observable, not an implicit process cancellation.\n  // The idle lifetime bounds abandoned conversations independently.\n  clients.exit -> session_exit\n}\n\nlab app_server {\n  mock conversation.model {\n    // Actual JSON objects are maps, not DSL struct literals.\n    // This fixture's client frames all have the protocol's method field.\n    on in where data is JsonObject {\n      match {\n        data.?method == \"initialize\" => out = { \"id\": data.?id, \"result\": { \"userAgent\": \"scripted-codex\" } }\n        data.?method == \"initialized\" => nothing\n        data.?method == \"thread/start\" => out = { \"id\": data.?id, \"result\": { \"thread\": { \"id\": thread_id } } }\n        data.?method == \"turn/start\" => {\n          val turn_id = \"turn-1\"\n          out = { \"id\": data.?id, \"result\": { \"turn\": { \"id\": turn_id, \"status\": \"inProgress\" } } }\n          out = ({ \"method\": \"item/agentMessage/delta\", \"params\": { \"threadId\": thread_id, \"turnId\": turn_id, \"itemId\": \"item-1\", \"delta\": \"Hello from the simulated agent.\" } })\n          out = ({ \"method\": \"turn/completed\", \"params\": { \"threadId\": thread_id, \"turn\": { \"id\": turn_id, \"status\": \"completed\" } } })\n        }\n        data.?method == \"turn/interrupt\" => out = { \"id\": data.?id, \"result\": {:} }\n        _ => out = { \"id\": data.?id, \"error\": { \"code\": -32601, \"message\": \"scripted method unavailable\" } }\n      }\n    }\n    on in { out = nothing }\n  }\n\n  scenario two_conversations {\n    app.peer = { meta.ext.session_id = alice_session; data = { \"id\": 0, \"method\": \"initialize\", \"params\": { \"clientInfo\": { \"name\": \"rastok_gallery\", \"version\": \"1\" } } } }\n    expect app.reply where meta.ext.session_id == alice_session\n    app.peer = { meta.ext.session_id = bob_session; data = { \"id\": 0, \"method\": \"initialize\", \"params\": { \"clientInfo\": { \"name\": \"rastok_gallery\", \"version\": \"1\" } } } }\n    expect app.reply where meta.ext.session_id == bob_session\n    app.peer = { meta.ext.session_id = alice_session; data = { \"method\": \"initialized\" } }\n    expect app.reply == nothing\n    app.peer = { meta.ext.session_id = bob_session; data = { \"method\": \"initialized\" } }\n    app.peer = { meta.ext.session_id = alice_session; data = { \"id\": 1, \"method\": \"thread/start\", \"params\": { \"approvalPolicy\": \"never\", \"sandbox\": \"read-only\" } } }\n    expect app.reply\n    app.peer = { meta.ext.session_id = bob_session; data = { \"id\": 1, \"method\": \"thread/start\", \"params\": { \"approvalPolicy\": \"never\", \"sandbox\": \"read-only\" } } }\n    expect app.reply\n    app.peer = { meta.ext.session_id = alice_session; data = { \"id\": 2, \"method\": \"turn/start\", \"params\": { \"threadId\": thread_id, \"input\": [{ \"type\": \"text\", \"text\": \"Hello Alice\" }] } } }\n    expect 3 app.reply where meta.ext.session_id == alice_session\n    expect app.process_exit == nothing\n    app.peer = { meta.ext.session_id = bob_session; data = { \"id\": 2, \"method\": \"turn/start\", \"params\": { \"threadId\": thread_id, \"input\": [{ \"type\": \"text\", \"text\": \"Hello Bob\" }] } } }\n    expect 3 app.reply where meta.ext.session_id == bob_session\n    app.close = { meta.ext.session_id = alice_session; data = \"operator requested shutdown\" }\n    advance duration(\"2s\")\n    expect app.process_exit where data is OutcomeUnknown\n    app.peer = { meta.ext.session_id = bob_session; data = { \"id\": 3, \"method\": \"turn/start\", \"params\": { \"threadId\": thread_id, \"input\": [{ \"type\": \"text\", \"text\": \"Still here?\" }] } } }\n    expect 3 app.reply where meta.ext.session_id == bob_session\n    expect app.process_exit == nothing\n  }\n\n  scenario unknown_method {\n    app.peer = { meta.ext.session_id = alice_session; data = { \"id\": 0, \"method\": \"fixture/unknown\", \"params\": {:} } }\n    expect app.reply\n    expect app.process_exit == nothing\n  }\n}\n```\n\n## Expected result\n\nThis cut of `app_server.two_conversations` starts after both initialization\nand thread exchanges. The Lab enters through `peer`, not a real socket;\neach reply also targets `clients.in`, omitted here to focus on isolation.\n\n```mermaid\nsequenceDiagram\n    participant lab as Lab: app_server.two_conversations\n    participant app as agent_gateway\n    participant model as conversation.model: Process service\n    participant route as conversation.route_reply\n    participant finish as conversation.finish\n    Note over model,route: Separate instances keyed by session_id\n    loop Alice, then Bob, in recorded order\n        lab->>app: peer = turn/start, id 2, session_id\n        app->>model: in = turn/start for this session\n        app->>route: remember = this session_id\n        model->>lab: Scripted service input\n        lab-->>model: Response, delta, turn/completed\n        model->>route: Three out frames in that order\n        route-->>app: Three reply frames addressed to this session\n    end\n    lab->>app: close = Alice's session\n    app->>finish: in = close request\n    finish->>model: Alice: instance.stop\n    lab->>lab: advance 2s\n    model-->>app: process_exit = OutcomeUnknown for Alice\n    lab->>app: peer = Bob's turn/start, id 3\n    Note over model,route: Bob's original service returns three addressed replies\n```\n\nAlice and Bob both initialize and start a thread. Both use request ids 0, 1\nand 2: isolation cannot rely on globally unique RPC ids. Each scripted turn\nreturns an initial response, a text delta and a final notification. Two\nresources serve the conversation, not one process per message. Alice's stop\nsettles as `OutcomeUnknown` because the mock supplies no system-shutdown\nobservation. Bob's next turn still uses his original child.\n\nThe second scenario returns a scripted unknown-method error. It is JSON data,\nnot a Process `exit`. The separate resident primer,\n[agent-dialogue.rkg](/examples/agent-dialogue.rkg), shows an\napplication `quit`, observed resource exit and a fresh resource on new input.\nIts real child, `cat`, echoes a JSON line with `tenant` and `text`. The\nadapter reads the object with `as? Message` and puts the text in the reply's\n`answer` field. Only the Lab supplies the scripted conversation.\n\nWith `cat` on PATH, run the primer interactively:\n\n```sh\nrastok run examples/agent-dialogue.rkg\n```\n\nType `hello from cat` and press Enter. The real reply is:\n\n```text\nout: {\"answer\":\"hello from cat\",\"tenant\":\"local\"}\n```\n\nEach line uses the same local session. Press Ctrl-C to stop it.\n\nTo run the scripted conversations instead, use the same traces directory as the gateway:\n\n```sh\nrastok simulate examples/agent-dialogue.rkg --compare examples/traces/agent-gateway\n```\n\n```text\nPASS scripted_model.alice_and_bob\nPASS scripted_model.fresh_child\n2 scenario(s), 0 failed\n```\n\nTo break just this primer, change `text = \"Plant tomatoes.\"` in the mock to\n`text = \"Plant carrots.\"`. Leave the expectations and reference traces alone:\n\n```sh\nrastok simulate examples/agent-dialogue.rkg --compare examples/traces/agent-gateway\n```\n\n```text\nFAIL scripted_model.alice_and_bob\n     expect app.out where data.tenant == \"alice\" && data.answer == \"Plant tomatoes.\"  (agent-dialogue.rkg:95)\n     observed app.out: {\"answer\":\"Plant carrots.\",\"tenant\":\"alice\"}\n     where data.tenant == \"alice\" && data.answer == \"Plant tomatoes.\" is false for 1 of 1 deliveries; count 0, expected 1\n     golden divergence: record 10: envelope(8) . data(5)[1] (ccbor value)[1][0][1][1]; expected \"Plant tomatoes.\"; got \"Plant carrots.\"; cause: INGRESS \"conversation.model\" · port \"out\" · sequence 0\nFAIL scripted_model.fresh_child\n     golden divergence: record 10: envelope(8) . data(5)[1] (ccbor value)[1][0][1][1]; expected \"Plant tomatoes.\"; got \"Plant carrots.\"; cause: INGRESS \"conversation.model\" · port \"out\" · sequence 0\n2 scenario(s), 2 failed\n```\n\nThe first scenario expected the original answer. The second checks that an answer\narrives, but its reference trace also checks which answer it was. Restore the example\nbefore continuing; this discards your edit to this file:\n\n```sh\ngit checkout -- examples/agent-dialogue.rkg\n```\n\n## Add the small browser client\n\nThe next step is [Rastok Codex Gateway](/examples/agent-chat.rkg), with a\nsingle [readable HTML file](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/examples/agent-chat.html). It uses plain\nHTML, CSS and JavaScript, with English comments: no framework, build step,\nCDN or generated bundle. Start with its scripted protocol:\n\n```sh\nrastok simulate examples/agent-chat.rkg\n```\n\n```text\nPASS browser_protocol.alice_and_bob\nPASS browser_protocol.duplicate_name\nPASS browser_protocol.invalid_message\n3 scenario(s), 0 failed\n```\n\nThree scenarios cover interleaved conversations, a duplicate nickname and\ninvalid messages. The same app-server handshake is now wrapped in\n`{ nickname, kind, rpc }`. `conversation` is keyed by the nickname and remembers\nits socket; a second socket cannot take that name or close its child. The Lab\nstill enters through `peer`, without binding either network listener.\n\nFor the real local application, use a macOS or Linux shell and install and\nconfigure Codex on PATH first. Live account-dependent output is not quoted\nhere: the documented checks run only the Lab. This\ncommand **does launch real processes** when a client connects, and sending a\nmessage may use your configured model/account:\n\n```sh\ncargo run -p rastok --features hosted-websocket -- run examples/agent-chat.rkg\n```\n\nOpen `http://127.0.0.1:8777/`, connect as Alice, and open another tab for Bob.\nSend a message in each, then choose **Quit** for Alice and continue with Bob.\nThe page waits for `turn/completed`, not just the initial `turn/start` reply,\nbefore enabling the next message. Model text is rendered literally, not as HTML.\nAn unsupported server-initiated request is explicitly declined.\n\nThe two flows share an App, not a transaction. `page` serves the embedded\n`asset(...)` through [HttpServer](/reference/connectors/http-server.md); `clients` carries chat over WebSocket at\n`127.0.0.1:8778/chat`. Neither listener is inside the keyed conversation.\nThe current cooperative Worker can keep serving the page and other children\nwhile external I/O waits; this does not claim parallel DSL execution.\n\nQuit is an application message routed to `instance.stop` **inside that\nconversation**. It closes the conversation and its children, not the App or\nBob. It is never a magic line sent to Codex's stdin. The acknowledgement means\n“closure requested”, not “the child exited successfully”. Closing a browser\ntab without Quit is different: the abandoned conversation has a five-minute\nidle lifetime. This page has no reconnect/resume feature or saved history.\nIt sends `ephemeral: true` on each `thread/start`: new Codex conversations\nstay in memory instead of being saved as local thread history. This option\nis part of the [app-server protocol](https://learn.chatgpt.com/docs/app-server),\nnot a Process flag. It does not delete earlier histories or disable technical\nlogs, Rastok's in-memory journal, or the model provider's data retention.\nQuit still requests process closure, not deletion of files.\n\nThe page selects the app-server read-only sandbox and no-approval policy;\nthis is a trusted local example, not a security boundary. Do not expose the\nlisteners publicly or send credentials through the chat. Editing the HTML\nchanges its embedded asset: restart `run` to load the new file.\n\n## Inspect a typed model response\n\nThe [HTTP model adapter](/examples/08-model-adapter.md) makes one non-streaming OpenAI\nResponses request per job. It selects a typed JSON response, retains original\nusage samples with their job and session, and distinguishes missing usage\nfrom an observed zero. Its six scenarios run with synthetic boot bindings.\n\nUse that chapter for the reproducible command, projected-schema rules,\nsecret boundary and golden comparison. A resident process preserves a\nconversation across messages; this adapter sends independent jobs and does\nnot retry an inference that could be charged twice.\n\n## Break it\n\nChange only `Hello from the simulated agent.` to `A different answer.` in\nthe mock. Leave the golden unchanged and run the comparison below.\nThe graph still compiles, and the shape/count assertions still pass. The\nchanged answer nevertheless differs in the recorded evidence.\n\n```sh\nrastok simulate examples/agent-gateway.rkg --compare examples/traces/agent-gateway\n```\n\n```text\nFAIL app_server.two_conversations\n     golden divergence: record 51: envelope(8) . data(5)[1] (ccbor value)[1][1][1][1][0][1][1]; expected \"Hello from the simulated agent.\"; got \"A different answer.\"; cause: INGRESS \"conversation.model\" · port \"out\" · sequence 5\nPASS app_server.unknown_method\n2 scenario(s), 1 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/agent-gateway.rkg\n```\n\n## Read the golden difference\n\nThe diff names the first changed record, expected and actual data, and the\nrecorded cause. Here the changed evidence is an inbound service frame, not\nan invented per-turn Call completion. Do not use `--save` to hide the change.\nRestore the answer before continuing.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/agent-gateway/app_server.two_conversations.rkc`\n\n```rastok-trace\na7070108a50150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025869821083828206626964820200828206666d6574686f6482066a696e697469616c697a6582820666706172616d738210818282066a636c69656e74496e666f821082828206646e616d6582066e726173746f6b5f67616c6c6572798282066776657273696f6e82066131068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a000b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na80702116c636f6e766572736174696f6e1282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000\na807021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na70702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d6265728243828080000116818266736f636b65748206782031313131313131313131313131313131313131313131313131313131313131311780\na20703182585015060f0ea2e346639561873c38cc146c4e550f3df1105112054d397a04ed0666ca4c872636f6e766572736174696f6e2e6d6f64656c5820310e5f8777e8a955077d59025cbf16dd436689f888e710ef8cff288a13053788\na20703182583025060f0ea2e346639561873c38cc146c4e572636f6e766572736174696f6e2e6d6f64656c\na9070108a50150362854cc809d77e8494e9a5dabf4bbe20350362854cc809d77e8494e9a5dabf4bbe20401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a000b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310001178183636f757400a6015061829718361a64aa02209a504448618d0250362854cc809d77e8494e9a5dabf4bbe20350362854cc809d77e8494e9a5dabf4bbe20401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f6964820678203131313131313131313131313131313131313131313131313131313131313131181881820850c5bb442dc34dbd29f39a6dd93aba1f3a181981835061829718361a64aa02209a504448618d7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na807021167636c69656e747312824b828167636c69656e7473800013676c3a737461727414801780181a5061829718361a64aa02209a504448618d1822824382808000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100011780181a5061829718361a64aa02209a504448618d\na7070108a50150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025869821083828206626964820200828206666d6574686f6482066a696e697469616c697a6582820666706172616d738210818282066a636c69656e74496e666f821082828206646e616d6582066e726173746f6b5f67616c6c6572798282066776657273696f6e82066131068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a010b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na80702116c636f6e766572736174696f6e1282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824382808000\na807021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na70702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d6265728243828080000216818266736f636b65748206782032323232323232323232323232323232323232323232323232323232323232321780\na20703182585015028ca2e2364d3761195c1858dc8f48b0250e6c20d6146234b74a33da1c709e86efd72636f6e766572736174696f6e2e6d6f64656c5820310e5f8777e8a955077d59025cbf16dd436689f888e710ef8cff288a13053788\na20703182583025028ca2e2364d3761195c1858dc8f48b0272636f6e766572736174696f6e2e6d6f64656c\na9070108a50150da26c6766ce89f38556f36b29c85d8600350da26c6766ce89f38556f36b29c85d8600401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a010b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320001178183636f757400a60150a6a9a6aa373d0ad52606aba55efd822b0250da26c6766ce89f38556f36b29c85d8600350da26c6766ce89f38556f36b29c85d8600401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f69648206782032323232323232323232323232323232323232323232323232323232323232321818818208500f26f577b136b33c00af37544808d3761819818350a6a9a6aa373d0ad52606aba55efd822b7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200011780181a50a6a9a6aa373d0ad52606aba55efd822b\na7070108a501506c793d2fff3f39818152c34ffedee98103506c793d2fff3f39818152c34ffedee9810401058202581b821081828206666d6574686f6482066b696e697469616c697a6564068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a020b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000031780\na20703182586035060f0ea2e346639561873c38cc146c4e550dfc724074306fa8e15132b42ebd3c211506c793d2fff3f39818152c34ffedee98172636f6e766572736174696f6e2e6d6f64656c5820a5b8f3e7598201ae7ece5b18fa12780e91f4fa6d00d63228263653fdcd4533a6\na20703182584045060f0ea2e346639561873c38cc146c4e550dfc724074306fa8e15132b42ebd3c21172636f6e766572736174696f6e2e6d6f64656c\na7070108a501501f48ee4d457e9526b70a88345813643a03501f48ee4d457e9526b70a88345813643a0401058202581b821081828206666d6574686f6482066b696e697469616c697a6564068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a030b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000041780\na20703182586035028ca2e2364d3761195c1858dc8f48b0250403609522b50139cd9e5f70500a46d24501f48ee4d457e9526b70a88345813643a72636f6e766572736174696f6e2e6d6f64656c5820a5b8f3e7598201ae7ece5b18fa12780e91f4fa6d00d63228263653fdcd4533a6\na20703182584045028ca2e2364d3761195c1858dc8f48b0250403609522b50139cd9e5f70500a46d2472636f6e766572736174696f6e2e6d6f64656c\na7070108a501507a1dc07e4137d05e725f8902f4c53a6b03507a1dc07e4137d05e725f8902f4c53a6b04010582025863821083828206626964820201828206666d6574686f6482066c7468726561642f737461727482820666706172616d738210828282066773616e64626f78820669726561642d6f6e6c798282066e617070726f76616c506f6c6963798206656e65766572068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a040b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000051780\na20703182586035060f0ea2e346639561873c38cc146c4e55023f9925781f33c8606191c249d91a336507a1dc07e4137d05e725f8902f4c53a6b72636f6e766572736174696f6e2e6d6f64656c5820785cb53ea440f6bb44f2ff148bde2eea8996a1dcf8278c576b0142d24536b506\na20703182584045060f0ea2e346639561873c38cc146c4e55023f9925781f33c8606191c249d91a33672636f6e766572736174696f6e2e6d6f64656c\na9070108a50150d85cab4a77515fa815eeda088b0d8e7d0350d85cab4a77515fa815eeda088b0d8e7d0401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a020b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310002178183636f757400a60150a48c7eae647650d39d1353c60e88253c0250d85cab4a77515fa815eeda088b0d8e7d0350d85cab4a77515fa815eeda088b0d8e7d0401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f69648206782031313131313131313131313131313131313131313131313131313131313131311818818208509bf911312c93486a11872119b36378221819818350a48c7eae647650d39d1353c60e88253c7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100021780181a50a48c7eae647650d39d1353c60e88253c\na7070108a501505a65c55dbdea6f2f6195918a7014326703505a65c55dbdea6f2f6195918a7014326704010582025863821083828206626964820201828206666d6574686f6482066c7468726561642f737461727482820666706172616d738210828282066773616e64626f78820669726561642d6f6e6c798282066e617070726f76616c506f6c6963798206656e65766572068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a050b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000061780\na20703182586035028ca2e2364d3761195c1858dc8f48b0250965c529effe97365ee48d403c8eaea9d505a65c55dbdea6f2f6195918a7014326772636f6e766572736174696f6e2e6d6f64656c5820785cb53ea440f6bb44f2ff148bde2eea8996a1dcf8278c576b0142d24536b506\na20703182584045028ca2e2364d3761195c1858dc8f48b0250965c529effe97365ee48d403c8eaea9d72636f6e766572736174696f6e2e6d6f64656c\na9070108a5015070263ee695d6f82fe6b7eaab5cdb6df8035070263ee695d6f82fe6b7eaab5cdb6df80401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a030b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320002178183636f757400a60150094928430ad3dc030db4357d5def6b60025070263ee695d6f82fe6b7eaab5cdb6df8035070263ee695d6f82fe6b7eaab5cdb6df80401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085007dc03a8a0f441b692274fb0d231e8fc1819818350094928430ad3dc030db4357d5def6b607827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200021780181a50094928430ad3dc030db4357d5def6b60\na7070108a5015094300aa39de9b2df8c605fb45942949c035094300aa39de9b2df8c605fb45942949c0401058202587b821083828206626964820202828206666d6574686f6482066a7475726e2f737461727482820666706172616d7382108282820665696e707574821181821082828206647465787482066b48656c6c6f20416c6963658282066474797065820664746578748282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a060b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000071780\na20703182586035060f0ea2e346639561873c38cc146c4e55036d97cb49e6b2dda7be724dfab872b3b5094300aa39de9b2df8c605fb45942949c72636f6e766572736174696f6e2e6d6f64656c58207c3a3a080b7bf40552e42561101343021e13c7961cd2844df0f65f5b55320018\na20703182584045060f0ea2e346639561873c38cc146c4e55036d97cb49e6b2dda7be724dfab872b3b72636f6e766572736174696f6e2e6d6f64656c\na9070108a501508399157fc1ce3bee3b71ecc12416c3c503508399157fc1ce3bee3b71ecc12416c3c50401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a040b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310003178183636f757400a601505ee43032f78c7dee057dd08e02fc9bb602508399157fc1ce3bee3b71ecc12416c3c503508399157fc1ce3bee3b71ecc12416c3c50401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782031313131313131313131313131313131313131313131313131313131313131311818818208501defae7990bb311da534ab1f1bca309518198183505ee43032f78c7dee057dd08e02fc9bb67827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100031780181a505ee43032f78c7dee057dd08e02fc9bb6\na9070108a50150a599ab8b09d1ad42b0da4db66542d37d0350a599ab8b09d1ad42b0da4db66542d37d0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a050b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310004178183636f757400a601504d002ed62c923755160e6b980fdf22690250a599ab8b09d1ad42b0da4db66542d37d0350a599ab8b09d1ad42b0da4db66542d37d0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313118188182085025a18503ead56bea58a1b80afd84973b18198183504d002ed62c923755160e6b980fdf22697827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100041780181a504d002ed62c923755160e6b980fdf2269\na9070108a5015021da703c80ac8a5699477d71967da0af035021da703c80ac8a5699477d71967da0af04010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a060b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310005178183636f757400a601503476f939f976804bdd24cdae240e2429025021da703c80ac8a5699477d71967da0af035021da703c80ac8a5699477d71967da0af04010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f6964820678203131313131313131313131313131313131313131313131313131313131313131181881820850fdb891ba72f9e5aa9f7f5476315a524d18198183503476f939f976804bdd24cdae240e24297827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100051780181a503476f939f976804bdd24cdae240e2429\na7070108a5015091784c371eafa12dd3f5b1371b9a99f0035091784c371eafa12dd3f5b1371b9a99f004010582025879821083828206626964820202828206666d6574686f6482066a7475726e2f737461727482820666706172616d7382108282820665696e707574821181821082828206647465787482066948656c6c6f20426f628282066474797065820664746578748282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a070b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000081780\na20703182586035028ca2e2364d3761195c1858dc8f48b02509c4837ed8dfb86e0e9a0c105e53199b45091784c371eafa12dd3f5b1371b9a99f072636f6e766572736174696f6e2e6d6f64656c5820b97e7d53bbbee50dca746a05483d53e494dc56b1494fd6e6a0253dc8c0f36dfe\na20703182584045028ca2e2364d3761195c1858dc8f48b02509c4837ed8dfb86e0e9a0c105e53199b472636f6e766572736174696f6e2e6d6f64656c\na9070108a501503667cc57f26972263806465fc521fbe303503667cc57f26972263806465fc521fbe30401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a070b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320003178183636f757400a601505ec01b153123b01b38bbe8bb56dcbc6902503667cc57f26972263806465fc521fbe303503667cc57f26972263806465fc521fbe30401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782032323232323232323232323232323232323232323232323232323232323232321818818208509609abe35466aef5d0e20a3b2a09193718198183505ec01b153123b01b38bbe8bb56dcbc697827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200031780181a505ec01b153123b01b38bbe8bb56dcbc69\na9070108a501503b5d783f2a2355c94fb177fcf3d821ce03503b5d783f2a2355c94fb177fcf3d821ce0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a080b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320004178183636f757400a6015050dc87efbca589bd458fa9f86a8f606f02503b5d783f2a2355c94fb177fcf3d821ce03503b5d783f2a2355c94fb177fcf3d821ce0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085072e0e9e05713400422e08d459e037131181981835050dc87efbca589bd458fa9f86a8f606f7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200041780181a5050dc87efbca589bd458fa9f86a8f606f\na9070108a501508e6d79deb010ca935813401a687af50903508e6d79deb010ca935813401a687af50904010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a090b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320005178183636f757400a60150a5ff7c92c54b7228552513b97c412fb002508e6d79deb010ca935813401a687af50903508e6d79deb010ca935813401a687af50904010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032323232323232323232323232323232323232323232323232323232323232321818818208509069cd3f4fb01ad07bf4667928e1789f1819818350a5ff7c92c54b7228552513b97c412fb07827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200051780181a50a5ff7c92c54b7228552513b97c412fb0\na7070108a5015094e195b78473826cf0a323972a212aa9035094e195b78473826cf0a323972a212aa90401058202581f8206781b6f70657261746f72207265717565737465642073687574646f776e068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a080b000c65636c6f73650d8182781d2e636c6f73653e636f6e766572736174696f6e2e66696e6973682e696e82584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na807021173636f6e766572736174696f6e2e66696e6973681282584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a5094e195b78473826cf0a323972a212aa9182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100\na707021173636f6e766572736174696f6e2e66696e6973681282584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e148183781d2e636c6f73653e636f6e766572736174696f6e2e66696e6973682e696e82438280800001178183636f757400a60150d3759ac2297936b27bd918838727504d025094e195b78473826cf0a323972a212aa9035094e195b78473826cf0a323972a212aa90401058202581f8206781b6f70657261746f72207265717565737465642073687574646f776e068183636578746a73657373696f6e5f6964820678203131313131313131313131313131313131313131313131313131313131313131182aa101818750a4b1d86f91e1de597d736278be92a8c102636f757482584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310082584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310082584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310050d3759ac2297936b27bd918838727504d\naa07021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a636c6f736514801780181882820550d72f675db802aa830f6374bb7429a2a282065034aa66a9f5e197b28bf2dd8617ff48f7181a50d3759ac2297936b27bd918838727504d182382584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100182aa10250a4b1d86f91e1de597d736278be92a8c1\na807021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013666c3a65786974148183781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82438280800001178183646578697400a60150d4cae196e843d14556fca9aea74f7d4b0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202558213826e4f7574636f6d65556e6b6e6f776e820f80068183636578746a73657373696f6e5f6964820678203630663065613265333436363339353631383733633338636331343663346535181a50f3df1105112054d397a04ed0666ca4c818245060f0ea2e346639561873c38cc146c4e5\na707021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013666c3a73746f7014801780181a50d3759ac2297936b27bd918838727504d\na7070108a50150321cb79d91c55f2a83c1d37584dd2f380350321cb79d91c55f2a83c1d37584dd2f380401058202587b821083828206626964820203828206666d6574686f6482066a7475726e2f737461727482820666706172616d7382108282820665696e707574821181821082828206647465787482066b5374696c6c20686572653f8282066474797065820664746578748282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a090b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200\na60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000091780\na20703182586035028ca2e2364d3761195c1858dc8f48b02508511ed8e6b8d49da0a5d16c6d6b8c44250321cb79d91c55f2a83c1d37584dd2f3872636f6e766572736174696f6e2e6d6f64656c5820c509a007751ed335460b8922a8ba7313eeb6912c1d1f9cede6967109247ce768\na20703182584045028ca2e2364d3761195c1858dc8f48b02508511ed8e6b8d49da0a5d16c6d6b8c44272636f6e766572736174696f6e2e6d6f64656c\na9070108a501502a83395156a623917280845d111cc5a603502a83395156a623917280845d111cc5a60401058202584a82108282820662696482020382820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a0a0b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320006178183636f757400a60150c38cc9bfe9be32cff8457bc345a7d38902502a83395156a623917280845d111cc5a603502a83395156a623917280845d111cc5a60401058202584a82108282820662696482020382820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f6964820678203232323232323232323232323232323232323232323232323232323232323232181881820850d1e75b558147897f7b4bd82b1c4d9f931819818350c38cc9bfe9be32cff8457bc345a7d3897827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200061780181a50c38cc9bfe9be32cff8457bc345a7d389\na9070108a50150ce4e269094360f9a1c8b9c74576f5b510350ce4e269094360f9a1c8b9c74576f5b510401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a0b0b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320007178183636f757400a601501b98e2416b21093f070c6cf001387f170250ce4e269094360f9a1c8b9c74576f5b510350ce4e269094360f9a1c8b9c74576f5b510401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085057c519758af6dea6f51b43d92474a1a918198183501b98e2416b21093f070c6cf001387f177827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200071780181a501b98e2416b21093f070c6cf001387f17\na9070108a5015086e1114149d7e29d8d0ac4799c66ecf1035086e1114149d7e29d8d0ac4799c66ecf104010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a0c0b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c\na80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320008178183636f757400a601506da88fb766bd96c99f41468aaf1c92ae025086e1114149d7e29d8d0ac4799c66ecf1035086e1114149d7e29d8d0ac4799c66ecf104010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085054bc77b81493d7958d6db5b269cbf4ea18198183506da88fb766bd96c99f41468aaf1c92ae7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000\na707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200081780181a506da88fb766bd96c99f41468aaf1c92ae\nseal 29b0c9ff02226074604d3b86f86f535d81d91d9e5edd1b6c857cecf45fdb0181\n```\n\n</details>\n\n## Carry forward\n\nPrevious: [Sensor alarm](/examples/05-sensor-alarm.md). You now have the pieces to\nisolate an agent conversation: typed Contracts, instance-owned state, a\nresident resource, explicit shutdown, and a controlled external world. Try\nthe standalone browser client above, or the smaller resident primer to add\nyour own typed adapter. Model-specific\nusage evidence belongs at that adapter boundary, not in a protocol hidden\ninside Process. The HTTP variant above shows the typed boundary and retains\nthe quantities declared by its response schema.\n\nNext: [Countdown](/examples/07-countdown.md), where a decreasing measure proves that\nauthored recurrence finishes.\n\n## Limits\n\nThis is a trusted **local** bridge, not a public authenticated AI service.\nA real client owns handshake sequencing, request ids, approvals and the\nread-only tool policy. The teaching page requests read-only execution; that\nis not an authentication boundary or permission to expose it publicly.\n`behavior = probabilistic` describes\nthe external boundary; the Lab remains deterministic. Tests compose real\nsockets with harmless shell children, not a model or a credential.\n\nProcess has no `secret()` binding. An installed Codex can use its existing\nlocal authentication; do not transmit credentials through this gateway.\nUnannotated protocol payloads remain visible in the in-memory journal.\nNo token count or cost is invented from missing usage, message counts or\nSession writes. The HTTP adapter targets OpenAI Responses.\nIts [projected profile](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/docs/architecture/openai-responses-hydration.md)\nis qualified locally, including original samples from a held Retry attempt\non an inert test endpoint. This does not authorize retrying model inference.\n`secret()` is bound only at the HttpClient Driver boundary; its bearer is not\nrecorded or displayed. That boot-dependent profile still refuses diagnostic\nrecording, rather than persisting deployment secrets or inventing replay inputs.\n\nDisconnecting a socket is not the same as canceling an agent turn. The idle\nlifetime bounds abandoned conversations but does not restore child memory\nafter restart. Details and the exact test commands live in the\n[composition evidence](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/docs/architecture/agent-gateway-showcase.md).\n\nThe service mock responds to inputs with frames and an optional terminal.\nUnsolicited/delayed scripted frames, system-close acknowledgements and `now()`\nin Session mocks remain named limits. The deployment journal is not durable.\n"},{"path":"/guide/06-instances-state-and-time","title":"Instances, state and time","description":"Choose the owner of state, separate instance keys from lifetimes, and make closure and bounded waiting explicit.","text":"---\ntitle: Instances, state and time\ndescription: Choose the owner of state, separate instance keys from lifetimes,\n  and make closure and bounded waiting explicit.\nurl: https://docs.rastok.com/guide/06-instances-state-and-time\nsource_revision: v0.2.0-alpha\n---\n\n# Instances, state and time\n\nAfter this chapter you can choose an instance key, distinguish immutable\nvalues from private mutable state, and explain when a lifetime or a bounded\njoin produces work. The central question is ownership: which tenant or sensor\ndoes this arrival belong to, and which live instance may consume it?\n\n## Select an instance\n\nIn `examples/keyed-retry.rkg`, lines 19–21, the App declares three independent\npolicies:\n\n```rkg\ninstance = { key = data.tenant }\nlifetime = { kind = idle; max = duration(\"10s\") }\nclosing = { drain_for = duration(\"1s\"); settle_for = duration(\"1s\") }\n```\n\nThe key selects Alice's or Bob's instance before delivery. An unkeyed child\nis a singleton within its parent, not across tenants. An Operator owns state\nand mailboxes; a Connector owns exchanges. A nested Graph types its key from\nits declared input, even before a Connector that accepts `variant`.\nKeys do not create threads: the [Worker](/reference/execution.md) runs\ntransactions sequentially while external Calls can remain open.\n\nTry a resident Process with `rastok run examples/agent-dialogue.rkg`\nand `cat` on PATH. Type a line and read its echo on `out`. The next line\nuses the same local session; Ctrl-C stops it.\n\nThe key reads the entering envelope and permitted enclosing immutable\nvalues. Its type must be valid on every admitting input. Changing the payload (DATA) later\ndoes not move the current instance. When an address closes and later opens\nagain, a new generation separates its clean state from old deliveries and\ndeadlines. The journal records that exact destination generation.\n\n## Values and mutable state\n\nA handler-local `val` lasts one transaction. A Node-level `val` can read\nthat owner's `instance.key`, as can its handlers (including `on stop`) and\ninstance-bound settings. A Graph can pass its key to children through a\nnamed `val`; the children never inherit `instance.key`.\n\nA `var` belongs to one Operator instance. In `examples/sensor-alarm.rkg`,\nlines 19–21, each sensor keeps its own alarm state, even across a silent period:\n\n```rkg\ninstance = { key = data.sensor }\nlifetime = { kind = persistent }\nvar tripped: bool = false\n```\n\nPump-a can be tripped while pump-b is normal. The state change and emission\ncommit together in the owning Operator transaction. Another Operator cannot\nread that cell by name; shared mutable behavior needs an explicit Operator\nwith typed inputs and outputs. See [`docs/spec/instances.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md) §§3–5.\n\n## Choose a lifetime\n\nIf you declare a key, you must also declare a lifetime. The key says which\ninstance receives a delivery; the lifetime says when that instance closes.\nWithout a key, omitting the lifetime still gives a persistent singleton.\nThe attribute has the shape\n`lifetime = { kind = ... }`, with a positive `max` duration where required.\n\n| Kind | Meaning and additional field |\n|---|---|\n| `persistent` | No lifetime deadline |\n| `idle` | Close after admission silence, with `max = duration(\"10s\")` |\n| `age` | Close at a fixed age from the creating admission, using `max` |\n| `once` | Admit one entering envelope into a generation, then request Closing |\n| `slot` | Select the epoch-aligned processing-time box at admission, with `max = duration(\"5m\")` |\n\nTraffic refreshes an idle deadline, not an age deadline. An open Call alone is\nnot admission activity. Slot boundaries are independent of boot time;\nthe run's recorded start timestamp maps them onto the logical timeline.\n\n## Close with explicit budgets\n\nClosing drains admitted work, then settles canceled Calls. Both durations\nare positive. Confirmed outcomes keep their typed exits; unconfirmed ones\nbecome `OutcomeUnknown` at the settlement deadline.\n\nA finite owner needs this policy when it is an outbound Connector or owns\none in its subtree. The rule includes the root App. Children close\nbefore their parent, and later arrivals wait for a successor generation.\nClosure is neither a rollback nor permission to drop the old generation's\noutcomes. The full sequence is in [`docs/spec/instances.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md) §7.1.\n\n## Bound a wait, then advance time\n\n`examples/sensor-alarm.rkg`, lines 34–44, correlates within the sensor instance:\n\n```rkg\noperator watchdog {\n  input probe: Sensor\n  input heartbeat: Sensor\n  output out: string\n  output expired: MissedHeartbeat\n  instance = { key = data.sensor }\n  lifetime = { kind = persistent }\n  on (probe, heartbeat) within duration(\"5m\") {\n    out = probe.data.sensor\n  }\n}\n```\n\n`within` bounds how long each candidate waits; `last N` instead bounds the\nnumber retained per input. A bounded join must declare and wire `JoinExpired`\non its `expired` output, even if the intended scenario always supplies both\ninputs. Deliberate `-> nothing` is a destination; silence is not.\n\nAfter a pair fires, the watchdog has no candidate or state to keep, but its\nsensor instance stays open for the next pair. Check reports this as\n[`W-EMPTY-INSTANCE`](/reference/diagnostics.md#instance-warnings).\nIf the instance is finished instead, write `stop` on that branch.\n\nThe Lab's `advance` visits due deadlines without sleeping. A partial join\ncan be waiting while no work is runnable. `now()` observes the transaction's\ncivil timestamp, derived from origin plus logical time; it does not trigger\na handler. See [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §§5, 7 and 8.\n\n## Summary\n\nKeys select owners, `var` stores private state, and lifetimes determine when\ninstances close. Joins bound retained candidates; the Lab advances their\ndeadlines explicitly. Sliding/event-time windows and durable recovery are\noutside the [current alpha scope](/index.md#what-is-available-today).\n\n## Next\n\nContinue with [Loops and retries](/guide/07-loops-and-retries.md), then compare [Two tenants](/examples/03-two-tenants.md)\nand [Sensor alarm](/examples/05-sensor-alarm.md). Explain which instance owns\neach pending Call or unmatched probe before running the scenario.\n"},{"path":"/reference/connectors/websocket-server","title":"WebSocketServer","description":"Ports, terminal outcomes, settings and qualification evidence for the WebSocketServer connector.","text":"---\ntitle: WebSocketServer\ndescription: Ports, terminal outcomes, settings and qualification evidence for\n  the WebSocketServer connector.\nurl: https://docs.rastok.com/reference/connectors/websocket-server\nsource_revision: v0.2.0-alpha\n---\n\n# WebSocketServer\n\n`std/websocket-server@1`. Accepts peer Sessions. Replies follow session lineage or an explicit `correlate`. A pre-admission handshake refusal creates no Session or exit.\n\n## Declaration\n\nThis declaration comes from `examples/agent-gateway.rkg`. Place the Connector in a Graph\nand wire its ports; the excerpt alone is not an App.\n\n```rkg\nconnector clients : WebSocketServer {\n  listen = \"127.0.0.1:8443\"\n  path = \"/agent\"\n  codec = json\n  handshake_timeout = duration(\"5s\")\n  max_message = \"1MiB\"\n  correlate = meta.ext.session_id\n  versions = [\"http/1.1\"]\n}\n```\n\nThe [contract index](/reference/contracts.md) explains shared settings, build features\nand the distinction between a Contract, a Lab model and an installed Driver.\n\nSee [instance ownership and bounded admission](/reference/execution.md#instances-own-state-not-threads); this Contract uses Sessions, not the outbound Call queue rule.\n\n| Mode | Driver direction | Exchange | Lab model | Installed in this binary |\n|---|---|---|---|---|\n| No selector | inbound+outbound | session | `lab-websocket` | Not compiled |\n\n## Ports and completion\n\n| Mode | Port | Direction | Type rule |\n|---|---|---|---|\n| all | `in` | input | `codec = bytes` → `array<byte>`; `codec = json` → `variant`; `codec = string` → `string` |\n| all | `out` | output | Same as `in` |\n| all | `exit` | output | WebSocketExit, below |\n\n| Mode | Output cardinality |\n|---|---|\n| all | Zero or more frames and writes; exactly one `exit` per Session |\n\n## Exit union\n\n| Case | Payload | Call visibility |\n|---|---|---|\n| `Closed` | `{ code: int, reason: string }` | Not an outbound Call |\n| `ConnectFailed` | Empty | Not an outbound Call |\n| `DecodeFailed` | Empty | Not an outbound Call |\n| `DnsFailed` | Empty | Not an outbound Call |\n| `HandshakeRejected` | `{ status: int }` | Not an outbound Call |\n| `MessageTooLarge` | `{ limit: ulong }` | Not an outbound Call |\n| `OutcomeUnknown` | Empty | Not an outbound Call |\n| `ProtocolFailed` | Empty | Not an outbound Call |\n| `TimeoutExpired` | Empty | Not an outbound Call |\n| `TlsFailed` | Empty | Not an outbound Call |\n| `TransportLost` | Empty | Not an outbound Call |\n\n## Settings\n\nWith `codec = json`, `rastok check` refuses a producer whose resolved type\ncontains a [value without a JSON form](/reference/types.md#json-request-values), using\n`E-TYPE-INVALID`. A `variant` producer is checked at execution instead: an\nunencodable message ends the Session with `DecodeFailed` before it is sent.\n\n| Mode | Setting | Domain | Presence / default | Latest phase |\n|---|---|---|---|---|\n| all | `allowed_origins` | `array<string>` | optional | instance |\n| all | `auth_bearer` | `string` | optional | instance |\n| all | `behavior` | `deterministic` | `deterministic` | plan |\n| all | `codec` | `bytes \\| json \\| string` | required | plan |\n| all | `correlate` | `string` | optional | invocation |\n| all | `handshake_timeout` | `duration` | required | instance |\n| all | `headers` | `HTTP headers` | optional | instance |\n| all | `custom_headers` | `map<string,array<string>>` | optional | instance |\n| all | `listen` | `string` | required | instance |\n| all | `max_message` | `ByteSize` | `\"8MiB\"` | plan |\n| all | `path` | `string` | `\"/\"` | plan |\n| all | `subprotocols` | `array<string>` | optional | instance |\n| all | `tls_certificate` | `array<byte>` | optional | instance |\n| all | `tls_private_key` | `array<byte>` | optional | instance |\n| all | `versions` | `array<http/1.1 \\| http/2 \\| http/3>` | `[\"http/3\", \"http/2\", \"http/1.1\"]` | plan |\n| all | `zero_rtt` | `disabled` | `disabled` | plan |\n\nThe Lab has an effectless Session binding, but authored WebSocket Session\nmocks are not executable. `rastok check` refuses a `mock` on this Connector\nwith `E-CHECK-DEFERRED`; a declaration without a mock still checks. Driver\ntests cover Session opening, frames and terminal outcomes separately from a\nphysical listener, authentication or wire handshake. Explicit correlation\nnever chooses another Connector's Session.\n\n## Qualification inventory\n\nNo dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/websocket.rs`.\n"},{"path":"/reference/diagnostics","title":"Diagnostics","description":"Compiler error codes, their trigger, the source change to make, and message excerpts from exercised refusals.","text":"---\ntitle: Diagnostics\ndescription: Compiler error codes, their trigger, the source change to make, and\n  message excerpts from exercised refusals.\nurl: https://docs.rastok.com/reference/diagnostics\nsource_revision: v0.2.0-alpha\n---\n\n# Diagnostics\n\nA graph that leaves a possible outcome with nowhere to go does not compile.\n`E-UNWIRED-OUTPUT` enforces that rule, including outputs that carry a fault.\nCodes starting with `W-`, including `W-JOIN-UNPAIRED`, are warnings,\nnot refusals.\n\nCodes identify refusals; messages explain the particular source location.\nThe code and structured fields are stable, while message wording can change.\nThe examples below are excerpts collected from compiler runs on test inputs\nor from the internal-plan diagnostic regression.\n\n`check`, `simulate` and `run` all compile source first. A Parse or Check\nerror therefore appears before simulation or physical I/O starts. The CLI\nprints a source span and, where relevant, the expected and found values.\nSee [Command line](/guide/09-command-line.md) for exit status and invocation.\n\n## Parse\n\nLexing and parsing report malformed source, unavailable syntax and excessive\ndecision nesting.\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `E-DISPATCH-DEPTH` | Nested decisions exceed the Dispatch bound; also checked after parsing. | Split the decision into Operators instead of adding nesting. | “nested `match` decisions exceed the Dispatch depth budget” |\n| `E-JSON-VALUE` | A json! literal is not valid JSON. | Correct the JSON inside the literal. | “the JSON value does not read: unexpected `?`” |\n| `E-LEX-CHAR` | Character outside the source grammar. | Remove or quote the character. | “the character `-` is not part of the grammar” |\n| `E-LEX-UNTERMINATED-BLOCK` | Raw frontend block has unmatched delimiters. | Balance its braces and embedded strings. | “this raw block never closes” |\n| `E-LEX-UNTERMINATED-COMMENT` | Block comment reaches end of file. | Close the comment. | “this block comment never closes” |\n| `E-LEX-UNTERMINATED-STRING` | String reaches a line ending without its closing quote. | Close the string or use the appropriate multiline frontend. | “this string never closes before the end of the line” |\n| `E-PARSE-DEFERRED` | The parser recognizes a construct that this build does not implement. | Use the executable subset or omit that construct. | “an experiment syntax is not implemented by this build yet” |\n| `E-PARSE-EXPECTED` | A token cannot continue the current production. | Follow the expected token or statement shown at the source span. | “expected `{`, found `lab`” |\n\n## Check\n\nName resolution is included here because it happens before a plan exists.\nIts structured phase is `resolve`; the remaining rows have phase `check`.\nIndependent plan validation can also surface these semantic refusals.\n\n### Names and declarations\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `E-APP-COUNT` | The compilation unit has zero or several App roots. | Keep exactly one graph annotated App. | “a deployed unit needs exactly one `: App` graph, found 0” |\n| `E-DUP-LAB-IDENTITY` | Simulation, scenario, mock or origin declarations conflict. | Remove the repeated declaration or distinguish its name. | “the scenario `same` is already declared at this level” |\n| `E-DUP-NODE` | Two children share a name in one Graph. | Give each child its own name. | “the node name `o` is already declared in this graph” |\n| `E-DUP-TYPE` | Two type declarations share a name. | Keep one definition for that name. | “the type `T` is already declared” |\n| `E-LAB-DUP` | More than one logical Lab name is declared. | Keep one Lab name; use simulation groups for different mock worlds. | “a unit has one logical Lab; use simulations for different mock worlds” |\n| `E-NAME-CLASH` | A child and a Graph port share a name. | Rename one declaration. | “`work` already names a Graph port; ports and children share one namespace” |\n| `E-NAME-RESERVED` | A declaration uses a reserved name, including a standard type or annotation. | Choose another name; use standard types without redeclaring them. | “`nothing` is a reserved word” |\n| `E-RESOLVE-UNKNOWN` | A referenced name has no declaration in scope. | Declare the name or correct its spelling. | “`ghost` names neither a Graph port nor a child Node in this Graph” |\n| `E-SIM-TARGET` | A simulation targets something other than the unit's App. | Omit the target or name the complete App boundary. | “a simulation closes the unit's App; sub-graph targets are a deferred capability” |\n\n### Types, wiring and execution rules\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `E-ASSET` | A build-time asset cannot be read within its root and size limits. | Correct the literal path, placement or asset size. | “this compilation has no asset root” |\n| `E-BRACE-MIXED` | A braced value mixes data members with envelope roots. | Place ordinary members inside data. | “this braced value mixes data fields with reserved envelope roots; wrap the data in `data = { … }`” |\n| `E-CHECK-DEFERRED` | A parsed construct has no executable lowering in this build. | Use a supported value or construct; also reported during Plan. | “a WebSocket Session mock is outside the executable subset of this build” |\n| `E-CONNECTOR-HANDLER` | A Connector contains a DSL handler. | Put application decisions in an Operator; the Driver implements the Contract. | “a Connector cannot own DSL handlers; its Contract and Driver events define its transitions” |\n| `E-CONNECTOR-STATE` | A Connector declares application-owned mutable state. | Keep that state in an Operator. | “a Connector's semantic state is defined by its Contract; author private `var` state in an Operator” |\n| `E-CONNECTOR-UNAVAILABLE` | The compiler has no executable definition for that Contract. | Choose a Contract and mode listed by rastok connectors. | “`Timer` is declared in the catalogue; its Driver is not in this build” |\n| `E-CONTENT-TYPE` | A content-type qualifier appears inside a nested value. | Apply it to the whole payload instead. | “a content type qualifies the WHOLE payload” |\n| `E-CONTRACT-ATTR` | A Connector attribute violates its mode's definition. | Use an allowed value and evaluation site from the Contract catalogue. | “`codec` violates the Process sheet: expected one of [\"bytes\", \"jsonl\", \"lines\"], got `utf16`” |\n| `E-CONTRACT-REQUIRED` | A required Connector setting is missing, or a Call mock's frames contradict its terminal. | Declare the setting, or match the response status: a 204 or 205 has no body. | “a 204 response has no body; remove `out` from this branch” |\n| `E-HANDLER-MISSING` | A route delivers to an Operator input that no handler consumes. | Route to an input handled by `on` or a join, or add its handler. A bare destination means `in`. | “`receiver.in` receives deliveries but `receiver` has no handler for `in`” |\n| `E-DATA-ANNOTATION` | A field annotation cannot be resolved or applied consistently. | Correct its name, constant arguments, target or measurement unit. | “unknown data annotation” |\n| `E-DISPATCH-POSITION` | A decision or guard occurs after work or in a conflicting position. | Place the decision first and combine duplicate guards. | “a handler admits at most one `where`; combine predicates or use one `match` dispatch” |\n| `E-DUP-BINDING` | A binding shadows a name already visible in its scope. | Rename the new binding. | “`limit` shadows an already visible binding” |\n| `E-DUP-KEY` | Two literal map keys canonicalize to the same value. | Keep a single entry for each canonical key. | “the map key `a` is already present” |\n| `E-EXPR` | An expression is invalid, unbound or outside the supported expression subset. | Correct the expression at the reported span. | “`mystery` is not a visible name” |\n| `E-EXTENSION-CONFLICT` | Extensions make incompatible demands on one owner. | Separate the owners, for example a Retry Connector inside a Loop Graph. | “Loop and Retry on the same owner are not admitted; put the Retry Connector inside a Loop Graph” |\n| `E-GRAPH-CYCLE` | Static wiring contains a cycle. | Keep wiring acyclic and express bounded recurrence with an Extension. | “the wiring cycles through `a`; edges form a DAG” |\n| `E-GRAPH-HANDLER` | A Graph contains application handler code. | Move the handler to an Operator child and wire it. | “a Graph cannot own application handlers; move the handler into an Operator child and wire its ports” |\n| `E-GRAPH-STATE` | A Graph declares private mutable state. | Move the state and transitions to an Operator. | “a Graph is a scope and cannot declare private `var` state; move the state and its handlers into an Operator child” |\n| `E-HANDLER-DUPLICATE` | An Operator repeats a handler for one trigger. | Combine its alternatives in one match. | “an Operator has exactly one handler for each trigger; put the alternatives in one `match`” |\n| `E-INSTANCE` | Instance keys, lifetime or closing settings do not satisfy their contract. | Correct the reported setting and supply bounded closing where required. | “closable owner `shell` contains outbound Connector `shell` and therefore requires `closing = { drain_for = <duration>; settle_for = <duration> }`” |\n| `E-INSTANCE-COMMAND` | An instance closure command is used in an invalid routing position. | Use it only as a permitted final destination in its owning context. | “an instance closure command is a destination, never a source port or an intermediate endpoint” |\n| `E-LIFETIME-REQUIRED` | A Graph, Operator or Connector has a key but no authored lifetime. | Choose when its instances close, or write `lifetime = { kind = persistent }` to retain them. | “`decide` declares `instance.key` and no `lifetime`” |\n| `E-LOOP` | A Loop setting or finitude condition is invalid. | Supply a positive fuel bound or a provably decreasing measure. | “a `+ Loop` Executor requires positive `Loop.fuel` or a `Loop.measure` that can be proved finite” |\n| `E-LOOP-CARDINALITY` | Repeated frames could produce several verdicts for one application. | Derive the verdict from a once-per-application terminal. | “this Contract may produce several frames on the port; a Loop application needs exactly one verdict” |\n| `E-LOOP-CONTROL` | The checker cannot prove one verdict for every application path. | Follow the marked arm: declare its terminal output or select one verdict, not both. Call-hosted Loops also require finite timeouts. | “this arm of Loop `count` selects two verdicts: the terminal output `out` and `Loop.next`” |\n| `E-LOOP-ENTRY` | No unique recurrent input can be selected. | Declare the input and Loop.entry consistently. | “Loop needs one recurrent Graph input; declare `Loop.entry = <input>`” |\n| `E-LOOP-HOST` | The host cannot provide a finite Loop application. | Use an Operator, admissible Graph or finite outbound Call. | “Loop requires an Operator or a resolved outbound Call Contract with closed frame and terminal guarantees” |\n| `E-LOOP-TERMINAL` | The selected terminal ports are ambiguous or incompatible. | Correct the host terminal declaration; Call terminals come from their Contract. | “every `Loop.terminal` item must name one output port” |\n| `E-MATCH-DUPLICATE` | One source has more than one closed route match. | Combine them into one route match. | “a source may have at most one closed route `match`” |\n| `E-MATCH-NONEXHAUSTIVE` | A possible case has no arm, or an ordered match lacks a fallback. | Cover the remaining cases or add the required fallback. | “an open match requires a final `_` fallback” |\n| `E-MATCH-NOT-CLOSED` | A closed match scrutinizes an open or unsupported type. | Match a closed union, enum or bool, or use ordered predicates. | “route `match` requires a pinned tagged union, enum, or bool source” |\n| `E-MATCH-OVERLAP` | Two closed match arms cover the same case. | Assign each case to one arm. | “route case `true` appears in two arms” |\n| `E-META-PREFIX` | One application metadata key is a prefix of another. | Choose keys that are consistently leaves. | “`meta.app.audit` is a leaf and `meta.app.audit.origin` makes it a branch” |\n| `E-META-SYS-READONLY` | A write targets metadata owned by execution. | Write application metadata under meta.app instead. | “meta.sys is read-only and runtime-owned; it is never an lvalue” |\n| `E-META-TYPE` | Writes to one application metadata field disagree on its type. | Use one type or separate fields. | “`meta.app.x` is written as int and as string: one field, one type” |\n| `E-META-ZONE` | The field is not in the zone's vocabulary, or an incoming route does not write the required application field. | Use a declared leaf. Write it on the named route, or use `meta.app.?field` to handle its absence. | “a metadata zone is not a value” |\n| `E-MULTI-EMIT-ARITY` | The output tuple and value tuple have different lengths. | Provide one value per output or use broadcast syntax. | “this atomic multi-emission has 3 targets but 2 tuple values” |\n| `E-MULTI-EMIT-DUPLICATE` | An atomic emission lists the same output twice. | Name each output once. | “output `left` appears twice in one atomic multi-emission” |\n| `E-NODE-ANNOTATION` | A Node's Contract and Extension annotation is invalid. | Declare the Contract and compatible Extensions in the required order. | “a Connector requires its exact Contract first, before every Extension” |\n| `E-PORT-CONFLICT` | A port is redeclared or inferred with incompatible roles. | Give the port one declaration and direction. | “`in` is already an input port of the graph; it cannot also be an output” |\n| `E-PORT-DIRECTION` | A port is used as a source, destination or emission against its direction. | Reverse the wiring or select the appropriate port. | “`chan` is an input port; an emission targets an output port” |\n| `E-PORT-TYPE` | A destination cannot accept the inferred value. | Match the named types and their differing fields, or narrow the value without an implicit lossy conversion. | “this route connects `Draft` to `Review`; pinned ends must agree: `Review` has no field `hash`, and `Draft` has no field `reviewer`” |\n| `E-PORT-UNKNOWN` | A Node has no port with the referenced name. | Use a declared port from that Node or Contract. | “`o` exposes no port named `mystery`” |\n| `E-RETRY` | A Retry setting is missing, repeated, misplaced or invalid. | Supply the required policy with positive bounds and valid settings. | “`Retry.attempts` must be a positive integer, first attempt included” |\n| `E-RETRY-CASES` | Retry.on does not select distinct declared terminal cases. | Use case names from the Contract's exit union, once each. | “`SpawnFailed` appears twice in Retry.on” |\n| `E-RETRY-EFFECT` | A selected retry case requires a repetition guarantee that is absent. | Select a before_effect case or declare a justified idempotence guarantee. | “Retry after `TimeoutExpired` (outcome_unknown) requires idempotent = true” |\n| `E-RETRY-HOST` | Retry is attached to something other than a supported outbound Call. | Put the policy on the outbound Call Connector. | “Retry requires an outbound Call Connector” |\n| `E-ROUTE-DUPLICATE` | Routing selects the same destination twice for one case. | Remove the duplicate route, including equivalent shorthand. | “destination `sink.in` is selected twice for the same source case” |\n| `E-ROUTE-MIXED` | One case is routed both to nothing and to a destination. | Choose discard or delivery for that case. | “`nothing` cannot coexist with a real destination for the same source case” |\n| `E-TYPE-BUDGET` | Type expansion exceeds a nesting, node, width or alias bound. | Reduce the dimension reported in the diagnostic. | “the type `Deep` nests 129 levels deep” |\n| `E-TYPE-DUP` | A field or symbol is repeated inside one type. | Remove or rename the duplicate member. | “the struct field `x` is declared twice” |\n| `E-TYPE-INVALID` | A type constructor violates its invariants, or a JSON input receives a known type without a JSON form. | Correct the type, or explicitly convert the named field before sending it. | “array&lt;int&gt; is not a canonical map-key type” |\n| `E-TYPE-RECURSIVE` | A named type expands back to itself. | Use a finite nonrecursive type. | “the type `Node` does not expand: `Node` reaches itself” |\n| `E-TYPE-UNRESOLVED` | An inference constraint reaches a position needing a closed type. | Supply a concrete type or enough contextual constraints. | “an open struct is an inference constraint, not an effective type” |\n| `E-UNION-OVERLAP` | Structural-union branches overlap in the values they accept. | Use disjoint branches or a tagged union. | “structural-union branches `int` and `long` overlap” |\n| `E-UNWIRED-OUTPUT` | A possible output or case has no explicit disposition. | Wire it to a destination or deliberately discard it with nothing. | “`o.side` can be produced but has no destination; route it or write `o.side -> nothing`” |\n| `E-WIRING-MIGRATION` | Wiring uses a removed spelling or continues after a command. | Use current port paths, match routing and final command destinations. | “edge `when` was removed; route a closed value with `-> match { ... }` or decide in an Operator” |\n\n### Instance warnings\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `W-EMPTY-INSTANCE` | A keyed `persistent` Operator can take a branch from its initial state that writes no state and does not stop. A join is checked when it fires. Without a deadline, the empty instance never closes on its own. | Give the instance a delay with `idle`, `age`, or `slot`. Use `stop` only if that branch ends its work. | “`dossier` can open an instance that retains nothing on `note`” |\n\n### Lost-answer warnings\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `W-MATCH-CATCHALL` | A wildcard on a finite outbound Call's terminal, or in the first handler receiving it, accepts a lost-answer case that no arm names. | Name each listed case, grouped or separately, even when its destination stays the same. | “the answer may have been lost while the operation succeeded” |\n\nThe warning points to the written `_`. The `source` field names the terminal,\n`owner` names the Connector or receiving Operator, and `case` lists the\nunnamed cases. Check still succeeds. See [When the answer is lost](/guide/10-when-the-answer-is-lost.md).\n\n### Join warnings\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `W-JOIN-UNPAIRED` | A presence join receives frames and a terminal from one Call, but their counts do not pair for every terminal case. | Route every terminal accompanying a frame to the join, or key its Operator by the Call and bound the join with `within` or `last`. | “`ServerError` delivers 1 to `pair.body`, 0 to `pair.exit`; a lone delivery can pair with another Call” |\n\nThe fields name the joining `node`, the source `connector`, its frame\n`port` and the terminal `case`. For a zero-or-more frame port, `case = \"all\"`\nmeans the warning is independent of one terminal case, not that every run\nfails. A bound without an instance key does not separate Calls. The warning\ndoes not change execution or make a failed scenario pass.\n\n## Plan\n\n`E-PLAN-DEPTH` also occurs at Check when an expression exceeds its\n128-level bound, measured on the resolved tree with compiler-added\nconversions included. Plan checks the combined serialized representation against\nthe reader's separate 256-level bound, with the root at level zero.\n\n| Code | When it fires | What the author changes | Example message excerpt |\n|---|---|---|---|\n| `E-INTERNAL-PLAN` | Compiler output fails independent plan validation. | Report the source and diagnostic as a compiler defect. | “the lowering emitted an invalid plan” |\n| `E-PLAN-DEPTH` | The complete serialized plan exceeds the reader's bound; expressions also have a smaller Check bound. | Reduce combined nesting; the message identifies the boundary. | “the serialized plan reaches level 256; the format requires a level below 256 (root is level 0)” |\n\nThe internal-plan case is a compiler defect, not an invitation to weaken a\ntype or discard an outcome. Its message is exercised by\n`compiler::tests::the_internal_plan_diagnostic_carries_its_registered_payload`.\n\n## Simulate\n\nThe current runner reports failed scenarios, missing observations and golden\ndifferences as scenario results, not as additional structured `E-…` codes.\nFor a golden mismatch it names the scenario, record, expected and obtained\nvalues, and cause. Correct the graph or the scenario; save a new trace only\nafter reviewing the intended change.\nSee [The Lab](/reference/lab.md#golden-traces) and\n[Echo](/examples/01-echo.md#read-the-golden-difference).\n\nA `TimeoutExpired`, `JoinExpired` or `LoopExpired` value is a typed\noutcome that the graph routes. It is not a compiler diagnostic.\n\n## Run\n\nDeployment refusals, unavailable physical Drivers and recording/replay\nerrors currently use contextual command errors, without a separate registry\nof emitted `E-…` codes. Use the reported Connector path, missing binding or\nformat mismatch to correct the deployment or select the matching artifact.\nCommand usage errors go to stderr with status 2; compilation and execution\nerrors return a nonzero status.\nSee [Command line](/guide/09-command-line.md).\n\n## Specified, not shipped\n\nSource registry: [`docs/spec/diagnostics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/diagnostics.md), “Registry”.\n\n| Code | Status in this build | Specification |\n|---|---|---|\n| `E-SAGA-DURABILITY` | Saga durability checking is a deferred tool surface. | [`docs/spec/diagnostics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/diagnostics.md), Registry |\n| `E-COMPENSATE-KEY` | Compensation-key checking is deferred with Saga. | [`docs/spec/diagnostics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/diagnostics.md), Registry |\n| `E-REPLAY-VERSION-MISMATCH` | Replay checks compatibility, but does not emit this structured code. | [`docs/spec/identity.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/identity.md) |\n| `E-LOOP-CONTEXT` | The name occurs in an execution refusal, not a structured compiler diagnostic. | [`docs/spec/loop.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/loop.md) |\n| `E-DUP-EDGE` | Superseded by `E-ROUTE-DUPLICATE`; the route check reports duplicate destinations. This code is not emitted. | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) |\n"},{"path":"/examples/07-countdown","title":"Countdown: a bounded loop","description":"Prove that a countdown terminates, follow its manager commands, and see the checker reject a measure that cannot prove progress.","text":"---\ntitle: \"Countdown: a bounded loop\"\ndescription: Prove that a countdown terminates, follow its manager commands, and\n  see the checker reject a measure that cannot prove progress.\nurl: https://docs.rastok.com/examples/07-countdown\nsource_revision: v0.2.0-alpha\n---\n\n# Countdown: a bounded loop\n\nThis program counts down from an integer and emits one final message.\n\nA conversation keeps a resource alive until closure. A countdown asks the\nopposite question: can the program prove that repeated work will finish?\nThe answer is written beside the Operator, without a backwards graph edge.\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root, with `rastok` installed:\n\n```sh\nrastok simulate examples/countdown.rkg --compare examples/traces/countdown\n```\n\n```text\nPASS proof.positive\nPASS proof.already_finished\n2 scenario(s), 0 failed\n```\n\nAdd `--ui` to inspect each admitted application and its manager transition.\n\n```sh\nrastok simulate examples/countdown.rkg --compare examples/traces/countdown --ui\n```\n\nThis requires `hosted-ui`. Open the private loopback URL printed by the CLI.\n\nFor the controls and source view, see [the debugger tour](/debugger.md).\n\n## Read the program\n\nThe App wires `in -> count -> out`. Inside `count`, a positive integer produces\n`Loop.next = data - 1`; otherwise the Operator emits `liftoff`. `Loop.next`\nis a command to the Loop manager, not a port or a graph edge. The manager\nrecords the command and admits the next application after the previous one\nhas finished.\n\n`Loop.state` is the envelope admitted for the current application.\n`Loop.measure = Loop.state.data` selects its integer DATA as the decreasing\nquantity. The positivity guard and subtraction by one provide the proof.\nThe terminal `out` supplies the final Done verdict.\n\nThis example needs no exhaustion output because its measure proves termination.\nWith an explicit fuel bound, possible exhaustion instead produces\n`LoopExpired { last_state: EntryType }` on the host's declared terminal,\nnormally `err` for an Operator or `exit` for a Call. It must have a destination.\nLoop never adds a synthetic expiry port. See [`docs/spec/loop.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/loop.md) §§8 and 10.\n\nThere is no Connector in this program. The [Lab reference](/reference/lab.md)\nexplains expectations and observation windows; `advance` supplies virtual time.\n\n<a id=\"graph\"></a>\n\nSource: `examples/countdown.rkg`\n\n```rkg\n// A passive App wires one finite Operator application. The measure proves\n// termination; Loop.next is a manager command, not a spatial back-edge.\ngraph countdown : App {\n  input in: int\n  output out: string\n\n  operator count : Loop {\n    input in: int\n    output out: string\n    Loop.measure = Loop.state.data\n\n    on in match {\n      data > 0 => Loop.next = data - 1\n      _        => out = \"liftoff\"\n    }\n  }\n\n  in -> count -> out\n}\n\nlab proof {\n  scenario positive {\n    app.in = 3\n    expect app.out == \"liftoff\"\n  }\n  scenario already_finished {\n    app.in = 0\n    expect app.out == \"liftoff\"\n  }\n}\n```\n\n## Expected result\n\n`proof.positive` admits states 3, 2, 1 and 0, then emits one `liftoff`.\n`proof.already_finished` admits 0 and emits the same result without recurrence.\nThe CLI ends with `2 scenario(s), 0 failed`.\n\nInspect the positive trace: ordinary Operator transactions produce commands;\nManager transactions, labeled `l:loop` in the trace, record its progress. Four applications and\nthree recurrences are different counts. Each application has its own causal\nidentity even when it belongs to the same run.\n\n## Break it\n\nReplace `Loop.measure = Loop.state.data` with `Loop.measure = 3`, then run:\n\n```sh\nrastok check examples/countdown.rkg\n```\n\nThe checker reports exactly:\n\n```text\nerror[E-LOOP]: this Loop cannot be proved finite: the Loop measure is outside the supported direct integer-path fragment\n  --> examples/countdown.rkg:7:3\n  |\n7 |   operator count : Loop {\n  |   ^^^^^^^^^^^^^^^^^^^^^^^\n  = detail: this Loop cannot be proved finite: the Loop measure is outside the supported direct integer-path fragment\n```\n\nRestore the measure before trying the next edit (this discards edits to the example):\n\n```sh\ngit checkout -- examples/countdown.rkg\n```\n\nFor a runtime comparison, change only the Operator's\n`out = \"liftoff\"` to `out = \"changed\"` and run the complete comparison below.\n\n```sh\nrastok simulate examples/countdown.rkg --compare examples/traces/countdown\n```\n\n```text\nFAIL proof.positive\n     expect app.out == \"liftoff\"  (countdown.rkg:24)\n     observed app.out: \"changed\"\n     expected 1 matching delivery on app.out, but observed 0\n     golden divergence: record 14: emissions(23)[0][2] . data(5)[1] (ccbor value)[1]; expected \"liftoff\"; got \"changed\"; cause: TRANSACTION \"count\" · trigger \"p:in\" · cause_id absent\nFAIL proof.already_finished\n     expect app.out == \"liftoff\"  (countdown.rkg:28)\n     observed app.out: \"changed\"\n     expected 1 matching delivery on app.out, but observed 0\n     golden divergence: record 5: emissions(23)[0][2] . data(5)[1] (ccbor value)[1]; expected \"liftoff\"; got \"changed\"; cause: TRANSACTION \"count\" · trigger \"p:in\" · cause_id absent\n2 scenario(s), 2 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/countdown.rkg\n```\n\n## Read the golden difference\n\nThe invalid measure is rejected before execution, so it creates no new trace.\nThe changed output, by contrast, changes an emission: the golden comparison\nnames the first differing record, expected and actual values, and its cause.\nThe unchanged scenario expectation also rejects the changed text. Restore the\noutput rather than saving over the reference.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/countdown/proof.positive.rkc`\n\n```rastok-trace\na6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024382020309636c61620a000b000d81826c2e696e3e636f756e742e696e8249828165636f756e748000\na7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na807021165636f756e74128249828165636f756e74800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000\na807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a50f3df1105112054d397a04ed0666ca4c81828a105818701502fcfad2f040f633a2eaa6ac52c55d15c8249828165636f756e74800082025009426b9ccc12398e2552b10d29a250f762696e04a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820203\na807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a50f3df1105112054d397a04ed0666ca4c81828a105818503502fcfad2f040f633a2eaa6ac52c55d15c005009426b9ccc12398e2552b10d29a250f7a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820203\na707021165636f756e74128249828165636f756e7480001364703a696e1481836c2e696e3e636f756e742e696e8243828080000117801828a20181502fcfad2f040f633a2eaa6ac52c55d15c03818450bce978a7369910794ccef6fd5aaee307502fcfad2f040f633a2eaa6ac52c55d15c008201a501501acf1fd1704b6331132d400037b54c3a0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820202\na807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a501acf1fd1704b6331132d400037b54c3a1828a2048150bce978a7369910794ccef6fd5aaee30705818702502fcfad2f040f633a2eaa6ac52c55d15c00010350bce978a7369910794ccef6fd5aaee307a501501acf1fd1704b6331132d400037b54c3a0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820202\na907021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181981835020946af912fea1c531b9a8c156c5c0067829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e748000181a5020946af912fea1c531b9a8c156c5c0061828a105818503502fcfad2f040f633a2eaa6ac52c55d15c015020946af912fea1c531b9a8c156c5c006a5015020946af912fea1c531b9a8c156c5c00602501acf1fd1704b6331132d400037b54c3a0350f3df1105112054d397a04ed0666ca4c8040105820243820202\na707021165636f756e74128249828165636f756e7480001364703a696e1481837829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e7480000117801828a20181502fcfad2f040f633a2eaa6ac52c55d15c03818450dc759cce07b7cd08e3c541091909eac2502fcfad2f040f633a2eaa6ac52c55d15c018201a50150af90e571f28b0c57cc303bb4639eb522025020946af912fea1c531b9a8c156c5c0060350f3df1105112054d397a04ed0666ca4c8040105820243820201\na807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a50af90e571f28b0c57cc303bb4639eb5221828a2048150dc759cce07b7cd08e3c541091909eac205818702502fcfad2f040f633a2eaa6ac52c55d15c01020250dc759cce07b7cd08e3c541091909eac2a50150af90e571f28b0c57cc303bb4639eb522025020946af912fea1c531b9a8c156c5c0060350f3df1105112054d397a04ed0666ca4c8040105820243820201\na907021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181981835001149eb903f2a42a411bd2a5c99fda297829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e748000181a5001149eb903f2a42a411bd2a5c99fda291828a105818503502fcfad2f040f633a2eaa6ac52c55d15c025001149eb903f2a42a411bd2a5c99fda29a5015001149eb903f2a42a411bd2a5c99fda290250af90e571f28b0c57cc303bb4639eb5220350f3df1105112054d397a04ed0666ca4c8040105820243820201\na707021165636f756e74128249828165636f756e7480001364703a696e1481837829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e7480000217801828a20181502fcfad2f040f633a2eaa6ac52c55d15c0381845070adccffc97318389abff806c642078f502fcfad2f040f633a2eaa6ac52c55d15c028201a501506f63ca530a3ff07e0a2e0b98b1c07fdb025001149eb903f2a42a411bd2a5c99fda290350f3df1105112054d397a04ed0666ca4c8040105820243820200\na807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a506f63ca530a3ff07e0a2e0b98b1c07fdb1828a204815070adccffc97318389abff806c642078f05818702502fcfad2f040f633a2eaa6ac52c55d15c0203015070adccffc97318389abff806c642078fa501506f63ca530a3ff07e0a2e0b98b1c07fdb025001149eb903f2a42a411bd2a5c99fda290350f3df1105112054d397a04ed0666ca4c8040105820243820200\na907021165636f756e74128249828165636f756e74800013666c3a6c6f6f70148017801819818350a08ecae7e45001287125498fcbb858fa7829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e748000181a50a08ecae7e45001287125498fcbb858fa1828a105818503502fcfad2f040f633a2eaa6ac52c55d15c0350a08ecae7e45001287125498fcbb858faa50150a08ecae7e45001287125498fcbb858fa02506f63ca530a3ff07e0a2e0b98b1c07fdb0350f3df1105112054d397a04ed0666ca4c8040105820243820200\na707021165636f756e74128249828165636f756e7480001364703a696e1481837829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e74800003178183636f757400a501507b1488260cb97cfd8331c5237d727d300250a08ecae7e45001287125498fcbb858fa0350f3df1105112054d397a04ed0666ca4c804010582024a8206676c6966746f66661828a20181502fcfad2f040f633a2eaa6ac52c55d15c0381845050b117f43155e440bad41482136d4336502fcfad2f040f633a2eaa6ac52c55d15c03820382507b1488260cb97cfd8331c5237d727d3001\na807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a507b1488260cb97cfd8331c5237d727d301828a204815050b117f43155e440bad41482136d433605818404502fcfad2f040f633a2eaa6ac52c55d15c0301\nseal 104ac3b13f441a7ad2128e83fbff1abc3e3f4aeb9f9a4505d38e4a9dc2ecfbb1\n```\n\n</details>\n\n## Carry forward\n\nPrevious: [Agent gateway](/examples/06-agent-gateway.md). Separate a resource's lifetime\nfrom a finite algorithm's progress. A Loop advances authored state; a Retry\nrepeats a prepared operation. Next: [HTTP model adapter](/examples/08-model-adapter.md),\nwhich adds typed usage evidence to an external response.\n\n## Limits\n\nThis is a pure integer countdown, with no external program or elapsed-time\nclaim. The direct proof fragment is deliberately small; unsupported proofs\nrequire a finite fuel bound and an explicit exhaustion disposition.\nThe journal remains in memory; a golden trace is comparison evidence, not\ndurable recovery.\n"},{"path":"/guide/07-loops-and-retries","title":"Loops and retries: bounded recurrence","description":"Separate authored state progression from safe repetition of one prepared Call, with explicit bounds, delays and terminal outcomes.","text":"---\ntitle: \"Loops and retries: bounded recurrence\"\ndescription: Separate authored state progression from safe repetition of one\n  prepared Call, with explicit bounds, delays and terminal outcomes.\nurl: https://docs.rastok.com/guide/07-loops-and-retries\nsource_revision: v0.2.0-alpha\n---\n\n# Loops and retries: bounded recurrence\n\nAfter this chapter you can choose Loop for state progression and Retry for\nrepeating one operation, explain their bounds, and identify the guarantee\nneeded before repeating a visible external effect. Both use a journal-owned\nmanager. Neither introduces a backwards edge into the directed acyclic graph (DAG).\n\n## Advance a state with Loop\n\nRead `examples/countdown.rkg`, lines 7–16:\n\n```rkg\noperator count : Loop {\n  input in: int\n  output out: string\n  Loop.measure = Loop.state.data\n\n  on in match {\n    data > 0 => Loop.next = data - 1\n    _        => out = \"liftoff\"\n  }\n}\n```\n\nEach application either produces a new state through `Loop.next` or ends\nthrough its terminal output. The command is recorded in the producing\ntransaction. The manager later consumes it and admits another application.\nIt is a command destination, not an output port or an edge to wire backwards.\n\n`Loop.state` is the complete envelope admitted for the current application.\nIts DATA is an integer here. `Loop.measure` selects the quantity whose strict\ndecrease proves termination: a direct integer path, a positivity guard and\nliteral subtraction are within the executable proof fragment. Input 3 needs\nfour applications, ending at 0. A constant measure is not a progress proof.\n\n`Loop.again` retains that admitted state; `Loop.done` finishes without a\nbusiness output. Every application needs exactly one verdict. A terminal\noutput such as `out` supplies Done implicitly; `nothing` only disposes an\noutput and does not itself finish a Loop application.\n\n## Bound and delay the applications\n\nAt least one of `Loop.measure` or `Loop.fuel` is required. Positive\n`Loop.fuel = N` permits at most N applications, including the first. If the\nlast application requests another, the manager emits\n`LoopExpired { last_state: EntryType }` on the existing host terminal. An\nOperator normally declares `err` for that case; a Call uses `exit`. The\nterminal must be typed and wired like every other productible outcome.\nThe measure-only countdown proves exhaustion impossible, so it needs no\nexpiry declaration.\n\n`Loop.delay = { kind = fixed; after = duration(\"1s\") }` sets a fixed delay.\nA delay may also be exponential,\nwith `kind = exponential`, `first` and `ceiling`. Durations are positive;\nthere is no jitter. The delay starts when the manager consumes the command\nafter the application has no outstanding work. No next application overlaps\nthe previous one. See [`docs/spec/loop.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/loop.md) §§7–10.\n\n## Repeat an operation with Retry\n\nThe webhook uses `examples/webhook-to-partner.rkg`, lines 91–95:\n\n```rkg\nidempotent = true\nbehavior = deterministic\nRetry.attempts = 2\nRetry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed]\nRetry.delay = { kind = fixed; after = duration(\"1s\") }\n```\n\nThe manager retains one prepared request, including evaluated settings and\nthe partner key. Attempts reuse it; invocation expressions are not evaluated\nagain. `Retry.attempts` includes the first Call. `Retry.on` is a static set\nof terminal case names, not a predicate over arbitrary response DATA.\n\nFixed delay uses `after`. Exponential delay uses `first` and `ceiling`, with\n`first <= ceiling`; after failed attempt i its delay is\n`min(first * 2^(i - 1), ceiling)`. It starts at the winning Call closure,\nnot when a delayed manager happens to run. Each attempt remains in the\njournal; only the final batch, its response frames and terminal outcome,\nis delivered downstream. Exhaustion forwards\nthe last terminal unchanged, without a new Retry error case.\n\n## Check repetition safety separately\n\nThe Contract classifies every terminal:\n\n| Class | Meaning for repetition |\n|---|---|\n| `before_effect` | The operation has not become externally visible; Retry may select it without an idempotence guarantee |\n| `outcome_unknown` | Visibility or outcome is uncertain; Retry requires `idempotent = true` |\n| `after_effect` | The operation became visible; Retry requires `idempotent = true` |\n\nThe checker enforces that rule for every selected case. A decoded HTTP 500\nis `ServerError`, an `after_effect` response, not a transport fault. The\nwebhook's real partner must honor the declared same-request guarantee; merely\nsending an idempotency key does not establish it.\n\n`behavior = deterministic | probabilistic` describes results, not repetition\nsafety. A deterministic payment can still charge twice. An inference may\nreturn different text and incur another charge, which is why the model\nadapter omits Retry. Loop proves finitude, not effect safety; its advisory\n`W-LOOP-REPEAT` is distinct from Retry's hard refusal.\n\n## Summary\n\nLoop chooses the next state; Retry keeps the same prepared operation.\nTheir bounds and delays are explicit. A Loop Graph may contain Retry Calls;\nthe enclosing application waits for them through backoff and final closure.\nCompensation belongs to the future Saga contract, not a global `effect`\nattribute. See [`docs/spec/retry.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/retry.md), [`docs/spec/effects-and-sagas.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/effects-and-sagas.md) and the\n[current alpha scope](/index.md#what-is-available-today).\n\n## Next\n\nIf a partner may have acted before its response disappeared, read\n[When the answer is lost](/guide/10-when-the-answer-is-lost.md).\n\nContinue with [Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md). Practice the distinction\nin [Countdown](/examples/07-countdown.md) and\n[Webhook to partner](/examples/04-webhook-to-partner.md): identify the\nverdict or terminal that permits each recurrence before advancing time.\n"},{"path":"/reference/stdlib","title":"Standard library","description":"Find the types, Connector Contracts, annotations and value frontends supplied with Rastok.","text":"---\ntitle: Standard library\ndescription: Find the types, Connector Contracts, annotations and value\n  frontends supplied with Rastok.\nurl: https://docs.rastok.com/reference/stdlib\nsource_revision: v0.2.0-alpha\n---\n\n# Standard library\n\nThe standard library supplies definitions that an application can use without\ncopying them into its source. A Connector Contract describes an interaction;\na Driver implements it. Selecting physical Drivers does not change the\nstandard types available to the compiler.\n\n## Types\n\nThese names are available without an import or a local declaration. Their\ndefinitions are the same logical types used by the Connector ports.\n\n| Type | Definition and cases |\n|---|---|\n| `FileExit` | [File](/reference/connectors/file.md#exit-union), read and replace |\n| `ProcessExit` | [Process](/reference/connectors/process.md#exit-union), job and service |\n| `HttpClientExit` | [HttpClient](/reference/connectors/http-client.md#exit-union) |\n| `HttpServerExit` | [HttpServer](/reference/connectors/http-server.md#exit-union), ack and respond |\n| `WebSocketExit` | [WebSocketClient](/reference/connectors/websocket-client.md#exit-union) and [WebSocketServer](/reference/connectors/websocket-server.md#exit-union) |\n\nWrite `output failed: FileExit` without a `type FileExit` declaration.\nThese names also work in aliases, fields, collections and `is`/`as`.\nFor example, `type StorageResult = FileExit` declares an application alias\nwithout creating a different type identity.\n\nRedeclaring a standard name is `E-NAME-RESERVED`. A typed destination resolves\nconstructors such as `Completed {}`; without one, constructor lookup uses\nonly unions explicitly declared in the source. The [type reference](/reference/types.md)\ncovers scalar, collection, struct and union notation and schema projections.\n\n## Connector Contracts\n\n[Connectors and contracts](/reference/contracts.md) lists File, Process, HttpClient,\nHttpServer, WebSocketClient and WebSocketServer. Each Connector page gives\nits exact Contract id, modes, ports, settings, terminal outcomes and\nqualification limits.\n\n`rastok connectors` lists the Contracts and the implementations present in\nthe current binary; `rastok connectors --json` produces the machine-readable\ncatalog. Physical networking depends on the binary's feature selection,\nnot on an import in the program.\n\n## Annotations\n\n| Annotation | Meaning |\n|---|---|\n| `@sensitive(level = ...)` | Classifies confidentiality as `Internal`, `Confidential` or `Restricted` |\n| `@personal(...)` | Classifies personal data with identifier, special and criminal flags |\n| `@secret` | Declares secret handling; clear secret-bearing executable schemas are refused |\n| `@measure(id = ..., unit = ...)` | Associates a numeric field with a measurement id and unit |\n\nThese annotations are available without imports. Their interpretation and\ncurrent limits are described in\n[Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md).\nA user annotation with the same field shape does not acquire the authority\nof a standard annotation.\n\n## Value frontends and expressions\n\nThe standard tagged frontends are `json!` for a JSON value, `string!` for\nverbatim text and `base64!` for bytes. Their syntax and restrictions are in\n[Expressions and dispatch](/reference/expressions.md#tagged-frontends). That reference\nalso lists the available operators and expression functions.\n\n## Modules and imports\n\nThere is no `import`, `use` or `using` directive in this version. Standard\ndefinitions are available implicitly. Modules, explicit imports, visibility\nand namespace rules remain a later design discussion; no syntax or delivery\ndate is decided.\n\n## Specified, not shipped\n\n| Item | Specification |\n|---|---|\n| File `watch`, Timer, Calendar and Memory | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §§3.4–3.7; see the [Contract limits](/reference/contracts.md#specified-not-shipped) |\n| Additional tagged guest-language frontends | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §§2–3; see the [expression limits](/reference/expressions.md#specified-not-shipped) |\n\nSources: [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §1.2, [`docs/spec/types.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md),\n[`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md) and the standard Contract definitions.\n"},{"path":"/examples/08-model-adapter","title":"HTTP model adapter: typed responses and token metering","description":"Select a typed view of an OpenAI Responses result, retain original token measurements by job and session, and distinguish absent usage from an observed zero.","text":"---\ntitle: \"HTTP model adapter: typed responses and token metering\"\ndescription: Select a typed view of an OpenAI Responses result, retain original\n  token measurements by job and session, and distinguish absent usage from an\n  observed zero.\nurl: https://docs.rastok.com/examples/08-model-adapter\nsource_revision: v0.2.0-alpha\n---\n\n# HTTP model adapter: typed responses and token metering\n\nThis program sends a model request and keeps the response's reported usage with its job and session.\n\nA bounded loop tells you how much work may repeat. At a model boundary,\nanother question matters: what usage did the partner actually report?\nKeep that evidence on the original typed response, without turning an absent\nfield into a zero or counting a downstream copy again.\n\nThe [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for\nthe program and Lab, `.rkc` for a reviewed scenario reference and `.rkr`\nfor a real execution recording.\n\n## Run\n\nFrom the repository root, use the synthetic fixture bindings and the checked\n[deployment profile](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/examples/agent-http.deployment.json):\n\n```sh\nRASTOK_SHOWCASE_MODEL_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_MODEL_TOKEN_VERSION=fixture-v1 rastok simulate examples/agent-http.rkg --deployment examples/agent-http.deployment.json --compare examples/traces/agent-http\n```\n\n```text\nPASS responses.two_sessions\nPASS responses.missing_usage\nPASS responses.observed_zero\nPASS responses.schema_failure\nPASS responses.transport_failure\nPASS responses.http_errors\n6 scenario(s), 0 failed\n```\n\nAdd `--ui` for the paused debugger.\n\n```sh\nRASTOK_SHOWCASE_MODEL_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_MODEL_TOKEN_VERSION=fixture-v1 rastok simulate examples/agent-http.rkg --deployment examples/agent-http.deployment.json --compare examples/traces/agent-http --ui\n```\n\nThis requires `hosted-ui`. Open the private loopback URL printed by the CLI. The Lab never contacts the profile's\nconfigured model URL. These fixture values are not credentials.\n\nFor the controls and source view, see [the debugger tour](/debugger.md).\n\n## Read the program\n\nStart with `ResponseUsage` and `ModelResponse`. The former marks the three\noriginal quantities with `@measure(id = ..., unit = \"token\")`. The latter\nis an explicit selected view of an external JSON object: response identity,\noutput, status, usage and error.\n\nThe `model` [HttpClient](/reference/connectors/http-client.md) refines its existing port with `output out: ModelResponse`.\nUnder `codec = json` and `json_profile = projected`, deserialization keeps\ndeclared members, omits additional members and turns an absent nullable\nmember into null. A member with the wrong type produces `DecodeFailed`;\nits `message` names the field and the expected type without copying the\nreceived value.\nOrdinary structs and strict JSON deserialization remain closed.\n\n`request` carries `session` and `job` into META. `explain_usage` emits an\nexplanation when usage is absent; it neither extracts nor sums measurements.\n`terminal` separates a usable 2xx response from other HTTP outcomes. One job\nmeans one non-streaming inference, not a resident conversation.\n\nThe bearer is a logical `secret(\"showcase/model/token\")` reference. Its value\nis bound at boot and supplied only at the real HttpClient Driver boundary.\n`behavior = probabilistic` describes the partner's outputs. It does not mean\nthat repeating a request is safe: there is no Retry on this inference.\n\nThe [Lab reference](/reference/lab.md) explains mock responses, expectations\nand observation windows. `advance` supplies virtual time; a mock's terminal\nresponse ends its simulated exchange, not the whole scenario.\n\n<a id=\"graph\"></a>\n\nSource: `examples/agent-http.rkg`\n\n```rkg\n// Each job makes one HTTP request and reports the usage in the model's reply.\n// The Lab scripts replies; the graph never retries a potentially billable request.\nval model_name = \"gpt-6-astra\"\nval simulated_message = json! {\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Hello from the simulated model.\",\"annotations\":[]}]}\n\ntype Job = struct { session: string, job: string, prompt: string }\ntype JsonObject = map<string, variant>\ntype ResponseUsage = struct {\n  input_tokens: ulong @measure(id = input_tokens, unit = \"token\")\n  output_tokens: ulong @measure(id = output_tokens, unit = \"token\")\n  total_tokens: ulong @measure(id = total_tokens, unit = \"token\")\n  input_tokens_details: JsonObject?\n  output_tokens_details: JsonObject?\n}\ntype ModelResponse = struct {\n  id: string\n  object: string\n  output: array<variant>\n  status: string?\n  usage: ResponseUsage?\n  error: JsonObject?\n}\ntype UnknownUsage = struct { session: string, job: string, reason: string }\n\ngraph agent_http : App {\n  input in: Job\n  output response: ModelResponse\n  output unknown: UnknownUsage\n  output failed: HttpClientExit\n  instance = { key = data.session }\n  lifetime = { kind = idle; max = duration(\"2h\") }\n  closing = { drain_for = duration(\"30s\"); settle_for = duration(\"5s\") }\n\n  operator request {\n    input in: Job\n    output out: variant\n    on in {\n      val body = { model = model_name; input = data.prompt; stream = false; store = false; max_output_tokens = 128 }\n      out = {\n        data = body as variant\n        meta.app.session = data.session\n        meta.app.job = data.job\n      }\n    }\n  }\n  connector model : HttpClient {\n    url = env(\"MODEL_URL\")\n    auth_bearer = secret(\"showcase/model/token\")\n    method = \"POST\"\n    codec = json\n    json_profile = projected\n    output out: ModelResponse\n    timeout = duration(\"10s\")\n    max_body = \"256 KiB\"\n    behavior = probabilistic\n  }\n  // Quantities already live on model.out. This Operator only explains absence;\n  // it neither extracts, copies nor totals measurements.\n  operator explain_usage {\n    input in: ModelResponse\n    output unknown: UnknownUsage\n    on in match {\n      data.usage is ResponseUsage => nothing\n      _ => unknown = { session = meta.app.session as string; job = meta.app.job as string; reason = \"usage not reported\" }\n    }\n  }\n  operator terminal {\n    input in: HttpClientExit\n    output failed: HttpClientExit\n    output unknown: UnknownUsage\n    on in match {\n      data is Completed => match {\n        data.status >= 200 && data.status < 300 => nothing\n        _ => failed = Completed { status = data.status }\n      }\n      data is ServerError => failed = ServerError { status = data.status }\n      _ => {\n        failed = .\n        unknown = { session = meta.app.session as string; job = meta.app.job as string; reason = \"no usable response\" }\n      }\n    }\n  }\n\n  in -> request -> model\n  model.out -> { response; explain_usage }\n  explain_usage.unknown -> unknown\n  // Lost answers go to the same handler, which reports the unknown usage.\n  model.exit -> match {\n    BodyTooLarge | DecodeFailed | OutcomeUnknown | ProtocolFailed | TimeoutExpired -> terminal\n    Completed | ConnectFailed | DnsFailed | ServerError | TlsFailed -> terminal\n  }\n  terminal.failed -> failed\n  terminal.unknown -> unknown\n}\n\nlab responses {\n  // Mocks supply already typed values. Wire-shape refusals are separately\n  // tested against the real HTTP decoder, not inferred from this Lab.\n  mock model {\n    on in match {\n      meta.app.job == \"missing\" || meta.app.job == \"null\" => {\n        out = { id = \"resp_without_usage\"; object = \"response\"; output = []; status = \"completed\"; usage = null; error = null }\n        exit = Completed { status = 200 }\n      }\n      meta.app.job == \"invalid\" => exit = DecodeFailed { message = \"response `out.usage.total_tokens` expects ulong; received string\" }\n      meta.app.job == \"error_body\" => exit = DecodeFailed { message = \"response `out.id` expects string; required member is missing\" }\n      meta.app.job == \"zero\" => {\n        out = { id = \"resp_zero\"; object = \"response\"; output = []; status = \"completed\"; usage = { input_tokens = 0u; output_tokens = 0u; total_tokens = 0u; input_tokens_details = null; output_tokens_details = null }; error = null }\n        exit = Completed { status = 200 }\n      }\n      meta.app.job == \"timeout\" => nothing\n      meta.app.job == \"server_error\" => {\n        out = { id = \"resp_failed\"; object = \"response\"; output = []; status = \"failed\"; usage = null; error = {\"message\": \"scripted service error\"} }\n        exit = ServerError { status = 500 }\n      }\n      _ => {\n        out = {\n          id = \"resp_fixture\"\n          object = \"response\"\n          output = [simulated_message]\n          status = \"completed\"\n          usage = { input_tokens = 12u; output_tokens = 4u; total_tokens = 16u; input_tokens_details = {\"cached_tokens\": 0}; output_tokens_details = {\"reasoning_tokens\": 0} }\n          error = null\n        }\n        exit = Completed { status = 200 }\n      }\n    }\n  }\n  scenario two_sessions {\n    app.in = { session = \"alice\"; job = \"a1\"; prompt = \"Hello\" }\n    expect model.out where meta.app.session == \"alice\" && meta.app.job == \"a1\"\n    app.in = { session = \"bob\"; job = \"b1\"; prompt = \"Hello\" }\n    expect model.out where meta.app.session == \"bob\" && meta.app.job == \"b1\"\n    app.in = { session = \"alice\"; job = \"a2\"; prompt = \"Another independent job\" }\n    expect model.out where meta.app.session == \"alice\" && meta.app.job == \"a2\"\n    expect app.unknown == nothing\n    expect app.failed == nothing\n  }\n  scenario missing_usage {\n    app.in = { session = \"alice\"; job = \"missing\"; prompt = \"Hello\" }\n    expect app.unknown where data.reason == \"usage not reported\"\n    app.in = { session = \"alice\"; job = \"null\"; prompt = \"Hello\" }\n    expect app.unknown where data.reason == \"usage not reported\"\n    expect app.failed == nothing\n  }\n  scenario observed_zero {\n    app.in = { session = \"alice\"; job = \"zero\"; prompt = \"Hello\" }\n    expect model.out where data.usage is ResponseUsage && data.usage.input_tokens == 0u && data.usage.output_tokens == 0u && data.usage.total_tokens == 0u\n    expect app.unknown == nothing\n  }\n  scenario schema_failure {\n    app.in = { session = \"bob\"; job = \"invalid\"; prompt = \"Hello\" }\n    expect app.failed where data is DecodeFailed && data.message.contains(\"out.usage.total_tokens\")\n    expect app.unknown\n    expect model.out == nothing\n  }\n  scenario transport_failure {\n    app.in = { session = \"alice\"; job = \"timeout\"; prompt = \"Hello\" }\n    advance duration(\"10s\")\n    expect app.failed == TimeoutExpired {}\n    expect app.unknown\n    expect model.out == nothing\n  }\n  scenario http_errors {\n    app.in = { session = \"alice\"; job = \"server_error\"; prompt = \"Hello\" }\n    expect app.failed where data is ServerError && data.status == 500\n    expect model.out\n    app.in = { session = \"alice\"; job = \"error_body\"; prompt = \"Hello\" }\n    expect app.failed where data is DecodeFailed && data.message.contains(\"out.id\")\n    expect model.out == nothing\n  }\n}\n```\n\n## Expected result\n\nThe CLI ends with `6 scenario(s), 0 failed`:\n\n| Scenario | Evidence |\n|---|---|\n| `two_sessions` | Alice's two jobs and Bob's job retain their own session and original response; each fixture reports 12 input, 4 output and 16 total tokens |\n| `missing_usage` | Absent/null usage produces an explanation and no measurement sample |\n| `observed_zero` | Three explicitly reported zero quantities remain observations |\n| `schema_failure` | `DecodeFailed` supplies no partially usable `model.out` |\n| `transport_failure` | A ten-second logical timeout produces no usage and no repeated inference |\n| `http_errors` | A decoded 500 is `ServerError`; an incompatible error body is `DecodeFailed` |\n\nThe three token quantities are separate facts, not three numbers to add\ntogether. Input plus output already accounts for the reported total in this\nfixture; the graph invents neither a monetary amount nor a missing quantity.\n\n## Break it\n\nIn the `simulated_message` constant, change `Hello from the simulated model.`\nto `A different model answer.`. Keep the expected trace unchanged and run\nthe comparison below. The counts still match, but `responses.two_sessions`\nfails its golden comparison. The other five scenarios still pass.\n\n```sh\nRASTOK_SHOWCASE_MODEL_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_MODEL_TOKEN_VERSION=fixture-v1 rastok simulate examples/agent-http.rkg --deployment examples/agent-http.deployment.json --compare examples/traces/agent-http\n```\n\n```text\nFAIL responses.two_sessions\n     golden divergence: record 6: closure(32)[1][0][1][1]; expected 820f868265657272…(399 bytes); got 820f868265657272…(393 bytes); cause: EGRESS \"model\" · emitting_id 7c6e92c8de6b86d2…(16 bytes) · call_key absent\nPASS responses.missing_usage\nPASS responses.observed_zero\nPASS responses.schema_failure\nPASS responses.transport_failure\nPASS responses.http_errors\n6 scenario(s), 1 failed\n```\n\nRestore the checked-in source (this discards your edits to this example):\n\n```sh\ngit checkout -- examples/agent-http.rkg\n```\n\n## Read the golden difference\n\nThe measured first divergence is `record 6: closure(32)[1][0][1][1]`:\nthe expected encoded value has 399 bytes and the changed one 393 bytes.\nThe cause is `EGRESS \"model\"`, with no Call key. The differing external\nresponse is recorded before downstream interpretation, even though the\nscenario's count assertions still hold. Restore the text; do not save over\nthe reference to hide the changed answer.\n\n<details id=\"golden\" class=\"raw-trace\">\n<summary>Inspect the raw sealed trace (.rkc)</summary>\n\nThe versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence.\n\nSource: `examples/traces/agent-http/responses.two_sessions.rkc`\n\n```rastok-trace\na6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202582e820f8382636a6f628206626131826670726f6d707482066548656c6c6f826773657373696f6e820665616c69636509636c61620a000b000d81826e2e696e3e726571756573742e696e82581882816772657175657374818380018207820665616c69636500\na7070211601282508280818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8\na807021167726571756573741282581882816772657175657374818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282508280818380018207820665616c69636500\na807021167726571756573741282581882816772657175657374818380018207820665616c696365001364703a696e1481836e2e696e3e726571756573742e696e82508280818380018207820665616c6963650001178183636f757400a601507c6e92c8de6b86d2cd0b2595345189fe0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025853820f858265696e70757482066548656c6c6f82716d61785f6f75747075745f746f6b656e738202188082656d6f64656c82066b6770742d362d6173747261826573746f72658201f4826673747265616d8201f406828363617070636a6f62820662613183636170706773657373696f6e820665616c6963651818818201506cef1737ef75613f4e28c116cf87754518198183507c6e92c8de6b86d2cd0b2595345189fe74726571756573742e6f75743e6d6f64656c2e696e82568281656d6f64656c818380018207820665616c69636500\na8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a737461727414801780181a507c6e92c8de6b86d2cd0b2595345189fe182282508280818380018207820665616c69636500\na60703181b507c6e92c8de6b86d2cd0b2595345189fe181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f01182174726571756573742e6f75743e6d6f64656c2e696e\na70703181b507c6e92c8de6b86d2cd0b2595345189fe181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f02182082018282636f7574820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e738214108264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c8182174726571756573742e6f75743e6d6f64656c2e696e\na7070211656d6f64656c1282568281656d6f64656c818380018207820665616c696365001364703a696e14818374726571756573742e6f75743e6d6f64656c2e696e82581882816772657175657374818380018207820665616c6963650001178283636f757400a60150b50ee3bb021a25a906a15643703a0aaa02507c6e92c8de6b86d2cd0b2595345189fe0350f3df1105112054d397a04ed0666ca4c8040105820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e7382141006828363617070636a6f62820662613183636170706773657373696f6e820665616c69636583646578697400a601505c6a50d6bb594d1d03157c3a3519cb5c02507c6e92c8de6b86d2cd0b2595345189fe0350f3df1105112054d397a04ed0666ca4c80401058202581c82138269436f6d706c65746564820f818266737461747573820218c806828363617070636a6f62820662613183636170706773657373696f6e820665616c69636518198283505c6a50d6bb594d1d03157c3a3519cb5c766d6f64656c2e657869743e7465726d696e616c2e696e8258198281687465726d696e616c818380018207820665616c696365008350b50ee3bb021a25a906a15643703a0aaa781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82581e82816d6578706c61696e5f7573616765818380018207820665616c69636500\na80702116d6578706c61696e5f75736167651282581e82816d6578706c61696e5f7573616765818380018207820665616c6963650013676c3a737461727414801780181a50b50ee3bb021a25a906a15643703a0aaa182282508280818380018207820665616c69636500\na8070211687465726d696e616c128258198281687465726d696e616c818380018207820665616c6963650013676c3a737461727414801780181a505c6a50d6bb594d1d03157c3a3519cb5c182282508280818380018207820665616c69636500\na60702116d6578706c61696e5f75736167651282581e82816d6578706c61696e5f7573616765818380018207820665616c696365001364703a696e148183781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82568281656d6f64656c818380018207820665616c69636500011780\na6070211687465726d696e616c128258198281687465726d696e616c818380018207820665616c696365001364703a696e148183766d6f64656c2e657869743e7465726d696e616c2e696e82568281656d6f64656c818380018207820665616c69636500011780\na6070108a40150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd0401058202582c820f8382636a6f628206626231826670726f6d707482066548656c6c6f826773657373696f6e820663626f6209636c61620a010b000d81826e2e696e3e726571756573742e696e825682816772657175657374818380018207820663626f6200\na70702116012824e8280818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd\na8070211677265717565737412825682816772657175657374818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824e8280818380018207820663626f6200\na8070211677265717565737412825682816772657175657374818380018207820663626f62001364703a696e1481836e2e696e3e726571756573742e696e824e8280818380018207820663626f620001178183636f757400a60150b312f77e5679f2bf2cf6a90512486e150250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025853820f858265696e70757482066548656c6c6f82716d61785f6f75747075745f746f6b656e738202188082656d6f64656c82066b6770742d362d6173747261826573746f72658201f4826673747265616d8201f406828363617070636a6f62820662623183636170706773657373696f6e820663626f62181881820150fd9b99717f323d91d5cf80e3988108a61819818350b312f77e5679f2bf2cf6a90512486e1574726571756573742e6f75743e6d6f64656c2e696e82548281656d6f64656c818380018207820663626f6200\na8070211656d6f64656c1282548281656d6f64656c818380018207820663626f620013676c3a737461727414801780181a50b312f77e5679f2bf2cf6a90512486e151822824e8280818380018207820663626f6200\na60703181b50b312f77e5679f2bf2cf6a90512486e15181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f01182174726571756573742e6f75743e6d6f64656c2e696e\na70703181b50b312f77e5679f2bf2cf6a90512486e15181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f02182082018282636f7574820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e738214108264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c8182174726571756573742e6f75743e6d6f64656c2e696e\na7070211656d6f64656c1282548281656d6f64656c818380018207820663626f62001364703a696e14818374726571756573742e6f75743e6d6f64656c2e696e825682816772657175657374818380018207820663626f620001178283636f757400a601505ba912d3696d95a061b788ba2c4cacd70250b312f77e5679f2bf2cf6a90512486e150350e6c20d6146234b74a33da1c709e86efd040105820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e7382141006828363617070636a6f62820662623183636170706773657373696f6e820663626f6283646578697400a601504bca3916c10fb79f16e79de566b7c1550250b312f77e5679f2bf2cf6a90512486e150350e6c20d6146234b74a33da1c709e86efd0401058202581c82138269436f6d706c65746564820f818266737461747573820218c806828363617070636a6f62820662623183636170706773657373696f6e820663626f6218198283504bca3916c10fb79f16e79de566b7c155766d6f64656c2e657869743e7465726d696e616c2e696e82578281687465726d696e616c818380018207820663626f620083505ba912d3696d95a061b788ba2c4cacd7781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82581c82816d6578706c61696e5f7573616765818380018207820663626f6200\na80702116d6578706c61696e5f75736167651282581c82816d6578706c61696e5f7573616765818380018207820663626f620013676c3a737461727414801780181a505ba912d3696d95a061b788ba2c4cacd71822824e8280818380018207820663626f6200\na8070211687465726d696e616c1282578281687465726d696e616c818380018207820663626f620013676c3a737461727414801780181a504bca3916c10fb79f16e79de566b7c1551822824e8280818380018207820663626f6200\na60702116d6578706c61696e5f75736167651282581c82816d6578706c61696e5f7573616765818380018207820663626f62001364703a696e148183781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82548281656d6f64656c818380018207820663626f6200011780\na6070211687465726d696e616c1282578281687465726d696e616c818380018207820663626f62001364703a696e148183766d6f64656c2e657869743e7465726d696e616c2e696e82548281656d6f64656c818380018207820663626f6200011780\na6070108a401506c793d2fff3f39818152c34ffedee98103506c793d2fff3f39818152c34ffedee98104010582025840820f8382636a6f628206626132826670726f6d7074820677416e6f7468657220696e646570656e64656e74206a6f62826773657373696f6e820665616c69636509636c61620a020b000d81826e2e696e3e726571756573742e696e82581882816772657175657374818380018207820665616c69636500\na807021167726571756573741282581882816772657175657374818380018207820665616c696365001364703a696e1481836e2e696e3e726571756573742e696e82508280818380018207820665616c6963650002178183636f757400a60150d86e9f1831c6494789aa711badd7ddd302506c793d2fff3f39818152c34ffedee98103506c793d2fff3f39818152c34ffedee98104010582025865820f858265696e707574820677416e6f7468657220696e646570656e64656e74206a6f6282716d61785f6f75747075745f746f6b656e738202188082656d6f64656c82066b6770742d362d6173747261826573746f72658201f4826673747265616d8201f406828363617070636a6f62820662613283636170706773657373696f6e820665616c6963651818818201505d480b4d1cb0c47547a7f416398d9e481819818350d86e9f1831c6494789aa711badd7ddd374726571756573742e6f75743e6d6f64656c2e696e82568281656d6f64656c818380018207820665616c69636500\na60703181b50d86e9f1831c6494789aa711badd7ddd3181c656d6f64656c181e5820d58e69e99055a2805c230647ed967fef93b58b8b820b06ee81c958388772c531181f01182174726571756573742e6f75743e6d6f64656c2e696e\na70703181b50d86e9f1831c6494789aa711badd7ddd3181c656d6f64656c181e5820d58e69e99055a2805c230647ed967fef93b58b8b820b06ee81c958388772c531181f02182082018282636f7574820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e738214108264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c8182174726571756573742e6f75743e6d6f64656c2e696e\na7070211656d6f64656c1282568281656d6f64656c818380018207820665616c696365001364703a696e14818374726571756573742e6f75743e6d6f64656c2e696e82581882816772657175657374818380018207820665616c6963650002178283636f757400a6015093f83c16cbcdd7c379cf6f05bcea521e0250d86e9f1831c6494789aa711badd7ddd303506c793d2fff3f39818152c34ffedee981040105820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e7382141006828363617070636a6f62820662613283636170706773657373696f6e820665616c69636583646578697400a6015021e649687ec5094e871d1561c4fd85800250d86e9f1831c6494789aa711badd7ddd303506c793d2fff3f39818152c34ffedee9810401058202581c82138269436f6d706c65746564820f818266737461747573820218c806828363617070636a6f62820662613283636170706773657373696f6e820665616c696365181982835021e649687ec5094e871d1561c4fd8580766d6f64656c2e657869743e7465726d696e616c2e696e8258198281687465726d696e616c818380018207820665616c69636500835093f83c16cbcdd7c379cf6f05bcea521e781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82581e82816d6578706c61696e5f7573616765818380018207820665616c69636500\na60702116d6578706c61696e5f75736167651282581e82816d6578706c61696e5f7573616765818380018207820665616c696365001364703a696e148183781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82568281656d6f64656c818380018207820665616c69636500021780\na6070211687465726d696e616c128258198281687465726d696e616c818380018207820665616c696365001364703a696e148183766d6f64656c2e657869743e7465726d696e616c2e696e82568281656d6f64656c818380018207820665616c69636500021780\nseal 53fde566fb48ea019d3f0b337349482361780d44c0520e3714578b29dd0d4c72\n```\n\n</details>\n\n## Carry forward\n\nPrevious: [Countdown](/examples/07-countdown.md). Use an explicit response type when\na partner supplies usage or another business quantity. Keep each original\nsample and its provenance, including an honest absence. Compare this short\nadapter with the resident [Agent gateway](/examples/06-agent-gateway.md): the same\ntyped-boundary discipline applies to two different interaction lifetimes.\n\n## Limits\n\nThe Lab scripts typed responses. Separate local wire tests, described in\nthe [projected JSON qualification](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/docs/architecture/openai-responses-hydration.md),\nexercise full JSON deserialization; no paid OpenAI invocation is claimed.\nAn API can change its payload and fail deserialization at runtime.\n\nNo reporting engine, pricing rule or automatic inference retry is supplied.\nMissing usage remains unknown. The in-memory journal is not durable recovery.\nThe boot-dependent profile also refuses `run --record`; use these versioned\nLab traces rather than treating a deployment credential as a replay input.\n"},{"path":"/guide/08-privacy-secrets-and-measurements","title":"Privacy, secrets and measurements","description":"Classify typed data, bind credentials outside the graph, and retain exact business quantities on their original responses.","text":"---\ntitle: Privacy, secrets and measurements\ndescription: Classify typed data, bind credentials outside the graph, and retain\n  exact business quantities on their original responses.\nurl: https://docs.rastok.com/guide/08-privacy-secrets-and-measurements\nsource_revision: v0.2.0-alpha\n---\n\n# Privacy, secrets and measurements\n\nAfter this chapter you can distinguish a data annotation from its runtime\ninterpretation, prepare the supported secret and privacy bindings, and\nlocate a measurement in the original response. A value's type answers what\nit contains; its annotations state how that value must be handled or read.\n\n## Declare metadata on a type\n\nAn annotation-capable type uses `type Name = @struct { ... }`. Its argument\nfields are flat: scalars, enums and their nullable forms, rather than nested\nrecords or collections. The same declaration can describe ordinary data or\ntyped metadata. Annotation arguments are checked plan constants.\n\nA user-declared annotation supplies descriptive metadata, not a handler or a\nsecurity hook. Standard annotations have registered consumers in the checker,\nruntime and inspection tools. Reproducing a standard annotation's field shape\ndoes not acquire that authority. See [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md) §§1–5.\n\n## Classify data where it enters the schema\n\n`examples/webhook-to-partner.rkg`, lines 3–7, identifies the email explicitly:\n\n```rkg\ntype Webhook = struct {\n  event_id: string\n  email: string @personal(identifier = true)\n  amount: int\n}\n```\n\n`@personal` is a classification, independent of confidentiality. Its optional\n`identifier`, `special` and `criminal` flags describe the field's role. A\npersonal-data plan requires an attested deployment profile covering its\nprocessing and recipients before execution. The supplied webhook profile is\nsynthetic evidence for the demonstration, not authority for real processing.\n\n`@sensitive(level = ...)` orders `Internal`, `Confidential` and `Restricted`.\nCopies preserve policy; derived values conservatively carry relevant classification.\nThe CLI and debugger redact before formatting. Redaction of a screen is not\nan erasure policy for stored data, nor a promise that arbitrary unannotated\npayloads are safe to share.\n\n## Keep credentials outside DATA\n\n`@secret` describes a stronger handling class. The executable credential path\nis reference-based: a logical `secret(\"path\")` at an admitted Connector setting\nis bound by the deployment, then resolved at the physical Driver boundary.\nThe clear value is not an ordinary graph `Value`. Raw secret-bearing schemas\non executable ports are refused; annotating a string is not a way to persist\nit safely in the journal.\n\nThe current sites are specific: `HttpClient.url` accepts an exact `env()`\nreference and `HttpClient.auth_bearer` an exact `secret()` reference. Read\n`examples/agent-http.rkg`, lines 46–56:\n\n```rkg\nconnector model : HttpClient {\n  url = env(\"MODEL_URL\")\n  auth_bearer = secret(\"showcase/model/token\")\n  method = \"POST\"\n  codec = json\n  json_profile = projected\n  output out: ModelResponse\n  timeout = duration(\"10s\")\n  max_body = \"256 KiB\"\n  behavior = probabilistic\n}\n```\n\nThe deployment JSON names the logical secret, environment-provider coordinate\nand immutable version. Supply the value out of band; its `<NAME>_VERSION`\ncompanion must match. The graph, request digest and journal keep references,\nnot the bearer bytes. `--deployment` supplies the same binding contract to\nreal and simulated execution. General `env()` expressions at other sites are\nnot part of this profile. See [`docs/spec/observability.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/observability.md) §5.\n\n## Read quantities from original responses\n\nThe adapter's response schema maps JSON members by name before committing the\ntyped response. `examples/agent-http.rkg`, lines 8–14, supplies its measurement\nmeaning alongside the numerical types:\n\n```rkg\ntype ResponseUsage = struct {\n  input_tokens: ulong @measure(id = input_tokens, unit = \"token\")\n  output_tokens: ulong @measure(id = output_tokens, unit = \"token\")\n  total_tokens: ulong @measure(id = total_tokens, unit = \"token\")\n  input_tokens_details: JsonObject?\n  output_tokens_details: JsonObject?\n}\n```\n\n`@measure` has exactly `id` and `unit`. The integer or exact decimal field\nsupplies the quantity; signed types can retain refunds or corrections. A\ncurrency is an ordinary unit. Each id has one unit throughout the plan.\nMissing usage supplies no sample; an observed zero remains evidence.\n\nThe journal retains these values in their original envelopes. Read-only\ninspection pairs them with validated annotations and causal provenance.\nRetry's held attempts keep their own samples, even when no downstream\nOperator sees them. Consuming a held batch creates no second sample. Treat\ninput, output and inclusive totals as separate observations, not as three\nquantities to add blindly.\n\n## Generate types from an API description\n\n`rastok --resolve-open-api <project-dir> [--check]` discovers static HTTP\nendpoints, selects matching OpenAPI 3.0/3.1 documents and writes deterministic\n`openapi.generated.rkg` aliases. It leaves authored files untouched.\n`--check` writes nothing and refuses missing or stale generated source.\nDynamic or ambiguous endpoints and schemas outside the lossless subset\nrefuse by name. Choose where the generated types constrain ports; every\nactual response still has to conform at runtime.\n\n## Summary\n\nAnnotations classify typed data; deployment bindings supply external authority;\nmeasurements preserve original quantities. Reporting, automatic pricing,\nbudgets and durable personal-data storage remain outside the\n[current alpha scope](/index.md#what-is-available-today). Normative details\nare in [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md), [`docs/spec/observability.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/observability.md) and\n[`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md) §5.\n\n## Next\n\nContinue with [Command line](/guide/09-command-line.md). Practice with the deployment profile in\n[Webhook to partner](/examples/04-webhook-to-partner.md), then compare absent\nand zero usage in the [HTTP model adapter](/examples/08-model-adapter.md).\n"},{"path":"/reference/execution","title":"Execution and concurrency","description":"Distinguish instance ownership, concurrent external I/O and the execution model implemented by the current runtime.","text":"---\ntitle: Execution and concurrency\ndescription: Distinguish instance ownership, concurrent external I/O and the\n  execution model implemented by the current runtime.\nurl: https://docs.rastok.com/reference/execution\nsource_revision: v0.2.0-alpha\n---\n\n# Execution and concurrency\n\n## Current runtime\n\nThe hosted runtime advances a program through one single-threaded Worker.\nIt executes Operator transactions sequentially, not in parallel on several\nCPU cores. A Driver can have an external Call outstanding while the Worker\nprocesses other ready work. Network I/O and child processes can therefore\noverlap without parallel execution of DSL handlers.\n\nA transaction prepares its state changes and emissions, then commits them\ntogether. It does not wait for a partner response inside an Operator\nhandler. A Connector's later response or timeout supplies another activation.\nA long-running Operator computation can delay other ready work; the alpha\ndoes not schedule it on a separate compute pool.\n\n## Instances own state, not threads\n\n| Concept | Current meaning |\n|---|---|\n| Instance key | Selects a logical owner, such as one tenant or sensor; it does not allocate a thread or process |\n| Operator instance | Owns its mailbox and private `var` cells; its transactions run one at a time |\n| Connector instance | Owns its exchanges and Contract state; a Driver performs the external operations |\n| Graph instance | Owns containment and lifecycle, but has no application mailbox, handler or shared mutable state |\n| Lifetime | Determines when an instance closes; it is independent of key selection and physical placement |\n| Worker | Advances the execution, journal and selected Drivers; it is not created for each key |\n\nAn unkeyed child belongs to its enclosing Graph instance. Keying the App by\ntenant therefore isolates its descendants even when each child omits an\ninstance key. A `var` is private to the Operator instance that declares it;\nother Operators communicate through ports rather than reading that cell.\nSee [Instances, state and time](/guide/06-instances-state-and-time.md).\n\nAn outbound Call Connector instance holds one open Call at a time. The next\nrequest waits in that instance's mailbox, and its `timeout` already runs:\nthe budget starts when the request is delivered to the Connector, not when\nthe Call opens. A request queued behind a slow Call can therefore expire\nwithout having been sent; the journal shows it opening and closing with a\ntimeout. For independent Calls, give each request its own instance. This\nper-instance ordering does not prevent I/O on different instances from overlapping.\n\nMailboxes and Call capacities have bounds. A source Connector's proposal\nremains pending when its target mailbox is full; direct App input admission\ninstead reports a capacity error. Neither commits an ingress before room is\navailable. Adding an instance does not remove capacity bounds. The number\nof pending Calls is not a count of parallel Operator transactions.\n\nHttpServer handles inbound Calls, not that outbound mailbox queue. Its Driver\nbounds physical connections, requests and retained bytes. When the graph\ncannot admit a proposal, the Driver keeps it pending; an `ack` response of\n202 follows admission, never precedes it. When its connection or request slots\nare full, the Driver waits for room rather than accepting unlimited work.\nA request exceeding a configured body or header size limit is refused before\nadmission. Waiting does not guarantee that a client stays connected. Protocol\nrefusals and failures remain distinct from admitted requests and their terminal outcomes.\nWebSocket Connectors and Process `service` use Sessions, not one Call per message.\n\n## What the two-tenant example demonstrates\n\nIn [Two tenants](/examples/03-two-tenants.md), Alice's first Call remains\npending while Bob's Call completes. Alice's timeout and backoff belong to\nher instance, so Bob does not repeat his request. The Lab supplies both\npartners' behavior and advances the clock explicitly. This demonstrates\nindependent progress and isolated Retry state, not multicore throughput.\n\nThe corresponding real-world pattern can have several external requests\noutstanding. A Process Connector may start child processes under its\nContract; that does not make every keyed Operator an operating-system\nprocess.\n\n## Ordering and replay\n\nDeliveries within one instance mailbox are consumed in FIFO order.\nIndependent instances have no application-level ordering guarantee between\nthem. When external responses race, their admitted order can differ between\nlive runs. The journal records the chosen order and causes.\n\nThe Lab makes inputs, partner responses and time explicit, so a scenario\ncan reproduce its journal. Diagnostic replay reads recorded facts without\nrepeating external effects. Neither claim means that live partners must\nrespond in the same order on every deployment. See\n[The Lab](/reference/lab.md) and [Running for real](/guide/05-running-for-real.md).\n\n## Specified, not shipped\n\n| Capability | Boundary of the current implementation | Specification |\n|---|---|---|\n| A bounded pool of Workers across CPU cores | The hosted runtime uses one Worker; keyed instances are not scheduled across a pool | [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §2 |\n| Distributed placement and reassignment | Virtual-shard mapping has a proof implementation, but the alpha does not deploy instances across Hosts or implement ownership leases | [`docs/spec/instances.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md) §9 |\n| A separate compute pool | Operator evaluation is synchronous; CPU-heavy work is not offloaded by the runtime | [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §2 |\n\nThese implementation limits do not change the ownership rule: one instance\nmust never execute conflicting transactions concurrently.\n"},{"path":"/guide/09-command-line","title":"Command line","description":"Choose a Rastok command, supply its options, and distinguish read-only checks from real execution and file writes.","text":"---\ntitle: Command line\ndescription: Choose a Rastok command, supply its options, and distinguish\n  read-only checks from real execution and file writes.\nurl: https://docs.rastok.com/guide/09-command-line\nsource_revision: v0.2.0-alpha\n---\n\n# Command line\n\nAfter this chapter you can choose commands and interpret their exit status.\nRun examples from the checkout root.\n\n## Help and version\n\n```text\nrastok --help | -h | help\nrastok --version | -V | version\n```\n\nHelp prints to stdout and exits successfully.\n`rastok --version`, `rastok -V` and `rastok version` print the same package version. Global help and version reject extra\narguments. `rastok <command> --help` prints that command's usage and options on\nstdout and exits successfully; `-h` is the same.\nRun `rastok <command> --help` for the options of one command.\n\nBrackets mean optional, `|` separates alternatives, and `...` accepts multiple\nfiles in one compilation unit.\n\n## Create a program: new\n\n```text\nrastok new <name>\n```\n\n`rastok new hello` creates `hello.rkg`: an App, a typed Operator and a Lab\nscenario. Names exclude paths and extensions. Existing files are never\noverwritten; follow-up commands are printed, not executed.\n\n## Check a program: check\n\n```text\nrastok check <file.rkg>...\n```\n\n```sh\nrastok check examples/echo.rkg\n```\n\nChecks types, wiring and Contracts, then prints the Node count and\nsemantic hash. It neither executes the App nor writes a plan file. Success\ndoes not prove partner availability or compatible physical Drivers.\n\n## Run scenarios: simulate\n\n```text\nrastok simulate <file.rkg>... [--deployment <profile.json>] [--compare <dir> | --save <dir>] [--ui [--ui-port <port>]]\n```\n\n```sh\nrastok simulate examples/echo.rkg --compare examples/traces/echo\n```\n\nSimulation uses mocks and virtual time, not physical Drivers. Without `--ui`,\nit prints each scenario's `PASS` or `FAIL`, `simulation.scenario`, then totals.\nDirect scenarios use their Lab's name.\nA unit without a Lab refuses.\n\n- `--compare` reports each scenario's first difference from reviewed traces.\n  Missing references fail.\n- `--save` creates or replaces reference files named\n  `<simulation>.<scenario>.rkc`. Review the semantic reason for the change;\n  saving is not proof that expectations pass.\n- These options are exclusive. Neither selected: check expectations without\n  reading or writing reference traces.\n- `--deployment` supplies the graph's boot values and attestations even with mocks.\n\n`--ui` requires `hosted-ui`, prints a token-bearing loopback URL and starts\npaused. `--ui-port` requires `--ui` and selects a nonzero TCP port;\notherwise the OS chooses one.\n\n## Execute the App: run\n\n```text\nrastok run <file.rkg>... [--file-root <dir>] [--deployment <profile.json>] [--json-logs] [--record <file.rkr>]\n```\n\n```sh\nprintf 'hello\\n' | rastok run examples/echo.rkg --record echo.rkr\n```\n\nEach stdin line enters `app.in` as a string, selecting the exact `string` branch\nof a union. Stdin does not decode JSON. An incompatible port and its type\nare reported before stdin is read. Drivers perform real I/O; the Lab does not run.\n\nA string prints bare. Any other value prints as one line of JSON, the\nsame projection the Lab uses in its reports. Protected fields remain redacted.\nRaw payloads without a materialized value retain their byte-to-text rendering.\nWith several declared output ports, every line keeps its `port: value` prefix.\n\nAfter EOF, `run` waits for open Calls and Sessions, not deadlines alone.\nAn `HttpServer` keeps listening; read `listen` in the source.\nCtrl-C stops it without a message.\n\n- `--file-root` enables the physical File Driver within an explicit root.\n- `--deployment` reads typed boot settings, secret coordinates, attestations\n  and any Driver selection from a deployment JSON file. Secret material is\n  supplied out of band, never as a CLI argument.\n- `--json-logs` exports structured events on stderr; outputs stay on stdout.\n  The bounded exporter can drop observations; these logs are not a complete\n  journal. Other diagnostics use stderr.\n- `--record` writes a diagnostic recording and refuses an existing path.\n  Personal-data plans, nonempty deployment attestations and boot-dependent\n  Connector settings refuse. Recordings are sensitive evidence, not durable\n  restart storage.\n\n`run --ui` is not supported. Inspect a supported recording afterward instead.\n\n## Inspect a recording: replay\n\n```text\nrastok replay <file.rkr> [--ui [--ui-port <port>]]\n```\n\n`rastok replay echo.rkr` prints App outputs in `run`'s format on stdout and a\nrecord-count/seal summary on stderr, without Driver I/O.\n`--ui` uses simulation's port rules and opens read-only recorded history.\nMissing source lines are explicit. Replay needs no original source and cannot\nexecute the program or create a Lab scenario.\n\n## Inspect capabilities: connectors\n\n```text\nrastok connectors [--json]\n```\n\nLists Contracts, modes, ports, settings, implementations, Lab bindings and\nuntested cases, as text or `--json` on stdout. It constructs no Driver and\nprobes no service; checker support does not prove deployment support.\n\n## Resolve project schemas: --resolve-open-api\n\n```text\nrastok --resolve-open-api <project-dir> [--check]\n```\n\nThis matches static HTTP endpoints to OpenAPI 3.0/3.1 documents and writes\n`openapi.generated.rkg` types, leaving authored sources untouched. `--check`\nwrites nothing and refuses missing or stale output. Unsupported or ambiguous\nschemas refuse. Generation cannot prove a live API honors its schema.\nThe leading double dash is required.\n\n## Exit status and streams\n\n- `0`: the requested operation succeeded, including explicit help or version.\n- `1`: compilation, execution, scenario, comparison or file operation failed.\n- `2`: a recognized usage error, such as a missing command or invalid option combination.\n\nUsage errors go to stderr, including a bare `rastok` invocation. Scenario\nfailure details remain in the simulation report on stdout; do not detect\nsuccess solely by whether stderr is empty.\n\n## File formats\n\n- `.rkg`: program and Lab source.\n- `.rkp`: compiled plan package.\n- `.rkc`: causal reference for `simulate --compare`.\n- `.rkr`: execution recording for `replay`, without repeating external effects.\n\n## Summary\n\nCheck, then simulate before contacting partners; save only intentional baselines.\nRead the [alpha limits](/index.md#what-is-available-today), [`docs/spec/ui.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/ui.md)\nand [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md) §5.\n\n## Next\n\nPractice with [Echo](/examples/01-echo.md). Next: [When the answer is lost](/guide/10-when-the-answer-is-lost.md).\nPrevious: [Privacy](/guide/08-privacy-secrets-and-measurements.md). Deployment: [Running for real](/guide/05-running-for-real.md).\n"},{"path":"/guide/10-when-the-answer-is-lost","title":"When the answer is lost","description":"Read a Call terminal, distinguish a lost answer from a refused operation, and choose what to tell the caller.","text":"---\ntitle: When the answer is lost\ndescription: Read a Call terminal, distinguish a lost answer from a refused\n  operation, and choose what to tell the caller.\nurl: https://docs.rastok.com/guide/10-when-the-answer-is-lost\nsource_revision: v0.2.0-alpha\n---\n\n# When the answer is lost\n\nAfter this chapter you can distinguish “the partner said no” from “we never\nheard the answer.” Suppose you send a booking request. You wait, the deadline\npasses, and no receipt arrives. The room may still be booked. Starting again\nwith a different reference could book a second room; telling the guest that\nnothing was booked could leave a reservation that nobody knows to cancel.\n\n## What the terminal tells you\n\nA finite outbound Call has one terminal on its `exit` port. Losing the answer\ndoes not create a second port. It changes what you can conclude from the case:\n\n- **No answer arrives.** `TimeoutExpired` says the Call reached its deadline.\n  It does not say where the partner was in its work.\n- **The answer cannot be used.** An HTTP client may receive an unreadable body\n  (`DecodeFailed`), lose the exchange (`ProtocolFailed`), or reach the body\n  limit (`BodyTooLarge`). A File or Process has different case names. Check\n  the table in its [Connector contract](/reference/contracts.md).\n- **The runtime closes the Call without observing its end.** `OutcomeUnknown`\n  preserves that uncertainty. Recovery does not silently send the request again.\n\nAn outbound [HttpClient](/reference/connectors/http-client.md) can also produce\n`DecodeFailed` before sending a request that does not fit its codec.\nRead `data.message` after testing `data is DecodeFailed`: a request refusal\nnames the input, while an unreadable response names the output or the\ndeclared field that did not fit. The message explains the refusal without\ncopying the value. It is not a receipt: a partner may already have acted\nbefore sending an unreadable response.\n\n## Three responses to the same timeout\n\nChoose what is safe for this particular operation. These choices can go\nto the same output as other cases; the important part is to name the case\nand decide what the output means.\n\n| Choice | What the booking program does | What its caller learns |\n|---|---|---|\n| Report uncertainty | Route `TimeoutExpired` and the other lost-answer cases to the branch that emits `Unknown`. | There is no receipt. The caller can decide whether to investigate. |\n| Read back | Send a separate lookup with the original booking reference and compare the returned receipt with the request. | A matching receipt confirms the booking without making another one. If the lookup also loses its answer, report the booking as unconfirmed. |\n| Retry with a key | Give the Call a stable `idempotency_key`, declare the partner's idempotence guarantee, and select `TimeoutExpired` in `Retry.on`. | The partner can recognize another attempt at the same operation. If the attempts run out, the last terminal still needs a decision. |\n\nA key identifies the operation. It does not by itself make the partner\nhonor that key. In the [webhook example](/examples/04-webhook-to-partner.md)\nthe contract with the partner supplies that guarantee. Read\n`examples/webhook-to-partner.rkg`, lines 93–95:\n\n```rkg\nRetry.attempts = 2\nRetry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed]\nRetry.delay = { kind = fixed; after = duration(\"1s\") }\n```\n\n## Read the warning\n\nIf a route sends only `Completed` to a receipt handler and sends `_` to a\nfailure handler, `rastok check` reports `W-MATCH-CATCHALL` on the underscore.\nIt does the same for the match in the first Operator that receives the\nterminal through a simple route. The diagnostic lists the lost-answer cases\nthat no arm names. An arm that tests `data is TimeoutExpired` names that case;\nthe other cases can share one arm. The check follows nested matches. For\nexample, `data is TimeoutExpired && retrying` does not cover a timeout when\n`retrying` is false. A wildcard that writes neither an output nor state\ndiscards the event and is not reported. A handler with no wildcard is not\nreported either. The check does not follow the value through another Operator.\n\n## Summary\n\nA timeout is evidence about the answer, not the reservation. Name the\nuncertain outcomes and choose whether to report them, look up a receipt,\nor repeat an operation under a guarantee. A warning does not change the\nplan or its exit status. For implementation limits, see\n[What is available today](/index.md#what-is-available-today).\n\n## Next\n\nRun the timeout scenario in [Webhook to partner](/examples/04-webhook-to-partner.md).\nCompare its terminal after a successful retry with the last terminal when\nthe partner never answers. For the repetition rule, return to\n[Loops and retries](/guide/07-loops-and-retries.md).\n"},{"path":"/ai-agents","title":"AI Agents","description":"Read the documentation, the examples and their reference traces from a coding assistant through Markdown twins, llms.txt, content negotiation and the agent index.","text":"---\ntitle: AI Agents\ndescription: Read the documentation, the examples and their reference traces\n  from a coding assistant through Markdown twins, llms.txt, content negotiation\n  and the agent index.\nurl: https://docs.rastok.com/ai-agents\nsource_revision: v0.2.0-alpha\n---\n\n# AI Agents\n\nEvery page of this site exists twice: as HTML for people, and as Markdown for assistants and scripts. An assistant that can fetch a URL can read the whole documentation, the examples and their reference traces from the same pinned source as this site. Nothing here runs a graph or changes a file.\n\n## What an assistant can read\n\n| Address | Content |\n| --- | --- |\n| [/llms.txt](/llms.txt) | What Rastok is, a short vocabulary, and every page with its description, in reading order. |\n| [/llms-full.txt](/llms-full.txt) | The same index followed by the complete Markdown of every page. |\n| `<page>.md`, such as [/getting-started.md](/getting-started.md) | The Markdown twin of one page. Example pages include their raw graph and reference trace. |\n| [/agent-index.json](/agent-index.json) | The text of every page and the list of examples, as the visible search uses them. |\n| `/examples/<name>.rkg` | A raw example source from the pinned checkout, such as [/examples/echo.rkg](/examples/echo.rkg). |\n\nOn Cloudflare, requesting a page's HTML address with `Accept: text/markdown` returns its Markdown twin. The plain Astro development server serves the `.md` files and the indexes; content negotiation runs in the Cloudflare Pages Worker.\n\n## A working path, from nothing to a checked program\n\n1. **Discover.** Read [/llms.txt](/llms.txt): what Rastok is, the vocabulary, every page, the specification and the example sources.\n2. **Learn the syntax.** The normative grammar and the specification chapters are linked from `llms.txt` at the pinned revision; the [Reference](/reference/types) pages explain types, expressions, Contracts, Connectors, the Lab and the diagnostics in reading order.\n3. **Read a complete program.** Each `/examples/<name>.rkg` is a whole program with its Lab in the same file; start with [/examples/echo.rkg](/examples/echo.rkg), then [/examples/webhook-to-partner.rkg](/examples/webhook-to-partner.rkg) for Connectors, Retry and instances.\n4. **Write and check.** `rastok new <name>` creates a file with a typed Operator and a Lab; `rastok check <file>.rkg` compiles it and prints typed diagnostics with their codes, explained in [Diagnostics](/reference/diagnostics).\n5. **Simulate.** `rastok simulate <file>.rkg` runs every Lab scenario and reports `PASS` or the first difference; `--ui` opens the debugger. Install the CLI as described in [Getting Started](/getting-started).\n\n## Point your assistant at it\n\nGive the assistant the address of `llms.txt` or of one page; it follows the links from there. In Claude Code, Codex or Cursor, fetching the URL is enough, no server or plugin to install.\n\nTo write: open your preferred LLM harness or coding agent in an empty directory and give it a specification, for example: \"Using https://docs.rastok.com/llms.txt, develop a Rastok application and its Lab that meet the following specification: \\<your spec\\>.\" The documentation tells it how to check and simulate what it wrote.\n\nTo read: \"Read https://docs.rastok.com/examples/04-webhook-to-partner.md and explain how the retry is bounded and what the reference trace proves.\"\n\n\n## Public access\n\nThese addresses are public. They require no login, no token and no account. No graph execution is provided.\n"}],"examples":[{"name":"agent-chat","path":"examples/agent-chat.rkg","title":"agent-chat","description":""},{"name":"agent-dialogue","path":"examples/agent-dialogue.rkg","title":"agent-dialogue","description":""},{"name":"agent-gateway","path":"examples/agent-gateway.rkg","title":"Agent gateway: keep a conversation isolated","description":"Connect WebSocket conversations to resident JSONL processes, simulate interleaved app-server requests, and close one child without interrupting the other.","pagePath":"/examples/06-agent-gateway","goldenPath":"examples/traces/agent-gateway/app_server.two_conversations.rkc"},{"name":"agent-http","path":"examples/agent-http.rkg","title":"HTTP model adapter: typed responses and token metering","description":"Select a typed view of an OpenAI Responses result, retain original token measurements by job and session, and distinguish absent usage from an observed zero.","pagePath":"/examples/08-model-adapter","goldenPath":"examples/traces/agent-http/responses.two_sessions.rkc"},{"name":"countdown","path":"examples/countdown.rkg","title":"Countdown: a bounded loop","description":"Prove that a countdown terminates, follow its manager commands, and see the checker reject a measure that cannot prove progress.","pagePath":"/examples/07-countdown","goldenPath":"examples/traces/countdown/proof.positive.rkc"},{"name":"csv-count","path":"examples/csv-count.rkg","title":"csv-count","description":""},{"name":"echo","path":"examples/echo.rkg","title":"Echo: one graph, two worlds","description":"Run one graph with a real cat process or scripted Lab responses, then inspect a recording without starting the process again.","pagePath":"/examples/01-echo","goldenPath":"examples/traces/echo/smoke.roundtrip.rkc"},{"name":"file-pipeline","path":"examples/file-pipeline.rkg","title":"File pipeline: effects with a contract","description":"Read a bounded file, reject an empty input, count its bytes and atomically replace a second file, then replay without disk access.","pagePath":"/examples/02-file-pipeline","goldenPath":"examples/traces/file-pipeline/files.copy.rkc"},{"name":"gauge","path":"examples/gauge.rkg","title":"gauge","description":""},{"name":"jsonl","path":"examples/jsonl.rkg","title":"jsonl","description":""},{"name":"keyed-retry","path":"examples/keyed-retry.rkg","title":"Two tenants: whose state is this?","description":"Watch Bob finish once while Alice alone times out, waits for backoff and retries in an isolated keyed instance.","pagePath":"/examples/03-two-tenants","goldenPath":"examples/traces/two-tenants/ui_tour.two_tenants.rkc"},{"name":"sensor-alarm","path":"examples/sensor-alarm.rkg","title":"Sensor alarm: make time an input","description":"Isolate hysteresis state by sensor, detect a missed heartbeat with a bounded join, and advance through a virtual day without waiting a day.","pagePath":"/examples/05-sensor-alarm","goldenPath":"examples/traces/sensor-alarm/sensors.virtual_day.rkc"},{"name":"webhook-to-partner","path":"examples/webhook-to-partner.rkg","title":"Webhook to partner: put it together","description":"Admit a webhook, validate and deduplicate it, then exercise bounded partner retries with privacy, secret and cost evidence.","pagePath":"/examples/04-webhook-to-partner","goldenPath":"examples/traces/webhook-to-partner/webhook.nominal.rkc"}]}