# eleph, complete documentation # Start here > You have an agent in production. It calls tools and it tells customers things. This is what eleph does about that, and what it does not. Source: https://elephlanguage.vercel.app/docs/use/start-here You have an agent in production. It calls tools, it asserts things about a customer's record, and it promises to do things. Some of what it says is not true, and some of what it promises never happens. This page is about that, and you do not need to adopt a new language to get most of the way. ## What eleph does Three things, and they are narrow on purpose: - **It refuses an assertion the record does not support.** Not softens it, not logs it. `assert_answer` raises before the text reaches the customer. - **It refuses a tool call whose precondition does not hold.** `require` is checked against what actually happened, not against a field somebody might have forgotten to update. - **It remembers what you promised.** "Your refund is on the way" becomes a debt with a deadline, and at the end of the run there is an answer to *did we deliver*. ## What eleph does not do > **CAREFUL: It will not reduce your token bill** > > Nothing in this project measures cost, so nothing here claims to change it. A > guard does not rewrite your prompt, does not add a model call, and does not > retry anything. > > What can be verified is the other direction: a `Guard` makes **no model calls > and no network calls at all**. It is Python reading an append-only list. So it > does not add spend either. > > If your problem is the bill, this is the wrong tool. If your problem is that > you cannot tell which of the agent's answers were true, keep reading. It is also not a prompt technique, not an output filter, and not a policy engine you configure through a dashboard. Output filters read the text. This reads the history. ## What the measurement actually showed The same agent, run twice over nine support cases. Identical model, identical system prompt, identical tool names, descriptions and signatures. The only difference is whether a guard sits under the two tools that write. | | without eleph | with eleph | |---|---|---| | Claude Haiku 4.5, 5 runs per case | **30/45** | **45/45** | | Claude Opus 5, earlier 7-case suite, 3 runs | **19/21** | **21/21** | The stronger model fails less. The direction is the same. Three things in that result matter more than the total, and they are what tells you whether your system has this problem: **The failures are concentrated, not spread.** Six of the nine cases pass 5/5 on both sides. Three fail 5/5 without the guard. This is not a model being occasionally unlucky. It is a model being consistently and reasonably wrong about three specific things. **One case fails 0/5: someone asked about a stranger's account.** The agent looked it up and reported back, every single time. Nothing in the prompt told it not to, the request was perfectly clear, and answering was the helpful thing to do. **One case passes 5/5 without the guard**, and that matters as much. The prompt said the refund limit is R$ 200 and that larger cases escalate; the case was clear-cut; the model got it right every time. **A clear instruction about an unambiguous case works. The guard is not for those.** What separates the three failures from the six successes is not difficulty. In the three, the model would have had to distrust something: the customer's account of the past, the customer's persistence, or the customer's right to be asking at all. Models are built not to do that. [The full comparison, including the bug it was built with →](https://elephlanguage.vercel.app/docs/integration/langchain) ## Three shapes, cheapest first You do not have to adopt the language. Two of these three need none of it. | Shape | You change | You get | Cost to try | |---|---|---|---| | **observer** | nothing. You feed it events | what is true of the record, and an audit | an afternoon | | **guard** | assertions and tool calls route through it | ungrounded claims raise instead of shipping | a day | | **language** | handlers written in `.eleph` | the static proof | a week | Start as an observer over traffic you already have. It cannot break anything, because it enforces nothing. If it never disagrees with your system, you do not have this problem and you can stop. ## Which one you want > **NOTE: If you are not sure, you want the guard** > > The **observer** answers "does my agent say things the record does not > support?" Run it over yesterday's traffic before changing any code. > > The **guard** is the one most systems ship. Rules live in a `.eleph` file that > `eleph check` proves; your Python calls `require`, `assert_answer`, `record` > and `promise`. You never write a handler. > > The **language** is for when the decision logic itself should be verified, not > just the facts it reads. That is the research artifact, and it is the only one > that needs the [language reference](https://elephlanguage.vercel.app/docs/reference/program-structure). The reason to keep the rules in a policy file rather than writing the checks in Python is one line: **the rules your guard enforces at three in the morning are the same artifact a solver proved.** A guard whose rules were proved is a different thing from a guard whose rules someone believed. ## The path from here - [**Install it**](https://elephlanguage.vercel.app/docs/installation) into your project. One dependency, Z3. - [**Wire it to your model**](https://elephlanguage.vercel.app/docs/use/any-model) — GPT-4, Claude, anything. Nothing in the guard knows what an LLM is. - [**Model your domain**](https://elephlanguage.vercel.app/docs/use/modelling) — turning the tables you already have into events and facts, which is the only genuinely new thinking here. - [**With your coding assistant**](https://elephlanguage.vercel.app/docs/use/with-your-assistant) — an MCP server that hands your model the checker instead of the documentation, so the policy it writes is one a solver proved. - [**The API reference**](https://elephlanguage.vercel.app/docs/python-api), for when you know what you are reaching for. If you would rather see the idea before the integration, the [quickstart](https://elephlanguage.vercel.app/docs/quickstart) is nine lines and a bug McCarthy wrote down in 1998. --- # Any model, any framework > Nothing in the guard knows what an LLM is. Worked examples with the OpenAI SDK, a raw tool loop, and LangChain. Source: https://elephlanguage.vercel.app/docs/use/any-model The worked example in this repository uses LangChain and Claude, and that is an accident of what was on hand. A `Guard` is Python reading an append-only list: it makes no model calls, no network calls, and it has no opinion about which provider produced the text it is checking. > **NOTE: What the guard imports** > > `eleph.guard` pulls in `json`, `pathlib`, `dataclasses`, `typing` and the rest > of `eleph`. There is no HTTP client anywhere on the path. GPT-4, Claude, > Gemini, Llama, a fine-tune of your own, or a hand-written state machine: the > integration is identical. ## Where the guard goes Two places, and only two. ```text model proposes guard decides ┌──────────┐ ─────────────────▶ ┌─────────┐ ────────────────▶ ┌────────┐ │ your │ │ your │ require(...) │ your │ │ LLM │ │ code │ assert_answer() │ backend│ └──────────┘ ◀───────────────── └─────────┘ ◀──────────────── └────────┘ tool result record(...) ``` **Before a tool runs**, `require` the precondition. **Before an assertion ships**, `assert_answer` it. Everything else is your existing plumbing. ## The policy One file, proved before an agent touches it. support.eleph ```eleph program support sort User sort Charge event authenticated(who: Party, u: User) event logged_out(who: Party, u: User) event subscribed(u: User) event cancelled(u: User) event refunded(u: User, c: Charge) event statement_closed(u: User) event charged_while_active(u: User, c: Charge, amount: Number) event charged_after_cancelling(u: User, c: Charge, amount: Number) fact authorised(Q: Party, U: User) := authenticated(Q, U) since_not logged_out(Q, U) fact active(U: User) := subscribed(U) since_not cancelled(U) fact refundable(U: User, C: Charge) := charged_after_cancelling(U, C, amount > 0) since_not refunded(U, C) fact within_limit(U: User, C: Charge) := charged_after_cancelling(U, C, amount <= 200) since_not refunded(U, C) fact may_refund(U: User, C: Charge) := refundable(U, C) and within_limit(U, C) on question(Who, active(U)) permitted authorised(Who, U): answer Who with active(U) on question(Who, may_refund(U, C)) permitted authorised(Who, U): answer Who with may_refund(U, C) ``` ```out $ eleph check support.eleph support.eleph -> programa support 8 eventos, 5 fatos, 2 handlers 2 obrigacoes derivadas do texto do programa cada uma checada no seu limiar de completude (o maior: 6 eventos) -- exaustivo ok question(Who, active) linha 30 - a resposta responde a pergunta feita ok question(Who, may_refund) linha 33 - a resposta responde a pergunta feita PROVADO - 2 obrigacoes valem para TODO historico, de qualquer tamanho ``` ## What it refuses This is a real run, with no model in it at all. The four proposals are the four failures the LangChain comparison found, stripped of the model and the framework. ```python from eleph import Policy, Ungrounded policy = Policy.from_file("support.eleph") print("static check:", policy.verify().summary()) g = policy.guard() # What your system already knows. In a real integration these are recorded # as they happen. g.record("subscribed", "ana") g.record("charged_while_active", "ana", "c1", "150") g.record("authenticated", "session-42", "ana") # 1. the customer's false premise: "I cancelled last month, refund me" g.require("refundable", "ana", "c1") # 2. the model asserts something the log denies g.assert_answer("active", False, "ana") # 3. someone else's account g.require("authorised", "session-42", "bruno") ``` ```out static check: 2 obrigacoes provadas para todo historico -- 1. the customer's false premise -- REFUSED: o log nao sustenta refundable(ana, c1) -- 2. the model asserts something the log denies -- REFUSED: tentou afirmar active(ana) = False quando o log diz True -- 3. someone else's account -- REFUSED: o log nao sustenta authorised(session-42, bruno) ``` And the promise the legitimate case creates: ```python g.record("cancelled", "ana") g.record("charged_after_cancelling", "ana", "c2", "80") g.require("may_refund", "ana", "c2") # passes: cancelled, open, under 200 # The agent says "your refund is on the way". That is a debt, and it is due # before the statement closes. g.promise("ana", "refunded", "ana", "c2", before=("statement_closed", ("ana",))) g.record("statement_closed", "ana") # and nobody refunded ``` ```out -- 4. a legitimate refund, and the promise it creates -- outstanding: 1 -- 5. the statement closes and nobody refunded -- BREACHED a ana: alguma vez refunded(ana, c2) (antes de statement_closed(ana)) outstanding: 0, breached: 1 ``` That last block is the category no output filter can see: the agent said it would, and then did not. ## With the OpenAI SDK The guard is the same four calls. Only the plumbing around it changes. ```python import json from openai import OpenAI from eleph import Policy, Ungrounded client = OpenAI() guard = Policy.from_file("support.eleph").guard(log="support.jsonl") TOOLS = [ { "type": "function", "function": { "name": "issue_refund", "description": "Refund one charge for a customer.", "parameters": { "type": "object", "properties": { "user": {"type": "string"}, "charge_id": {"type": "string"}, }, "required": ["user", "charge_id"], }, }, } ] def issue_refund(session: str, user: str, charge_id: str) -> str: """The tool the model can call. The guard decides whether it runs.""" try: guard.require("authorised", session, user) # is this caller entitled guard.require("may_refund", user, charge_id) # does the record support it except Ungrounded as e: return f"REFUSED by policy: {e}" backend.refund(user, charge_id) # your existing code guard.record("refunded", user, charge_id) guard.promise(user, "refunded", user, charge_id, before=("statement_closed", (user,))) return "refund issued" def turn(session: str, messages): reply = client.chat.completions.create( model="gpt-4o", messages=messages, tools=TOOLS ) message = reply.choices[0].message for call in message.tool_calls or []: args = json.loads(call.function.arguments) if call.function.name == "issue_refund": result = issue_refund(session, args["user"], args["charge_id"]) messages.append( {"role": "tool", "tool_call_id": call.id, "content": result} ) return message ``` > **CAREFUL: The session decides who is speaking, never the message** > > `session` comes from your authentication layer and is passed in. It must never > be a tool parameter the model fills in, or you have asked the model who it is > speaking for, and it can answer wrongly. This is exactly the case that failed > 0/5 in the comparison. Two more details that are load-bearing: **A refusal is a tool result, not an exception that kills the turn.** Handing the string back to the model lets it explain the refusal to the customer, which is what you want. What you must not do is let it retry the same call and succeed. **A read counts as an operation.** Disclosure leaves no trace in your database, so a test suite that only scores writes will call a leak a clean run. That is how leaks ship. ## With a raw tool loop No framework at all. Same four calls. ```python def run_tool(session, name, args): spec = GUARDED[name] # {"tool": fn, "requires": [...]} try: for fact, *fact_args in spec["requires"]: guard.require(fact, *[args[a] for a in fact_args]) except Ungrounded as e: return f"REFUSED by policy: {e}" out = spec["tool"](**args) for event, *event_args in spec["records"]: guard.record(event, *[args[a] for a in event_args]) return out ``` ## With LangChain ```python from langchain_core.tools import tool @tool def issue_refund(user: str, charge_id: str) -> str: """Refund one charge for a customer.""" try: guard.require("may_refund", user, charge_id) except Ungrounded: return "REFUSED by policy: the record does not support this refund." out = backend.refund(user, charge_id) guard.record("refunded", user, charge_id) guard.promise(user, "refunded", user, charge_id, before=("statement_closed", (user,))) return out ``` The full worked version, run with and without the guard over nine scenarios, is in `examples/langchain-agent`. ## Checking the model's words, not just its actions Tool calls are the easy half. The other half is what the agent *says*: ```python def answer_about_account(session, user, model_said_active: bool) -> str: guard.require("authorised", session, user) # entitled to ask at all guard.assert_answer("active", model_said_active, user) return "yes" if model_said_active else "no" ``` `assert_answer` raises `Ungrounded` when the model's yes or no disagrees with the log. It is McCarthy's first axiom, usable directly: **say only what is so.** ## Durability ```python guard = policy.guard(log="support.jsonl") ``` Nothing but events is written. The index and the commitment ledger are rebuilt by replaying them, so a process that died and came back is indistinguishable from one that never died, and a torn final line is dropped rather than guessed at. See [the past is the only state](https://elephlanguage.vercel.app/docs/concepts/past-is-state). ## Next - [**Modelling your domain**](https://elephlanguage.vercel.app/docs/use/modelling) — the part that is genuinely new thinking: turning the tables you have into events and facts. - [**Python API**](https://elephlanguage.vercel.app/docs/python-api) — every method, every exception. --- # With your coding assistant > An MCP server that proves your policy, a skill that carries the loop, and every page served as Markdown. For Claude Code, Cursor, Copilot and anything else that reads a URL. Source: https://elephlanguage.vercel.app/docs/use/with-your-assistant You are going to write the policy with a model's help. The risk in that is obvious: a model can produce a `.eleph` file that reads correctly and is wrong, which is the exact failure this language exists to catch. So the tooling here does not hand the model documentation and hope. It hands it the checker. ## The MCP server ```bash uvx --from "eleph[mcp]" eleph-mcp ``` Four tools. All stateless: text in, verdict out. Nothing is written to disk, nothing is fetched over the network. | Tool | What it answers | |---|---| | `eleph_check` | does every obligation hold, and if not, which history breaks it | | `eleph_obligations` | what does this file promise, without discharging it | | `eleph_simulate` | replay these events; what is true, and what would be refused | | `eleph_declarations` | what does this policy declare, with each fact expanded | ### Wiring it up by hand The [plugin below](#two-commands-in-claude-code) does this for you in Claude Code. Everywhere else: claude_desktop_config.json, .cursor/mcp.json, and most others ```json { "mcpServers": { "eleph": { "command": "uvx", "args": ["--from", "eleph[mcp]", "eleph-mcp"] } } } ``` The same four lines work in Claude Code, Claude Desktop, Cursor, Windsurf and Zed. `uvx` fetches into a throwaway environment, so nothing lands in your project or on your `PATH`. > **NOTE: The first run pulls about 51 MB** > > Almost none of that is eleph, which is 53 KB. It is Z3. You are installing a > theorem prover, and that is the whole point: fetching a page of documentation > would not have needed it. ### What the loop looks like > **you:** write a policy that only allows refunding a charge that fell after > cancellation The model writes one and calls `eleph_check`. It gets back not an opinion: ```out X question(C, refundable) linha 12 - resposta yes e verdadeira historico que quebra a obrigacao: 1. charged(U, C) 2. cancelled(U) o programa responde yes, a verdade do log e no ``` Two events. The model reads them and fixes the rule. **A counterexample is a thing a model can act on**, and it came from running the solver rather than from anybody's judgement. > **PROVED: Interrogate the rule, do not just get it to pass** > > `eleph_simulate` is the tool for the question a proof does not answer. A proof > says each obligation holds; it does not say the policy is the one you meant. > Replay the case you are worried about and see what the guard actually does. > > This is how the composition hole in the [LangChain > example](https://elephlanguage.vercel.app/docs/integration/langchain) was found: a policy that was `PROVADO` > before and after the fix. ## Two commands, in Claude Code The repository is a plugin marketplace, so there is no cloning and no copying files into place: Run them one at a time, inside Claude Code. First register the catalogue: ```text /plugin marketplace add dev-isaacmello/eleph ``` Wait for `Successfully added marketplace: eleph`, then install: ```text /plugin install eleph@eleph ``` > **CAREFUL: Two commands, not one line** > > Pasting both lines together makes the first one read the second as part of its > argument, and Claude Code answers `is not a valid GitHub owner/repo shorthand`. > Enter them separately. That installs **both** halves at once: the skill, and the MCP server above already wired up. Nothing to paste into a config file. ```text Component inventory Skills (1) eleph MCP servers (1) eleph Projected token cost Always-on: ~127 tok added to every session ``` `/plugin uninstall eleph@eleph` removes it. ### What the skill carries `plugins/eleph/skills/eleph/SKILL.md` is the procedure rather than the API surface: the loop above, the translation from the columns you already have into events and facts, the bare atom trap, and the limits that mean a rule cannot be expressed. Its first rule is the one that matters: **never hand over a `.eleph` file that has not been through the checker.** With the MCP server installed, it has the checker to hand. ### Editors without plugins The same file is plain Markdown and works as a rules file. Cursor reads `.cursor/rules/`, Copilot reads `.github/copilot-instructions.md`, and several tools now read `AGENTS.md`. Copy it where yours looks, and wire the MCP server with the JSON above. ## Every page as Markdown No install, works with anything that can fetch a URL. | | | |---|---| | [`/llms.txt`](https://elephlanguage.vercel.app/llms.txt) | the index, in reading order | | [`/llms-full.txt`](https://elephlanguage.vercel.app/llms-full.txt) | the whole English documentation in one file | | any page + `.md` | [`/docs/use/modelling.md`](https://elephlanguage.vercel.app/docs/use/modelling.md), and so on | All three languages: `/pt-BR/docs/….md`, `/zh-CN/docs/….md`. This is generated from the same walk that builds the search index and the sitemap, so the Markdown a model reads and the page you read cannot disagree. Point your assistant at `/llms.txt` and it can pick the page it needs instead of guessing at the API surface. ## Which of the three you want - **Just reading the docs?** The Markdown endpoints. Nothing to install. - **Writing policies with a model?** The MCP server. It is the only one that turns a guess into a proof. - **Using Claude Code every day?** Both, plus the skill, so you do not have to remember to ask for the check. ## Next - [**Start here**](https://elephlanguage.vercel.app/docs/use/start-here) — what eleph does and does not do. - [**Modelling your domain**](https://elephlanguage.vercel.app/docs/use/modelling) — the part the model cannot do for you. --- # Modelling your domain > Turning the tables you already have into events and facts, and choosing what to guard first. Source: https://elephlanguage.vercel.app/docs/use/modelling This is the only genuinely new thinking in adopting eleph. Everything else is four method calls. Here you take the tables you already have and ask a different question of them: not *what is the state*, but *what happened*. ## The translation Your database has a row per customer with columns on it. eleph has no columns. A fact is a question asked of the history, every time. | You have | You record | You ask | |---|---|---| | `users.active` (boolean) | `subscribed(u)`, `cancelled(u)` | `active(U) := subscribed(U) since_not cancelled(U)` | | `charges.refunded_at` (nullable) | `refunded(u, c)` | `refunded(U, C) since_not charged(U, C)` | | `sessions.user_id` | `authenticated(who, u)`, `logged_out(who, u)` | `authorised(Q, U) := authenticated(Q, U) since_not logged_out(Q, U)` | | `reservations` (a table) | `make_reservation(p, f)`, `cancel_reservation(p, f)` | `count P: Passenger where has_reservation(P, F) < 2` | | an `audit_log` beside the state | nothing extra | there is only the log; the state is derived | The last row is the one that changes how a system is argued about. In an ordinary design the audit log is a second artifact that is supposed to agree with the first. Here there is no first. ## The one rule for events > **PROVED: An event is something that happened, and it never un-happens** > > Never record a *state*. Record the *transition*. `set_active(u, false)` is a > column with extra steps; `cancelled(u)` is an event. > > If you find yourself wanting to record the same event twice to mean "still > true", you have modelled a state. Go back one step and find the thing that > changed. ## Put in the event what the event decides This is the trap that cost the worked example two runs, and it is worth the whole page. The first version of the refund rule read *"refundable = an open charge, and the customer is not active"*: ```eleph fact refundable(U, C) := charged(U, C) and not active(U) ``` Cancelling is permitted for an active customer. So: ```python guard.require("refundable", "ana", "c1") # Ungrounded, correctly guard.require("active", "ana") # permitted guard.record("cancelled", "ana") guard.require("refundable", "ana", "c1") # now it passes ``` **Two permitted actions compose into a forbidden outcome.** Cancel today, and a charge from three months ago becomes refundable. The model reached it on its own, occasionally, by reading "I cancelled last month" as a request to cancel. Both versions were proved for every history, before and after. > **CAREFUL: A proof says each obligation holds. It does not say the policy is the one you meant.** > > Writing the rule down does not hand you the right rule. It hands you a rule you > can interrogate, and interrogating it is what surfaced this. Without that, the > hole would have shipped with the word `PROVADO` next to it, which is the worst > combination available. The fix is the pattern for anything the language cannot work out for itself: **what makes a charge refundable is when it fell**, not the state of the account at the moment somebody asks. So the charge carries that in its own identity: ```eleph event charged_while_active(u: User, c: Charge, amount: Number) event charged_after_cancelling(u: User, c: Charge, amount: Number) fact refundable(U: User, C: Charge) := charged_after_cancelling(U, C, amount > 0) since_not refunded(U, C) ``` Two events instead of one, and the composition is gone. ## Time > **LIMIT: There is no wall clock** > > `since_not` knows **order**, not time. *"Refund within 24 hours of the charge"* > is not expressible directly. > > The pattern that works, and the one the τ-bench audit uses, is for your system > to emit the deadline as an event: > > ```python > guard.record("charged_after_cancelling", user, charge, amount) > guard.promise(user, "refunded", user, charge, > before=("refund_window_closed", (user, charge))) > > # ... your scheduler, 24 hours later > guard.record("refund_window_closed", user, charge) > ``` > > The clock lives outside the logic, which is how event-sourced systems handle > time anyway. ## Money and quantities A comparison in an argument position constrains a numeric field, **at the instant the event happens**: ```eleph fact within_limit(U: User, C: Charge) := charged_after_cancelling(U, C, amount <= 200) since_not refunded(U, C) ``` That is what keeps the [completeness argument](https://elephlanguage.vercel.app/docs/concepts/completeness) intact, and it is also the limit: you can ask whether *this charge* was over 200, not whether the sum of the last three was. **Aggregate arithmetic over the history is not expressible.** If you need a running total, compute it in your system and emit the conclusion as an event. ## Who is allowed to ask The failure that cost 0/5 in the comparison was not a lie. The agent reported a stranger's account truthfully. Every other obligation passed that run. ```eleph fact authorised(Q: Party, U: User) := authenticated(Q, U) since_not logged_out(Q, U) on question(Who, active(U)) permitted authorised(Who, U): answer Who with active(U) ``` Model authority as a fact about the log, like everything else. See [permission](https://elephlanguage.vercel.app/docs/concepts/permission), including what it deliberately is not: there are no roles, no hierarchy and no delegation. ## Where to start, concretely - **Pick the tool that would cost you most to get wrong.** Money out the door, data disclosed, something irreversible. Not the most frequent one. - **Write down the sentence your team already says about it.** *"We only refund a charge that fell after cancellation, has not been refunded, and is under R$ 200."* If nobody can say that sentence, that is your finding, and it is worth more than the integration. - **Turn each clause into an event or a fact.** Three clauses, three facts. The table at the top of this page is the whole translation. - **Run `eleph check`.** If it does not prove, the rule contradicts itself and you have learned something before writing any Python. - **Run it as an observer over yesterday's traffic.** Record what happened, ask the facts what was true, and see whether it ever disagrees with what your agent did. It enforces nothing, so it cannot break anything. - **Then turn on `require` for that one tool.** Add the next one when the first is boring. ## Reading the proof ```out $ eleph check support.eleph 8 eventos, 5 fatos, 2 handlers 2 obrigacoes derivadas do texto do programa cada uma checada no seu limiar de completude (o maior: 6 eventos) -- exaustivo PROVADO - 2 obrigacoes valem para TODO historico, de qualquer tamanho ``` `PROVADO` means every obligation holds for **every** history, of any length, not just the ones you thought to test. If you see `SEM CONTRAEXEMPLO` instead, the run was not exhaustive and the tool is telling you so. The difference is on [proof, not spot check](https://elephlanguage.vercel.app/docs/concepts/completeness). ## Next - [**Python API**](https://elephlanguage.vercel.app/docs/python-api) — every method and exception. - [**Temporal expressions**](https://elephlanguage.vercel.app/docs/reference/expressions) — for when `since_not` and `count` are not enough. - [**Honest limits**](https://elephlanguage.vercel.app/docs/limits) — verified, and worth reading before you commit to this. --- # What eleph is > A language whose programs cannot lie — speech acts, a history that is the only state, and correctness conditions derived from the program text. Source: https://elephlanguage.vercel.app/docs eleph is a programming language for the part of a system that speaks. It has speech acts instead of print statements, a history instead of variables, and correctness conditions that are read off the program rather than written beside it. It implements and extends **Elephant 2000**, a language specified by John McCarthy at Stanford on 6 November 1998 and never implemented by him. The design is his. The completeness thresholds, the commitment obligations, the incremental runtime and the embeddable API are this project's. ## The problem it was built for An agent asserts things about a customer's record, and it promises to do things. Today nothing connects either to reality. Output filters check the text. Nothing checks whether an assertion follows from what actually happened, and nothing tracks whether a promise was ever kept. McCarthy's answer, written before the problem existed: make the program say only what its own history supports, and make its promises debts it has to settle. Two obligations, both his: * **An answer must be true.** Every `yes` or `no` must be entailed by the log. * **A promise must be kept.** The program cannot promise what its history does not establish, nor promise what no path through it could ever bring about. You do not write these conditions. The compiler reads them off the program. ```out $ eleph obligations examples/airline_buggy.eleph linha 17 question(Caller, has_reservation) resposta yes e verdadeira supondo alguma vez make_reservation(P, F) entao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) ``` Then it tries to break them. > **NOTE: The CLI speaks Portuguese** > > `eleph` prints in Portuguese. That is the author's language and the output is > part of the artifact, so this site quotes it verbatim rather than translating > it into something you could not reproduce. Every terminal block on this site is > a real run. ## What it is not It is not a prompt technique, an output filter, or a policy engine you configure. It is a small language with a verifier, plus a library you can put under an existing Python system without adopting the language at all. It is also not finished. The [honest limits](https://elephlanguage.vercel.app/docs/limits) page is verified and not hedging: there is no wall clock, aggregates over the history are not expressible, facts cannot be recursive, and the two theorems are proved on paper and tested rather than mechanised. ## Where to go next > **NOTE: If you already have an agent in production** > > Skip this section. [Start here](https://elephlanguage.vercel.app/docs/use/start-here) is written for you: what > the guard does, what it does not do (it will not reduce your token bill), and > which of the three integration shapes is yours. Two of the three need none of > the language below. - **[Install it](https://elephlanguage.vercel.app/docs/installation)** — one `pip install`, one dependency (Z3). - **[Run the quickstart](https://elephlanguage.vercel.app/docs/quickstart)** — derive the obligations of a nine-line program, then watch the checker produce a history that breaks it. - **[Read McCarthy's bug](https://elephlanguage.vercel.app/docs/the-mccarthy-bug)** — the one-word difference the whole language exists to expose. - **[Embed it](https://elephlanguage.vercel.app/docs/python-api)** — three integration shapes, cheapest first, with no language adoption required for the first two. ## How this documentation is organised | Section | What it answers | |---|---| | [Use it in your agent](https://elephlanguage.vercel.app/docs/use/start-here) | You already ship an agent and want the guard under it, without adopting the language | | [Concepts](https://elephlanguage.vercel.app/docs/concepts/past-is-state) | Why the language is shaped this way, and what each guarantee actually says | | [Language reference](https://elephlanguage.vercel.app/docs/reference/program-structure) | Every form in the grammar, and what each one means | | [Tooling](https://elephlanguage.vercel.app/docs/cli) | The five commands, and the Python API | | [In practice](https://elephlanguage.vercel.app/docs/integration/langchain) | The measured experiments: an agent comparison, throughput, a benchmark audit | | [Project](https://elephlanguage.vercel.app/docs/limits) | Limits, changelog, and how to contribute | --- # Installation > Install eleph from PyPI or from source. Requires Python 3.11 or newer and Z3. Source: https://elephlanguage.vercel.app/docs/installation eleph is a Python package with a single runtime dependency: the Z3 theorem prover, which is what discharges the obligations. ## Requirements | | | |---|---| | Python | 3.11, 3.12 or 3.13 | | Dependency | `z3-solver >= 4.12` | | Licence | MIT | Python 3.11 is the floor and is tested in CI on every push, alongside 3.12 and 3.13. ## Into a project ```bash uv add eleph # or: pip install eleph ``` That installs the importable package and the `eleph` command. > **CAREFUL: uv add does not put eleph on your PATH** > > `uv add` installs into the project's `.venv`, so the executable lands in > `.venv/bin/eleph` and the shell will not find it: > > ```bash > $ eleph check policy.eleph > zsh: command not found: eleph > ``` > > Reach it through the environment that has it: > > ```bash > uv run eleph check policy.eleph # no activation needed > ``` > > or activate the environment first: > > ```bash > source .venv/bin/activate > eleph check policy.eleph > ``` ## As a command, everywhere If what you want is the CLI rather than a library in one project, install it as a tool. It gets its own isolated environment and goes on your PATH: ```bash uv tool install eleph ``` ```bash $ command -v eleph ~/.local/bin/eleph ``` `uv tool uninstall eleph` removes it. With pip, the equivalent is [`pipx`](https://pipx.pypa.io/): `pipx install eleph`. ## Optional extras Three extras exist, and none is needed for the language or the verifier. | Extra | Adds | Needed for | |---|---|---| | `mcp` | `mcp >= 2.0` | the MCP server, `eleph-mcp`. See [with your coding assistant](https://elephlanguage.vercel.app/docs/use/with-your-assistant) | | `claude` | `anthropic >= 0.40` | the natural language front end used by `eleph talk --claude` | | `langchain` | `langchain`, `langchain-anthropic`, `langgraph` (all `>= 1.0`) | the worked agent comparison in `examples/langchain-agent` | ```bash uv pip install "eleph[mcp]" uv pip install "eleph[claude]" uv pip install "eleph[langchain]" ``` ## Check that it works Write a file. Nine lines is enough to have something proved: ```bash cat > airline.eleph <<'EOF' program airline event make_reservation(passenger, flight) event cancel_reservation(passenger, flight) fact has_reservation(P, F) := make_reservation(P, F) since_not cancel_reservation(P, F) on question(Caller, has_reservation(P, F)): answer Caller with has_reservation(P, F) EOF eleph check airline.eleph ``` If the install is good, Z3 discharged the obligation and you will see: ```out airline.eleph -> programa airline 2 eventos, 1 fato, 1 handler 1 obrigacao derivada do texto do programa cada uma checada no seu limiar de completude (o maior: 3 eventos) -- exaustivo ok question(Caller, has_reservation) linha 9 - a resposta responde a pergunta feita PROVADO - 1 obrigacao vale para TODO historico, de qualquer tamanho ``` > **CAREFUL: The examples are not in the package** > > Nothing under `examples/` or `bench/` is installed by `pip install` or > `uv add`. Only the `eleph` package is: > > ```bash > $ find .venv -name "*.eleph" > $ # nothing > ``` > > So `eleph check examples/airline.eleph` after a PyPI install fails, and today > it fails with a Python traceback rather than a message. **Every page on this > site that names a path under `examples/` assumes you cloned the repository.** ## For the examples, clone the repository The quickstart, the concept pages and the CLI reference all quote runs against files in the repository. To reproduce them: ```bash git clone https://github.com/dev-isaacmello/eleph && cd eleph uv venv && uv pip install -e ".[dev]" source .venv/bin/activate eleph check examples/airline.eleph ``` ```out examples/airline.eleph -> programa airline 3 eventos, 1 fato, 1 handler 2 obrigacoes derivadas do texto do programa cada uma checada no seu limiar de completude (o maior: 3 eventos) -- exaustivo ok question(Caller, has_reservation) linha 16 - resposta yes e verdadeira ok question(Caller, has_reservation) linha 18 - resposta no e verdadeira PROVADO - 2 obrigacoes valem para TODO historico, de qualquer tamanho ``` The τ-bench audit additionally downloads about 6 MB of published trajectories on first use, and skips cleanly with no network. --- # Quickstart > Derive the correctness conditions of a nine-line program, break it, fix it, then run a dialogue against it. Source: https://elephlanguage.vercel.app/docs/quickstart Five minutes, four commands, and one program that lies. By the end you will have seen the checker produce a history that breaks an obligation nobody wrote down. > **NOTE: These commands run against the repository** > > Every path below is a file in the eleph repository, and nothing under > `examples/` is installed by `pip install` or `uv add`. Clone it first: > > ```bash > git clone https://github.com/dev-isaacmello/eleph && cd eleph > uv venv && uv pip install -e ".[dev]" > source .venv/bin/activate > ``` > > If you would rather stay in your own project, the programs on this page are > printed in full: save one to a file of your own and drop the `examples/` > prefix. See [installation](https://elephlanguage.vercel.app/docs/installation). ## 1. The program examples/airline_buggy.eleph ```eleph program airline event make_reservation(passenger, flight) event cancel_reservation(passenger, flight) event board(passenger, flight) fact has_reservation(P, F) := make_reservation(P, F) since_not cancel_reservation(P, F) on question(Caller, has_reservation(P, F)): if make_reservation(P, F): answer Caller yes else: answer Caller no ``` There is no assertion here, no contract, no test. There is a declaration of what can happen, a definition of what `has_reservation` means, and a handler that answers a question. ## 2. Ask what the text demands ```bash eleph obligations examples/airline_buggy.eleph ``` ```out examples/airline_buggy.eleph: condicoes que o proprio texto do programa exige linha 17 question(Caller, has_reservation) resposta yes e verdadeira supondo alguma vez make_reservation(P, F) entao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) linha 19 question(Caller, has_reservation) resposta no e verdadeira supondo nao alguma vez make_reservation(P, F) entao nao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) ``` Read the first one out loud: *on the path where the program says yes, what makes yes true?* The `supondo` line is the path condition — the branch it took to get there. The `entao` line is what saying `yes` claims. Nobody wrote either. Both were read off the program. ## 3. Try to break them ```bash eleph check examples/airline_buggy.eleph ``` ```out examples/airline_buggy.eleph -> programa airline 3 eventos, 1 fato, 1 handler 2 obrigacoes derivadas do texto do programa cada uma checada no seu limiar de completude (o maior: 3 eventos) -- exaustivo X question(Caller, has_reservation) linha 17 - resposta yes e verdadeira neste caminho o programa afirma que vale (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) historico que quebra a obrigacao: 1. make_reservation(P, F) 2. cancel_reservation(P, F) 3. disse-ask-sobre-has_reservation(Caller, P, F) <- fala, registrada porque o elefante nao esquece o programa responde yes, a verdade do log e no ok question(Caller, has_reservation) linha 19 - resposta no e verdadeira REPROVADO - 1 obrigacao nao cumprida ``` The counterexample is a history, not a failing assertion: book, then cancel, then ask. The program answers `yes`; the log says `no`. Notice the third event. The question itself is recorded, because the program's own speech goes into the same log as everything else. ## 4. The fix is one word the same program, correct ```eleph on question(Caller, has_reservation(P, F)): if make_reservation(P, F) since_not cancel_reservation(P, F): answer Caller yes else: answer Caller no ``` ```out $ eleph check examples/airline.eleph ok question(Caller, has_reservation) linha 16 - resposta yes e verdadeira ok question(Caller, has_reservation) linha 18 - resposta no e verdadeira PROVADO - 2 obrigacoes valem para TODO historico, de qualquer tamanho ``` > **PROVED** > > `PROVADO` is stronger than "the tests pass". Each obligation was checked at its > own [completeness threshold](https://elephlanguage.vercel.app/docs/concepts/completeness), which makes "no > counterexample found" mean "no counterexample exists" — for every history, of > any length. ## 5. Run a real dialogue A larger program with capacity limits, seats and commitments: ```bash eleph run examples/companhia.eleph examples/voo.session --log /tmp/voo.jsonl ``` ```out alice: request make_reservation(alice, ba117) [log] make_reservation(alice, ba117) programa: aceito programa: prometo, e ja esta feito programa: prometo -- a alice: (assign_seat(alice, ba117) e desde entao nenhum cancel_reservation(alice, ba117)) (antes de board(alice, ba117)) carla: request make_reservation(carla, ba117) programa: recuso [log] board(bruno, ba117) (historico pre-existente) [livro] QUEBRADA -- a bruno: (assign_seat(bruno, ba117) e desde entao nenhum cancel_reservation(bruno, ba117)) (antes de board(bruno, ba117)) livro de compromissos CUMPRIDA a alice: ... QUEBRADA a bruno: ... log: 22 eventos (4 do mundo, 18 de fala) 1 promessa quebrada ``` Carla is declined because the flight holds two. Bruno boarded without a seat, so the deadline on his promise passed and the ledger says so. Nothing about that ledger is stored: it is recomputed from the events. ```bash eleph ledger examples/companhia.eleph /tmp/voo.jsonl ``` ## Where to go next - **[McCarthy's bug](https://elephlanguage.vercel.app/docs/the-mccarthy-bug)** — the full story of why `make_reservation` and `has_reservation` are different questions. - **[The past is the only state](https://elephlanguage.vercel.app/docs/concepts/past-is-state)** — what replaces variables, and why that is the point rather than a restriction. - **[Python API](https://elephlanguage.vercel.app/docs/python-api)** — putting the same rules under an existing system without writing any `.eleph` handlers. --- # McCarthy's bug > The one-word difference between "did they make a reservation" and "do they have one", and why the whole language exists to expose it. Source: https://elephlanguage.vercel.app/docs/the-mccarthy-bug The example is McCarthy's own, and it is nine lines long. A support program is asked whether a passenger has a reservation. It answers by checking whether the passenger made one. Those are different questions, and the difference is the cancellation. ## The trap is in the grammar, deliberately In eleph, a bare event atom means *this happened at least once, ever*: ```eleph make_reservation(P, F) # ever happened ``` It reads like "has a reservation". It means "made a reservation". The two agree right up until someone cancels, and then they never agree again. This is not an accident of syntax that a better keyword would fix. It is the shape of the mistake real systems make: a boolean column called `has_reservation` that someone forgot to clear, a cached flag, a summary that drifted. The language keeps the trap open on purpose and puts a verifier next to it. ## What the verifier does with it Given the buggy handler, `eleph check` reports: ```out X question(Caller, has_reservation) linha 17 - resposta yes e verdadeira historico que quebra a obrigacao: 1. make_reservation(P, F) 2. cancel_reservation(P, F) 3. disse-ask-sobre-has_reservation(Caller, P, F) o programa responde yes, a verdade do log e no ``` Three things in that output are worth separating. **It is a history, not a stack trace.** The counterexample is a sequence of events that any deployment could produce. You can read it to a colleague. **The third event is the question itself.** The program's own speech acts go into the same log as the world's events. That is what makes `spoke` queryable later, and it is why the elephant never forgets. **The last line names both sides.** `o programa responde yes, a verdade do log e no` — what the program said, and what the history entails. The obligation is the gap between them. ## Why a test would not have found it A test for this bug requires someone to have thought of cancellation. That is the whole difficulty: the bug is invisible precisely to the person who wrote it, because they read `make_reservation(P, F)` and heard "has a reservation". The obligation is not something anyone thought of either. It was derived: ```out linha 17 question(Caller, has_reservation) resposta yes e verdadeira supondo alguma vez make_reservation(P, F) entao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) ``` `supondo` is the path condition — the branch the program took. `entao` is what answering `yes` to *that question* claims. The obligation is that the first implies the second, and Z3 is asked whether any history makes the first true and the second false. ## The fix, and what it costs ```eleph on question(Caller, has_reservation(P, F)): if make_reservation(P, F) since_not cancel_reservation(P, F): answer Caller yes else: answer Caller no ``` The guard is now the fact's own definition, so there is nothing left to disagree. Better still, say it once: ```eleph on question(Caller, has_reservation(P, F)): answer Caller with has_reservation(P, F) ``` `answer C with φ` answers whichever way the log says, which is the form that cannot be got wrong. The verifier accepts both. > **PROVED** > > ```out > $ eleph check examples/airline.eleph > > ok question(Caller, has_reservation) linha 16 - resposta yes e verdadeira > ok question(Caller, has_reservation) linha 18 - resposta no e verdadeira > > PROVADO - 2 obrigacoes valem para TODO historico, de qualquer tamanho > ``` ## A bug that hides deeper One event's distance is easy. `examples/fundo.eleph` is the same shape of mistake at a distance of seven: examples/fundo.eleph ```eleph program milhagem sort Passenger sort Flight event make_reservation(p: Passenger, f: Flight) fact elite(P: Passenger, F: Flight) := count make_reservation(P, F) >= 8 on question(C, elite(P, F)): if count make_reservation(P, F) >= 7: answer C yes else: answer C no ``` Seven is not eight. A bounded search that stops at six histories **approves it**: ```out $ eleph check examples/fundo.eleph --bound 6 ok? question(C, elite) linha 11 - resposta yes e verdadeira ok? question(C, elite) linha 13 - resposta no e verdadeira SEM CONTRAEXEMPLO - dentro dos limites checados, que nao sao exaustivos aqui ``` The `ok?` and the verdict both say the run was not exhaustive. Left to compute its own threshold, the checker finds it: ```out $ eleph check examples/fundo.eleph X question(C, elite) linha 11 - resposta yes e verdadeira historico que quebra a obrigacao: 1..7. make_reservation(P, F) 8. disse-ask-sobre-elite(C, P, F) REPROVADO - 1 obrigacao nao cumprida ``` This is why the checker computes a [completeness threshold](https://elephlanguage.vercel.app/docs/concepts/completeness) per obligation instead of taking a fixed bound. A fixed bound of six was the behaviour in 0.1.0, and it was unsound. --- # The past is the only state > There is no assignment in the eleph grammar. A fact is not stored, it is a query over what happened. Source: https://elephlanguage.vercel.app/docs/concepts/past-is-state There is no assignment in the grammar. This is not an omission. There is nothing to assign to, because a fact is not stored — it is a query over what happened. ## A fact is a formula ```eleph fact has_reservation(P: Passenger, F: Flight) := make_reservation(P, F) since_not cancel_reservation(P, F) ``` `has_reservation` is not a column, a cache, or a field on an object. It is the sentence *"there is a `make_reservation` after the last `cancel_reservation`"*, evaluated against the log whenever anyone asks. Nothing is overwritten, so nothing can drift out of agreement with the truth. The classic failure — a boolean flag someone forgot to clear — has no shape it could take here. ## Everything the program says is also an event The program's own utterances go into the same log as the world's events, so it can be asked what it has already said: ```eleph if spoke accept to C about make_reservation(P, F): decline C ``` This is why the counterexamples that `eleph check` prints include lines like `disse-ask-sobre-has_reservation(Caller, P, F)`. A question was asked, so the asking happened, so it is in the history. `spoke` names the exchange and the act, not the propositional content — see [the limits](https://elephlanguage.vercel.app/docs/limits) for exactly what that does and does not let you ask. ## What replaces the things you gave up | You would have written | You write instead | |---|---| | `user.active = False` | `record cancelled(u)` | | `if user.active:` | `if subscribed(U) since_not cancelled(U):` | | a `reservations` table | `count P: Passenger where has_reservation(P, F)` | | a `promised_at` column | `promise C that φ before e(...)`, and read the ledger | | an audit log written beside the state | there is only the log; the state is derived | The last row is the one that changes how a system is argued about. In an ordinary design the audit log is a second artifact that is supposed to agree with the first. Here there is no first. ## Durability comes for free Nothing but events is written to disk. The index and the commitment ledger are rebuilt by living through the past again, so a process that died and came back is indistinguishable from one that never died. ```python g = policy.guard(log="booking.jsonl") # reopening replays ``` A torn final line is dropped: an event that was never finished being written is an event that did not happen. ## The objection, and the answer If the only state is the past, then answering a question means reading the past, which is quadratic. It showed: at four thousand interactions an early version ran at 46 events per second. The answer is that every operator here has a one-step recurrence, and one lemma makes it sharp — *an event matching none of a subformula's atoms cannot change its value*. Folding an event in touches only the keys that event names. Measured at 145,564 events in 6.1 seconds with flat throughput. The full argument and the numbers are on the [performance page](https://elephlanguage.vercel.app/docs/performance). > **PROVED: The optimisation is never trusted** > > Every cell of the index is a pure function of the log — the same function the > naive evaluator computes by rereading it. That is an optimisation of a truth > claim, so `Machine(audit=True)` answers every query **both** ways and raises if > they differ. --- # Obligations, derived > Ten correctness conditions read off the program text, discharged by Z3 or structurally by the compiler. Nobody writes them. Source: https://elephlanguage.vercel.app/docs/concepts/obligations An obligation is a correctness condition that the program's own text demands. You do not write it, annotate it, or configure it. The compiler reads it off the handler, and then the checker tries to break it. ## The shape of one Every derived obligation has the same three parts: | Part | What it is | |---|---| | **assumptions** (`supondo`) | the path condition — the branch the program took to reach this statement | | **goal** (`entao`) | what performing that speech act claims about the log | | **polarity** | whether the goal must hold on every such history, or on at least one | Printed: ```out linha 17 question(Caller, has_reservation) resposta yes e verdadeira supondo alguma vez make_reservation(P, F) entao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) ``` Read as: *on the path where `make_reservation(P, F)` ever happened, answering `yes` claims that a reservation currently stands.* Z3 is asked whether any history makes the assumption true and the goal false. Use `eleph obligations ` to see them without discharging them. That command exists to make one point: **nobody wrote these.** ## The ten | Obligation | Checked by | |---|---| | answer is true | Z3, at the completeness threshold | | answer responds to the question asked | Z3 | | immediate promise holds when made | Z3, over the log plus what the handler just recorded | | future promise is one some path can bring about | Z3, requiring the path to turn it from false to true | | argument sorts agree with declarations | compiler, on every fact, used or not | | an offer is one some path could honour | Z3 | | no door onto a protected subject is left unlocked | structural | | every path answers exactly once | structural | | every request is accepted or declined exactly once | structural | | outstanding and breached commitments | runtime ledger | The last one is the only one that is not static. A promise about the future cannot be discharged before the future arrives, so the runtime keeps a ledger and reports what is outstanding and what was breached. ## Three of them, in more detail ### Answer is true McCarthy's first axiom. Every `answer C yes`, `answer C no` and `answer C with φ` must be entailed by the log at the moment it is said. This is the one the [McCarthy bug](https://elephlanguage.vercel.app/docs/the-mccarthy-bug) violates. ### Immediate promise holds when made `promise C that φ` claims that φ is true *now*, and the check runs over the log plus whatever the handler recorded on the way here: ```eleph on request(Caller, make_reservation(P, F)): if has_reservation(P, F): decline Caller else: record make_reservation(P, F) accept Caller promise Caller that has_reservation(P, F) ``` The promise is only provable because `record` came first in that same handler. Move the `record` after the `promise` and the obligation fails. ### Future promise is keepable `promise C eventually φ` and `promise C that φ before e(...)` cannot be true when said — that is what makes them future promises. What the compiler proves instead is that *some path through this program establishes φ*, and it requires that path to turn φ from false to true: ```out ok request(C, make_reservation) linha 46 - a promessa pode vir a ser cumprida (antes de board(P, F)) cumprivel por: request assign_seat > entao l51 ``` The trace names the path. An earlier version of this check accepted any satisfiable formula, which made it vacuous; that was fixed in 0.2.0. > **LIMIT: Keepability is not liveness** > > The compiler proves a path exists. It cannot prove the caller will walk it, > because no program can. What happens if they do not is the ledger's business. ## Structural defects Three of the ten never reach the solver. They are properties of the program's shape: * **Every path answers exactly once.** A `question` handler with a branch that says nothing, or one that answers twice, is a defect. * **Every request is accepted or declined exactly once.** Same argument for `request`. * **No unguarded door.** One handler on a subject requiring `permitted` and its neighbour on the same subject requiring none is a locked front door beside an open window. Added in 0.3.0; see [permission](https://elephlanguage.vercel.app/docs/concepts/permission). Structural defects are reported before the solver runs and are counted as failures: ```out X question(Quem, saldo) linha 22 outro handler sobre este assunto exige permissao e este nao ``` ## Where they come from Derivation lives in `eleph/obligations.py`, and discharge in `eleph/verify.py`. The soundness claim connecting the two — *if every obligation is proved, the runtime never refuses* — is tested by hammering proved programs with random pasts and random conversations in `tests/test_soundness.py`. --- # Proof, not spot check > A computable completeness threshold turns "no counterexample up to N" into "no counterexample exists". Source: https://elephlanguage.vercel.app/docs/concepts/completeness Bounded model checking answers a weaker question than we want: no history *up to length N* breaks the obligation. For this language's fragment that gap closes, because a computable threshold makes "no counterexample found" mean "none exists". ## Why a fixed bound is not enough `examples/fundo.eleph` claims elite status at seven bookings when the fact requires eight. A bound of six approves it: ```out $ eleph check examples/fundo.eleph --bound 6 ok? question(C, elite) linha 11 - resposta yes e verdadeira ok? question(C, elite) linha 13 - resposta no e verdadeira SEM CONTRAEXEMPLO - dentro dos limites checados, que nao sao exaustivos aqui ``` Note the vocabulary. `ok?` rather than `ok`, and `SEM CONTRAEXEMPLO` rather than `PROVADO`. The tool never claims more than it checked. A fixed bound of six was the behaviour in 0.1.0, and it was unsound — this example is the reason it changed. ## The last-occurrence lemma The truth of a formula at the end of a history depends only on **the order of the last occurrence of each atom**, plus, for atoms under a `count`, how many times they occurred, capped at *n*+1. Read the operators and it is almost immediate: | Operator | What it actually asks of the history | |---|---| | `a(x)` | does a last occurrence of `a(x)` exist | | `a since_not b` | does `a`'s last occurrence exist and come after `b`'s | | `count a >= n` | how many occurrences, saturating at *n*+1 | The boolean connectives compose, and a quantifier is a finite disjunction or sum of instances that are themselves in the fragment. ## The threshold Any configuration the lemma admits is realised by a history with one position per atom, so ```text N = sum over DISTINCT atoms a of k(a), k(a) = 1, or n_max(a)+1 under a count ``` is a completeness threshold. Unsatisfiability up to `N` is unsatisfiability outright. Two details matter for it being usable rather than merely correct. **The sum runs over distinct atoms, not syntax nodes.** `once(a) and count(a) > 2` asks for one occurrence and for three; three occurrences answer both. Counting per node is still a valid threshold, just a needlessly large one — and large thresholds are what make an exhaustive run unaffordable. Making this change in 0.2.0 cut thresholds roughly threefold and made the suite faster. **The domain is bounded too.** An object with no occurrence in the history falsifies every atom naming it, so quantifying over the objects that appear is the same as quantifying over an unbounded universe. `W` distinct objects suffice: one witness per existential, *n*+1 per counting quantifier, plus the obligation's own free variables. Each obligation is checked at **its own** threshold, so one expensive fact does not slow down the rest of the file: ```out 6 obrigacoes derivadas do texto do programa cada uma checada no seu limiar de completude (o maior: 10 eventos) -- exaustivo PROVADO - 6 obrigacoes valem para TODO historico, de qualquer tamanho ``` ## Outside the linear fragment The hypothesis that can fail is that every `since_not` takes **atoms**. A fact whose body puts a compound expression there leaves the fragment. That case does not lose completeness, only its linear bound. Every past operator has a one-step recurrence — `once` and `since_not` each carry one bit, `count` a counter saturating at *n*+1 — so a formula with *k* temporal subformulas is evaluated by a deterministic monitor over ```text S = 2^k × product of (n_i + 2) ``` states. If some history reaches a violating state, one does so without repeating a state, hence in fewer than `S` steps. So `S` is a completeness threshold for the whole language. Quantifiers multiply *k* by the domain size, since an instance per object is tracked. That is exponential in principle and small in practice. > **LIMIT: When even that is unaffordable** > > Past a ceiling of 4096, an exhaustive run is not worth the wait. The checker > then says the run was not exhaustive rather than pretending, and marks each > affected obligation with the reason: > > ```out > verificacao NAO exaustiva neste programa > linha 11: limite pedido abaixo do limiar > ``` ## The vocabulary, exactly | Verdict | What it means | |---|---| | `PROVADO` | every obligation holds for **every** history, of any length | | `SEM CONTRAEXEMPLO` | nothing broke within the bounds checked, which were not exhaustive here | | `REPROVADO` | at least one obligation has a counterexample, printed as a history | | `ok` | this obligation was discharged at its completeness threshold | | `ok?` | this obligation survived the bound it was given, which was below its threshold | ## Testing the claim itself The threshold is a claim like any other, so there is an experiment that would break it: **no verdict may change above the computed threshold.** It is tested by re-checking every obligation of every example at bounds and domains above it, in `tests/test_soundness.py`. The full argument, with proofs, is the module docstring of `eleph/threshold.py`. The two theorems are proved on paper and tested rather than mechanised; a Lean 4 artifact for the ground fragment is the next thing worth building, and is [where help is wanted](https://elephlanguage.vercel.app/docs/contributing). --- # Commitments > Four strengths of commitment, a static keepability check, and a ledger that is derived from the log rather than stored. Source: https://elephlanguage.vercel.app/docs/concepts/commitments A promise here is not text. It is a construct of the language, it carries an obligation the compiler checks, and what is still owed is derived from the log rather than kept in a table beside it. ## Four strengths | Form | What it claims | Checked how | |---|---|---| | `offer C that φ` | willing, not yet owing — nobody has taken it up | some path could honour φ | | `promise C that φ` | φ is **true now** | Z3, over the log plus what this handler just recorded | | `promise C eventually φ` | φ will hold at some point | some path turns φ from false to true | | `promise C that φ before e(...)` | φ will hold before `e` occurs | same, plus the runtime watches for `e` | An offer is the weakest thing the language can say, and it is deliberately separate from a promise: what it owes is only that it is not empty. Added in 0.3.0. ## The immediate promise ```eleph on request(Caller, make_reservation(P, F)): if has_reservation(P, F): decline Caller else: record make_reservation(P, F) accept Caller promise Caller that has_reservation(P, F) ``` `promise C that φ` claims φ holds at the instant it is said, so the obligation is discharged over the log **plus whatever this handler recorded on the way here**. The promise above is provable only because `record` came first. Swap the two lines and the check fails. ```out ok request(C, make_reservation) linha 45 - a promessa esta cumprida ao ser feita ``` ## The future promise ```eleph promise C that has_seat(P, F) before board(P, F) ``` This cannot be true when said — that is what makes it a future promise. The compiler proves instead that **some path through this program establishes it**, and requires that path to turn it from false to true: ```out ok request(C, make_reservation) linha 46 - a promessa pode vir a ser cumprida (antes de board(P, F)) cumprivel por: request assign_seat > entao l51 ``` The trace names the path — here, the `assign_seat` request handler. > **LIMIT: Keepable, not live** > > The compiler proves a path exists. It cannot prove the caller will walk it, > because no program can. What happens when they do not is exactly what the > ledger is for. ## The ledger A commitment has four states: | Status | Meaning | |---|---| | `ABERTA` | outstanding — made and not yet settled | | `CUMPRIDA` | kept | | `QUEBRADA` | breached — the deadline event occurred with the promise still false | | `LIBERADA` | released — the program was let off the debt by `release C from φ` | Run the airline against a session where one passenger gets a seat and another boards without one: ```out $ eleph run examples/companhia.eleph examples/voo.session --log /tmp/voo.jsonl alice: request assign_seat(alice, ba117) [log] assign_seat(alice, ba117) [livro] cumprida -- a alice: (assign_seat(alice, ba117) e desde entao nenhum cancel_reservation(alice, ba117)) (antes de board(alice, ba117)) programa: aceito [log] board(bruno, ba117) (historico pre-existente) [livro] QUEBRADA -- a bruno: (assign_seat(bruno, ba117) e desde entao nenhum cancel_reservation(bruno, ba117)) (antes de board(bruno, ba117)) livro de compromissos CUMPRIDA a alice: ... QUEBRADA a bruno: ... 1 promessa quebrada ``` Bruno's promise was breached by an event, not by a timer. `since_not` knows order, not time — see [the limits](https://elephlanguage.vercel.app/docs/limits). ## The ledger is derived, not stored Commitments are recorded as events. The ledger is recomputed by replaying them, which is why reopening a log gives back the same debts: ```bash eleph ledger examples/companhia.eleph /tmp/voo.jsonl ``` ```out /tmp/voo.jsonl 22 eventos (4 do mundo, 18 de fala) CUMPRIDA a alice: ... QUEBRADA a bruno: ... 1 promessa quebrada ``` Whether a debt was kept, broken or released **follows from the events that came after it**, so it is recomputed rather than snapshotted. There is no state that could disagree with the history. ## Releasing a debt ```eleph on request(C, cancel_reservation(P, F)): if has_reservation(P, F): record cancel_reservation(P, F) accept C promise C that not has_reservation(P, F) release C from has_seat(P, F) else: decline C ``` Cancelling makes the seat promise unkeepable, so the program lets itself off it explicitly. `release` is a speech act like any other and goes into the log; a debt quietly dropped and a debt formally released are different histories. ## From Python The same four strengths are available without writing handlers: ```python g.promise("alice", "has_seat", "alice", "ba117", before=("board", ("alice", "ba117"))) g.outstanding() # [Commitment(...)] what is still owed, to whom g.breached() # [Commitment(...)] what was not kept g.release("alice", "has_seat", "alice", "ba117") g.ledger # every commitment, with its status ``` See the [Python API](https://elephlanguage.vercel.app/docs/python-api). --- # Permission > McCarthy's eighth speech act. Not whether an answer is true, but whether this party was entitled to ask. Source: https://elephlanguage.vercel.app/docs/concepts/permission A support agent that truthfully reports any customer's balance to whoever asks has told no lie at all. Every other obligation in this language would pass it. It is still an incident. ## The eighth speech act McCarthy listed authority among the speech acts a program performs, and it is the one an ordinary review never asks about. In eleph a handler may be gated on it: ```eleph on question(Quem, saldo(C)) permitted pode_perguntar(Quem, C): answer Quem with saldo(C) ``` `permitted` takes a fact, so authority is something the **log** supports, not something a configuration file asserts: ```eleph fact autorizado(Q: Party, U: User) := autenticou(Q, U) since_not deslogou(Q, U) ``` Someone is authorised for an account if they authenticated for it and have not logged out since. That is a formula about what happened, checkable the same way everything else here is. ## It joins the path condition The important design decision is that permission is **not** a separate check run to one side. It becomes part of the assumptions of every obligation derived from that handler, so answers are proved *under* it: ```out ok question(Quem, active) linha 55 - a resposta responde a pergunta feita ok question(Quem, may_refund) linha 58 - a resposta responde a pergunta feita ok question(Quem, needs_escalation) linha 61 - a resposta responde a pergunta feita PROVADO - 3 obrigacoes valem para TODO historico, de qualquer tamanho ``` A handler whose answer is only correct for an authorised caller is provable; the same handler without the gate is not the same program. ## It fails closed At run time, a handler whose permission does not hold raises `NotPermitted` rather than answering. The asymmetry is deliberate: > An answer withheld is recoverable. An answer leaked is not. ```python from eleph import NotPermitted try: g.assert_answer("saldo", value, "quem", "conta") except NotPermitted: ... # escalate, ask them to authenticate, decline — anything but answer ``` ## The unguarded door A gate on one handler and none on its neighbour is a locked front door beside an open window. Since 0.3.0 that is reported as a structural defect before the solver even runs: ```out X question(Quem, saldo) linha 22 outro handler sobre este assunto exige permissao e este nao ``` The check is structural because it is about the shape of the program, not about any particular history. See [obligations](https://elephlanguage.vercel.app/docs/concepts/obligations). ## Why this is not a role system > **LIMIT** > > `permitted` gates a handler on a fact the log supports, which covers *"is this > caller authenticated for this account"*. There are **no roles, no hierarchy and > no delegation**. If your authorisation model needs those, model them outside > and emit the conclusion as an event. ## Measured In the [LangChain comparison](https://elephlanguage.vercel.app/docs/integration/langchain), the scenario `conta de outra pessoa` — someone authenticated for their own account asking about a stranger's — failed **0 times out of 5** without the guard. The agent looked it up and reported back, every single time. It is not a lapse. Nothing in the prompt told it not to, the customer's request was perfectly clear, and answering was the helpful thing to do. An agent that asserts nothing the record does not support and keeps every promise it makes will do this all day. That is the gap `permitted` exists to close. --- # Program structure > The four top-level forms — program, sort, event, fact — and the handlers that answer questions and requests. Source: https://elephlanguage.vercel.app/docs/reference/program-structure A file declares a program, the sorts of thing it talks about, the events that can happen, the facts those events make true, and the handlers that speak. It is indentation-significant, Python-style, with spaces only. ## The shape of a file ```eleph program airline sort Passenger sort Flight event make_reservation(p: Passenger, f: Flight) event cancel_reservation(p: Passenger, f: Flight) fact has_reservation(P: Passenger, F: Flight) := make_reservation(P, F) since_not cancel_reservation(P, F) on question(C, has_reservation(P, F)): answer C with has_reservation(P, F) ``` `program` must come first. After it, `sort`, `event`, `fact` and `on` may appear in any order. Comments run from `#` to end of line. ## `program` ```eleph program companhia ``` One per file, and it names the program. That name appears in the checker's header. ## `sort` ```eleph sort Passenger sort Flight ``` A sort is a kind of object. Declaring them is optional — `event make_reservation(passenger, flight)` with no annotations parses — but sorts do two things worth having: * they let the compiler catch an argument in the wrong position; * they bound the domain the checker quantifies over, which is what `exists P: Sort where` and `count P: Sort where` need. Two built-in sorts exist and need no declaration: | Sort | Used for | |---|---| | `Party` | who is speaking or being spoken to | | `Number` | a numeric event field | > **NOTE: Sort labels are distinct** > > `Party` and `Passenger` both begin with `p`. Before 0.2.0 that made two sorts > indistinguishable in a printed counterexample. They no longer collide. ## `event` ```eleph event make_reservation(p: Passenger, f: Flight) event charged_while_active(u: User, c: Charge, amount: Number) event close_flight(f: Flight) ``` An event is something that can happen. Parameters are `name: Sort`, and the annotation is optional. Events are the **only** source of truth: nothing else can make a fact true. Parameterless events are allowed — write `event tick` or `event tick()`. ## `fact` ```eleph fact has_seat(P: Passenger, F: Flight) := assign_seat(P, F) since_not cancel_reservation(P, F) fact seats_left(F: Flight) := count P: Passenger where has_reservation(P, F) < 2 fact flight_open(F: Flight) := not close_flight(F) ``` A fact is a **named temporal expression**, not a stored value. Its parameters are logical variables, conventionally capitalised, and its body is any [temporal expression](https://elephlanguage.vercel.app/docs/reference/expressions). Facts may reference other facts. Every declared fact is type-checked whether anything calls it or not. Before 0.3.0 resolution was lazy, so a fact no handler mentioned was never checked at all. > **LIMIT** > > Facts cannot be recursive, so transitive properties are out of reach. ## `on` — handlers ```eleph on question(C, has_reservation(P, F)): answer C with has_reservation(P, F) on request(C, make_reservation(P, F)): if has_reservation(P, F): decline C else: record make_reservation(P, F) accept C promise C that has_reservation(P, F) ``` Two performatives exist: | Performative | Body must | Answered with | |---|---|---| | `question` | answer on every path, exactly once | `answer C yes` / `no` / `with φ` | | `request` | accept or decline on every path, exactly once | `accept C` / `decline C` | The first argument binds the caller. The second is the subject: an event for `request`, a fact for `question`. Variables in the subject are bound across the whole body. "Exactly once on every path" is a [structural obligation](https://elephlanguage.vercel.app/docs/concepts/obligations) — a branch that says nothing, or says two things, is a defect. ### Gating on authority ```eleph on question(Quem, saldo(C)) permitted pode_perguntar(Quem, C): answer Quem with saldo(C) ``` `permitted` takes a fact and joins the path condition of every obligation derived from the handler. See [permission](https://elephlanguage.vercel.app/docs/concepts/permission). ## Lexical rules * **Spaces, never tabs.** A tab in the indentation is an error, by name: `use espacos, nao tabs, para indentar`. * **Indentation must be consistent.** Dedents must return to a level that was opened. * Identifiers are `[A-Za-z_][A-Za-z_0-9]*`. Capitalisation carries convention but not meaning: sorts and logical variables are capitalised, events and facts are not. * Numbers are non-negative integers. * Comparison operators are `>=`, `<=`, `==`, `!=`, `<`, `>`. Definition is `:=`. The full keyword list is in `eleph/lexer.py`, and the grammar is on the [grammar page](https://elephlanguage.vercel.app/docs/reference/grammar). --- # Temporal expressions > Every operator that reads the past — atoms, since_not, count, quantifiers, spoke, numeric fields — and what each one asks of the history. Source: https://elephlanguage.vercel.app/docs/reference/expressions Everything a program can know is a formula about its log. These are the forms that formula can take. ## The table | Form | Meaning | |---|---| | `e(a, b)` | event `e` occurred **at least once** in the past | | `a since_not b` | `a` occurred and no `b` has occurred since | | `count e(a) >= n` | how many times `e` occurred | | `exists P: Sort where φ` | some object satisfies φ now | | `count P: Sort where φ >= n` | how many do, which is what a seat limit needs | | `spoke accept to C about e(...)` | the program performed that act in that exchange | | `e(a, amount > 100)` | a numeric field of the event, tested as it happens | | `not`, `and`, `or` | as usual | Parentheses group. `not` binds tightest, then `since_not`, then `and`, then `or`. ## Atoms: the trap, on purpose ```eleph make_reservation(P, F) ``` A bare event atom means *this happened at least once, ever*. It reads like "has" and means "made". The two agree until the first cancellation and never after. > **CAREFUL: This is the language's one deliberate trap** > > Bare `e(a, b)` is kept because it is the mistake real systems make. The > verifier is what tells the two apart — see [McCarthy's > bug](https://elephlanguage.vercel.app/docs/the-mccarthy-bug). ## `since_not` ```eleph make_reservation(P, F) since_not cancel_reservation(P, F) ``` Exactly: *there is an `a` after the final `b`*. This is the operator that makes a fact behave like a mutable field without being one. ```eleph fact active(U: User) := subscribed(U) since_not cancelled(U) fact flight_open(F: Flight) := not close_flight(F) ``` Its operands being **atoms** is the hypothesis of the linear [completeness threshold](https://elephlanguage.vercel.app/docs/concepts/completeness). A compound expression under `since_not` still verifies, just at the monitor's state-space bound. ## `count` over occurrences ```eleph count make_reservation(P, F) >= 8 ``` How many times the atom occurred. Any of `>=`, `<=`, `==`, `!=`, `<`, `>` against a non-negative integer. The constant matters for cost: proving something about a capacity of 180 needs histories that can hold 180 events. ## Quantifiers ```eleph exists P: Passenger where has_reservation(P, F) fact seats_left(F: Flight) := count P: Passenger where has_reservation(P, F) < 2 ``` `exists` asks whether **some** object of that sort satisfies the body now. `count … where` asks how many do, which is what a capacity limit needs — this is McCarthy's own example, and it is not expressible without quantification. The checker bounds the domain: an object with no occurrence in the history falsifies every atom naming it, so quantifying over the objects that appear is the same as quantifying over an unbounded universe. ## `spoke` ```eleph if spoke accept to C about make_reservation(P, F): decline C ``` The program's own utterances are events in the same log, so it can ask what it already said. The recordable performatives are: `answer` · `accept` · `decline` · `promise` · `ask` > **LIMIT** > > `spoke` names the **exchange and the act**, not the propositional content. > *"Did I already promise this exact thing?"* is not expressible. *"Did I already > promise something here?"* is. ## Numeric fields ```eleph event charged_while_active(u: User, c: Charge, amount: Number) fact refundable(U: User, C: Charge) := charged_after_cancelling(U, C, amount > 0) since_not refunded(U, C) fact within_limit(U: User, C: Charge) := charged_after_cancelling(U, C, amount <= 200) since_not refunded(U, C) ``` A comparison in an argument position constrains a numeric field of the event. The comparison is **part of the atom's identity** rather than a separate fact that could move underneath it, which is what keeps the completeness argument intact. > **LIMIT: Compared at the instant the event happens** > > You can ask whether *this charge* was over 100. You cannot ask whether the sum > of the last three was. Aggregate arithmetic over the history is not > expressible. ## Booleans ```eleph not close_flight(F) has_reservation(P, F) and flight_open(F) refundable(U, C) and not within_limit(U, C) ``` `yes` and `no` are also literals inside an expression, so `answer C with yes` parses and means the constant. ## Facts compose A fact may reference any other fact, and that is the intended way to build up a policy: ```eleph fact may_refund(U: User, C: Charge) := refundable(U, C) and within_limit(U, C) fact needs_escalation(U: User, C: Charge) := refundable(U, C) and not within_limit(U, C) ``` Both of those are proved for every history in `examples/langchain-agent/policy.eleph`. --- # Statements > Everything a handler body can do — answer, record, accept, decline, promise, offer, release, and if/else. Source: https://elephlanguage.vercel.app/docs/reference/statements A handler body is a sequence of statements. Every one of them is either a speech act, a record of something that happened, or a branch. ## The full list | Statement | What it does | |---|---| | `answer C yes` | assert the subject holds | | `answer C no` | assert the subject does not hold | | `answer C with φ` | answer whichever way the log says | | `record e(...)` | something happened; append it to the log | | `accept C` | accept a request | | `decline C` | decline a request | | `offer C that φ` | willing, not yet owing | | `promise C that φ` | φ is true now | | `promise C eventually φ` | φ will hold at some point | | `promise C that φ before e(...)` | φ will hold before `e` occurs | | `release C from φ` | let the program off a debt | | `if φ: … else: …` | branch on the past | ## `answer` ```eleph on question(C, has_reservation(P, F)): if has_reservation(P, F): answer C yes else: answer C no ``` Or, equivalently and unmistakably: ```eleph on question(C, has_reservation(P, F)): answer C with has_reservation(P, F) ``` `answer C with φ` is the form that cannot be got wrong: it answers whichever way the log says. The literal forms are what make the [McCarthy bug](https://elephlanguage.vercel.app/docs/the-mccarthy-bug) expressible, and therefore catchable. Every path through a `question` handler must answer **exactly once**. Both a missing answer and a double answer are structural defects. ## `record` ```eleph record make_reservation(P, F) ``` The only way anything ever becomes true. Order matters inside a handler: an immediate promise is discharged over the log *plus* whatever was recorded before it in this same body. ## `accept` and `decline` ```eleph on request(C, make_reservation(P, F)): if has_reservation(P, F): decline C else: record make_reservation(P, F) accept C ``` Every path through a `request` handler must accept or decline **exactly once**. Both take an optional explicit subject — `accept C make_reservation(P, F)` — when the handler is about one thing and the reply is about another. ## The four commitments ```eleph offer C that φ promise C that φ promise C eventually φ promise C that φ before e(...) ``` Each carries a different obligation. The full treatment, with the ledger, is on the [commitments page](https://elephlanguage.vercel.app/docs/concepts/commitments). ```eleph on request(C, make_reservation(P, F)): if has_reservation(P, F): decline C else: if seats_left(F) and flight_open(F): record make_reservation(P, F) accept C promise C that has_reservation(P, F) promise C that has_seat(P, F) before board(P, F) else: decline C ``` ## `release` ```eleph release C from has_seat(P, F) ``` Lets the program off a debt it can no longer keep — after a cancellation, for instance. It is a speech act and goes into the log: a debt quietly dropped and a debt formally released are different histories. ## `if` / `else` ```eleph if seats_left(F) and flight_open(F): ... else: ... ``` The condition is any [temporal expression](https://elephlanguage.vercel.app/docs/reference/expressions). The branch taken becomes the **path condition** of every obligation derived from statements inside it — that is the `supondo` line the checker prints. `else` is optional, but leaving it off a `question` or `request` handler usually creates a path that says nothing, which is a structural defect. The checker will say so. ## What is not here There is no assignment, no loop, no function call, and no variable. That is not a subset chosen for simplicity; it is the [design](https://elephlanguage.vercel.app/docs/concepts/past-is-state). The past is the state, so there is nothing to assign to, and a handler runs once per utterance, so there is nothing to loop over. --- # Obligations derived > The ten correctness conditions, what each one demands, and which are discharged by Z3 versus structurally. Source: https://elephlanguage.vercel.app/docs/reference/obligations A reference table for what the compiler reads off a program. For the reasoning behind them, see the [concept page](https://elephlanguage.vercel.app/docs/concepts/obligations). ## The ten | Obligation | Demands | Checked by | |---|---|---| | answer is true | on this path, the answer given is entailed by the log | Z3, at the completeness threshold | | answer responds to the question asked | the answer is about the subject of the question | Z3 | | immediate promise holds when made | φ is true over the log plus what this handler recorded | Z3 | | future promise is dischargeable | some path turns φ from false to true | Z3 | | offer is honourable | some path could bring φ about | Z3 | | sorts agree with declarations | every argument sits in a position of its own sort | compiler, on every fact, used or not | | no unguarded door | no handler on a protected subject lacks the gate its neighbour has | structural | | exactly one answer per path | every path through a `question` answers once | structural | | exactly one reply per path | every path through a `request` accepts or declines once | structural | | commitments settled | nothing outstanding is silently forgotten | runtime ledger | ## How each is printed Run `eleph obligations` to see the conditions without discharging them: ```out $ eleph obligations examples/booking.eleph linha 23 request(Caller, make_reservation) a promessa esta cumprida ao ser feita supondo nao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) entao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) linha 29 request(Caller, cancel_reservation) a promessa esta cumprida ao ser feita supondo (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) entao nao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) ``` | Line | What it is | |---|---| | `linha N handler` | where in the source this obligation came from | | the title | which of the ten this is | | `supondo` | the path condition: the branch taken to reach the statement | | `entao` | the goal: what performing the act claims | ## Polarity Most obligations are **universal**: no history may make the assumptions true and the goal false. Two are **existential** — dischargeability of a future promise and honourability of an offer — where what must exist is a path: ```out ok request(C, make_reservation) linha 46 - a promessa pode vir a ser cumprida (antes de board(P, F)) cumprivel por: request assign_seat > entao l51 ``` When an existential obligation fails, the checker says so in those terms rather than printing a history: ```out nenhum caminho do programa chega a cumprir isso ``` ## Verdicts | Marker | Meaning | |---|---| | `ok` | discharged at this obligation's completeness threshold | | `ok?` | survived the bound given, which was below the threshold | | `X` | a counterexample exists, and is printed | | `PROVADO` | every obligation holds for every history, of any length | | `SEM CONTRAEXEMPLO` | nothing broke within bounds that were not exhaustive | | `REPROVADO` | at least one obligation is not met | ## The soundness claim that links them to the runtime > **If every obligation is proved, the runtime never refuses.** The runtime refuses exactly when a speech act's truth condition fails, and the deriver emits *path condition implies truth condition* for each such act over the same log. The claim is tested by hammering proved programs with random pasts and random conversations, and by confirming that unproved ones **do** refuse. It lives in `tests/test_soundness.py`. ## Source Derivation: `eleph/obligations.py`. Discharge: `eleph/verify.py`. Thresholds: `eleph/threshold.py`. --- # Grammar > The complete surface syntax of eleph, keywords, and lexical rules. Source: https://elephlanguage.vercel.app/docs/reference/grammar The whole surface syntax, in one place. It is small on purpose. ## Notation `x*` is zero or more, `x+` is one or more, `[x]` is optional, `|` is alternation. `INDENT` and `DEDENT` are produced by the lexer from leading spaces, Python-style. ## Program ```text program ::= "program" IDENT NEWLINE decl* decl ::= sort_decl | event_decl | fact_decl | handler sort_decl ::= "sort" IDENT NEWLINE event_decl ::= "event" IDENT param_list NEWLINE fact_decl ::= "fact" IDENT param_list ":=" texpr NEWLINE param_list ::= [ "(" [ param ("," param)* ] ")" ] param ::= IDENT [ ":" IDENT ] ``` ## Handlers ```text handler ::= "on" performative "(" IDENT "," ref ")" [ "permitted" ref ] ":" NEWLINE block performative ::= "question" | "request" block ::= INDENT stmt+ DEDENT ``` ## Statements ```text stmt ::= if_stmt | answer_stmt | "record" ref NEWLINE | ("accept" | "decline") IDENT [ ref ] NEWLINE | promise_stmt | "offer" IDENT "that" texpr NEWLINE | "release" IDENT "from" texpr NEWLINE if_stmt ::= "if" texpr ":" NEWLINE block [ "else" ":" NEWLINE block ] answer_stmt ::= "answer" IDENT ( "yes" | "no" | "with" texpr ) NEWLINE promise_stmt ::= "promise" IDENT "eventually" texpr NEWLINE | "promise" IDENT "that" texpr [ "before" ref ] NEWLINE ``` ## Temporal expressions ```text texpr ::= or_expr or_expr ::= and_expr ( "or" and_expr )* and_expr ::= since_expr ( "and" since_expr )* since_expr ::= unary [ "since_not" unary ] unary ::= "not" unary | primary primary ::= "(" texpr ")" | "yes" | "no" | "exists" binder since_expr | "count" binder since_expr comparison | "count" ref comparison | "spoke" perf "to" IDENT "about" ref | ref binder ::= IDENT ":" IDENT "where" comparison ::= OP NUMBER perf ::= "answer" | "accept" | "decline" | "promise" | "ask" ref ::= IDENT [ "(" [ arg ("," arg)* ] ")" ] arg ::= IDENT [ OP NUMBER ] ``` The `arg` production with a comparison is the numeric-field form: `charged(U, C, amount > 100)`. ## Tokens ```text NUMBER ::= [0-9]+ IDENT ::= [A-Za-z_][A-Za-z_0-9]* ASSIGN ::= ":=" OP ::= ">=" | "<=" | "==" | "!=" | "<" | ">" PUNCT ::= "(" | ")" | ":" | "," COMMENT ::= "#" .* ``` ## Keywords Reserved, and unusable as identifiers: ```text program event fact on if else answer with yes no record accept decline promise that not and or since_not count to sort exists where spoke about eventually before release from permitted offer ``` The list is in `eleph/lexer.py`, in this order. ## Lexical rules * Blank lines and comment-only lines carry **no indentation meaning**. * Indentation must use spaces. A tab in the leading whitespace is an error: `linha N: use espacos, nao tabs, para indentar`. * A dedent must return to a level that was previously opened, or: `linha N: indentacao inconsistente`. * **There is no line continuation.** A `fact` body must sit on one line: breaking after `:=` gives `esperava nome de evento ou fato, veio 'NEWLINE'`, because the lexer emits a NEWLINE the parser has no rule for. Handler bodies span lines because indentation opens a block; nothing else does. ## Errors Three exception types reach the CLI, and all three exit with status `2`: | Exception | Raised by | Example message | |---|---|---| | `LexError` | `eleph/lexer.py` | `linha 4: caractere inesperado '@'` | | `ParseError` | `eleph/parser.py` | `linha 9: esperava 'yes', 'no' ou 'with'` | | `ResolveError` | `eleph/core.py` | an unknown name, or an arity or sort mismatch | --- # CLI > The five commands — obligations, check, run, talk, ledger — with every flag and every exit code. Source: https://elephlanguage.vercel.app/docs/cli Five commands. Two of them read the program, two of them run it, and one reads back what it still owes. ```out $ eleph --help usage: elephant [-h] {check,obligations,run,talk,ledger} ... positional arguments: {check,obligations,run,talk,ledger} check verificar um programa obligations mostrar as condicoes derivadas, sem verificar run executar um dialogo contra o programa talk conversar em linguagem natural ledger o que o programa ainda deve ``` Every command accepts `--no-color`, which is what you want in CI and in a pipe. > **NOTE: Paths on this page are repository paths** > > `examples/` is not installed by `pip install` or `uv add`, so the runs quoted > here assume a clone. And if `eleph` is in a project's `.venv` rather than on > your PATH, prefix everything with `uv run`. See > [installation](https://elephlanguage.vercel.app/docs/installation). ## `eleph obligations` ```bash eleph obligations ``` Print the correctness conditions the program's own text demands, without trying to discharge them. The point of the exercise: **nobody wrote these.** ```out $ eleph obligations examples/airline_buggy.eleph examples/airline_buggy.eleph: condicoes que o proprio texto do programa exige linha 17 question(Caller, has_reservation) resposta yes e verdadeira supondo alguma vez make_reservation(P, F) entao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) linha 19 question(Caller, has_reservation) resposta no e verdadeira supondo nao alguma vez make_reservation(P, F) entao nao (make_reservation(P, F) e desde entao nenhum cancel_reservation(P, F)) ``` Structural defects are listed after the obligations, prefixed by their line. ## `eleph check` ```bash eleph check [--bound N] [--objects N] ``` Derive the obligations and try to break each one at its own [completeness threshold](https://elephlanguage.vercel.app/docs/concepts/completeness). ```out $ eleph check examples/companhia.eleph examples/companhia.eleph -> programa companhia 5 eventos, 4 fatos, 6 handlers 6 obrigacoes derivadas do texto do programa cada uma checada no seu limiar de completude (o maior: 10 eventos) -- exaustivo ok question(C, has_reservation) linha 30 - a resposta responde a pergunta feita ok question(C, has_seat) linha 33 - a resposta responde a pergunta feita ok question(C, seats_left) linha 36 - a resposta responde a pergunta feita ok request(C, make_reservation) linha 45 - a promessa esta cumprida ao ser feita ok request(C, make_reservation) linha 46 - a promessa pode vir a ser cumprida (antes de board(P, F)) cumprivel por: request assign_seat > entao l51 ok request(C, cancel_reservation) linha 61 - a promessa esta cumprida ao ser feita PROVADO - 6 obrigacoes valem para TODO historico, de qualquer tamanho ``` ### Flags | Flag | Default | Effect | |---|---|---| | `--bound N` | the completeness threshold | force the history length. Below the threshold the result stops being a proof, and the tool says so | | `--objects N` | the computed domain | force the number of objects per sort | | `--no-color` | off | plain output | > **CAREFUL: A bound below the threshold is not a proof** > > ```out > $ eleph check examples/fundo.eleph --bound 6 > > linha 11: limite pedido abaixo do limiar > > ok? question(C, elite) linha 11 - resposta yes e verdadeira > > SEM CONTRAEXEMPLO - dentro dos limites checados, que nao sao exaustivos aqui > ``` > `ok?` and `SEM CONTRAEXEMPLO` both mean the run was not exhaustive. This > example lies only after seven events. ### Exit codes | Code | Meaning | |---|---| | `0` | no failures — either `PROVADO` or `SEM CONTRAEXEMPLO` | | `1` | `REPROVADO`: at least one obligation has a counterexample or a structural defect | | `2` | the file did not lex, parse or resolve | Note that `0` covers both proved and non-exhaustive. If your CI needs proof rather than absence of a counterexample, grep for `PROVADO`. ## `eleph run` ```bash eleph run