From b8e213ababa484d1b9f8d05d4ca4aee7f3611bc5 Mon Sep 17 00:00:00 2001 From: alakanani Date: Wed, 4 Nov 2026 11:05:53 +0000 Subject: [PATCH] The accountable agent: one folder, two locks, a report anyone can re-run --- AGENTS.md | 5 + CHANGELOG.md | 1 + docs/accountable-agent.md | 94 ++++++++++++ docs/sandbox.md | 2 +- examples/README.md | 3 + examples/accountable_agent.god | 57 ++++++++ .../accountable_agent_data/field-notes-1.txt | 2 + .../accountable_agent_data/field-notes-2.txt | 2 + .../accountable_agent_data/market-prices.txt | 2 + godcode/cli.py | 17 +++ godcode/sandbox.py | 8 + site/playground/engine.json | 2 +- tests/test_accountable_agent.py | 137 ++++++++++++++++++ 13 files changed, 330 insertions(+), 2 deletions(-) create mode 100644 docs/accountable-agent.md create mode 100644 examples/accountable_agent.god create mode 100644 examples/accountable_agent_data/field-notes-1.txt create mode 100644 examples/accountable_agent_data/field-notes-2.txt create mode 100644 examples/accountable_agent_data/market-prices.txt create mode 100644 tests/test_accountable_agent.py diff --git a/AGENTS.md b/AGENTS.md index 03fd844..e4146a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,11 @@ Same exit-code convention. JSON shape: `{"tool","command","file","ok", notices like `[SEAL]`); on runtime error it holds lines revealed *before* the error, and `error` carries `line`/`col`/`code`/`message`. `--sandbox` confines execution; `--json` composes with plain `run`/`check` too. +A sandboxed run denies every file read until the invoker grants one: +`run --sandbox --allow-read DIR scroll.god` (repeatable). The scroll's +permission manifest still narrows the grant, so the run may read only +what both the host and the scroll allow. See +`docs/accountable-agent.md` for the worked demo. ## Share scrolls diff --git a/CHANGELOG.md b/CHANGELOG.md index 76797cb..c8ada89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to the God Code engine are recorded here, that the generatio ## Unreleased ### Added +- **🕊️ The accountable agent.** The first flagship demo, and the small engine change it needed: a sandboxed run denied every file read until now, so an agent that reads one folder could not run sandboxed at all. New `godcode run --sandbox --allow-read DIR scroll.god` (repeatable) grants the host reads under the named folders only, and the scroll's permission manifest still narrows the grant, so the run may read only what both the host and the scroll allow. Using `--allow-read` without `--sandbox` is a usage error, since a plain run is unbound by the host. New example `examples/accountable_agent.god` with its entrusted folder `examples/accountable_agent_data`: it declares one read permission, fingerprints every file in the folder, and reveals the count, the total characters, and a fingerprint of the whole report, deterministically, so anyone can re-run it and compare. Documented in `docs/accountable-agent.md`, repo `AGENTS.md`, and `docs/sandbox.md`, with the worked checks (with the grant it runs, without it refused, reaching past the folder refused) kept honest by 8 new tests in `tests/test_accountable_agent.py`. - **🕊️ The MCP server.** `godcode mcp` serves God Code to any MCP client (Claude Code, Cursor, Codex, and the rest) over stdio, one JSON-RPC message per line, with protocol version negotiation and silence for notifications. It carries the eleven agent tools (`check`, `run`, `consult`, `intent`, `anchor_verify`, `ledger_verify`, `permissions`, `explain`, `get_schema`, plus new `format` and `list_scrolls`), and it holds one rule the plain bridge does not: runs through it are always sandboxed, so a client asking for an unsandboxed run still gets a sandboxed one, and the result says so. Tool work runs muted, so stdout carries exactly one protocol message per line and an engine notice can never break a client's parsing; the sandboxed tool path is muted the same way, which also heals the plain bridge. Documented in `docs/mcp.md`, `docs/agentics.md`, and repo `AGENTS.md`. New tests in `tests/test_mcp.py`; the tool-count tests now expect eleven tools. - **🕊️ The October 2026 machine interfaces.** God Code's `--json` shapes are frozen under dated schemas, so an agent can parse every output without guessing. New `godcode explain scroll.god [--json]`: a static reading of any scroll that runs nothing, reporting the tongue, the rites and their declared intents, the declared names, the reveals, the seals (including `ANCHOR` seals on a chain), the summoned verbs, the `CONSULT` questions, the imports, and the permission manifest, in warm plain words for humans and one JSON document for agents. New `godcode ledger verify --json`: the covenant chain and anchor chain attestation as one JSON document. New `godcode schema [name]`: list or print the four dated schemas (`check`, `run`, `explain`, `ledger-verify`), shipped inside the installed package and resolvable through `importlib.resources`. The agent bridge gains two tools, `explain` and `get_schema` (nine tools in all). The full contract, exit codes, and the stability promise (additive fields may appear, required fields never change meaning, breaking changes ship under a new dated schema) live in `docs/machine-interfaces.md`. New tests in `tests/test_machine_interfaces.py`; repo `AGENTS.md` documents the read-before-you-run workflow. - **🕊️ God Code speaks Igbo and Nigerian Pidgin.** The third and fourth tongues. A scroll that opens with `# tongue: ig` writes its keywords in Igbo (BIDO OKIKE for BEGIN CREATION, GOSI for REVEAL, Ọ BỤRỤ and MGBE AHỤ for IF and THEN, NWAA and JIDE for TRY and CATCH, and the rest), and one that opens with `# tongue: pg` (or the standard code `pcm`) writes them in Nigerian Pidgin (OYA KREASHON, TALK and BE for DECLARE and AS, SHOW for REVEAL, DEN for THEN, HOLD for CATCH, COMOT for ASCEND). Igbo words work with or without their dotted vowels (`DỊKA` and `DIKA` both speak), and Pidgin keeps the words it shares with English (IF, TRY, AND, RETURN). Two-word phrases now join whenever both words sit side by side on one line, even when one is an English keyword or a plain name, so `FINISH IF` closes an IF in Pidgin and `Ọ BỤRỤ` opens one in Igbo; Setswana and isiZulu closers behave exactly as before. The mappings live in `godcode/tongues.py`; the playground's lite engine knows both tongues (Igbo in its undotted spelling), the language server offers their completions, hover docs, and block snippets (hover now reads dotted words), and the VS Code extension paints their keywords and ships four starter snippets (`ndewo`, `oburu`, `howfar`, `ifden`). Documented in `docs/TONGUES.md` (both word tables and honest first-edition notes), `docs/LANGUAGE_REFERENCE.md` §1, repo `AGENTS.md`, the site landing card, and two new lessons on the learn page. New examples `examples/first_blessing_ig.god` and `examples/first_blessing_pg.god`, also offered as playground samples. 25 new tests in `tests/test_tongues_igbo_pidgin.py`; the VS Code snippet count in `tests/test_lsp_tongues.py` rises from 27 to 31 diff --git a/docs/accountable-agent.md b/docs/accountable-agent.md new file mode 100644 index 0000000..d11bc4c --- /dev/null +++ b/docs/accountable-agent.md @@ -0,0 +1,94 @@ +# The accountable agent + +The first flagship demo: an agent given exactly one folder, and +nothing else. It is the wedge in miniature. The agent states its +intent, receives narrow permission, runs safely, and leaves a report +anyone can re-run and check. + +## What it does + +`examples/accountable_agent.god` reads every file in +`examples/accountable_agent_data`, fingerprints each file with +`SHA256`, and reveals one line per file, the file count, the total +characters, and a fingerprint of the whole report. Run it twice and +every revealed line matches, because the scroll reads no clock, no +network, and no changing value. + +## The two locks + +Accountability here is two locks that must both open, not one: + +1. **The scroll's permission manifest.** The scroll declares a single + power at the top: + `DECLARE PERMISSION TO READ "accountable_agent_data"`. The path is + relative to the scroll, so it means the folder beside the scroll. + Anything the scroll did not declare is refused, even on a plain + run where the host is open. +2. **The host grant.** A sandboxed run denies every file read until + the invoker grants one. `--allow-read` names the folder the host + allows, and it may be repeated for more than one folder. The + scroll cannot widen its own cage: the effective read set is the + host grant intersected with the manifest. + +Read what a scroll may touch before running it. It runs nothing: + +```bash +godcode permissions examples/accountable_agent.god +``` + +Run the demo from the repo root, sandboxed, with exactly the one +grant: + +```bash +godcode run --sandbox --allow-read examples/accountable_agent_data examples/accountable_agent.god +``` + +## The three checks + +Each check is kept honest by a test in +`tests/test_accountable_agent.py`: + +- **With the grant, it runs.** The revealed report fingerprint is + recomputed from the files in the test, not copied from a past run. +- **Without the grant, it is refused.** The same sandboxed run with + no `--allow-read` exits nonzero and says the power is withheld. +- **Reaching past the folder is refused.** A scroll that keeps the + same manifest but points at another folder is stopped, under the + sandbox by the host grant and on a plain run by the manifest. + +`--allow-read` without `--sandbox` is a usage error: a plain run is +unbound by the host, so a host grant there would mean nothing, and +the manifest is already doing the narrowing. + +## The Spirit's counsel + +The demo declares its intent on the `survey` rite. At invocation the +Spirit discerns the intent from what the rite does ("Controlled data +access") and counsels when it drifts from the declared words. That +counsel is printed, and it never fails the run: drift is advice, not +a verdict. The `--json` report carries the discernment in its +`intents` array, beside the `permissions` block, so an agent host can +read both without parsing prose. + +## What this does not prove + +- The sandbox is in-process, not operating-system isolation. It is a + cooperative audit of the tree-walking interpreter. A hostile + program that escapes the interpreter is not contained by it. See + `docs/sandbox.md` for the honest limits. +- The host grant is the invoker's own act. Granting a folder the + scroll should not see is the invoker's mistake, and no manifest + can repair it, because the manifest can only narrow, never widen. +- The report fingerprint proves the report matches the files as read + at run time. It does not prove the files themselves are true. +- The demo writes nothing and seals nothing, so its proof is the + re-run: same folder, same lines. A sealed replayable receipt is + the next step, and this scroll is built ready for it, with no + changing values in its output. + +## What comes next + +The other two flagship demos follow the same shape: the covenant +contract (a savings circle expressed as rites with declared intent, +sealed on the ledger) and the first-program path (ten minutes in the +playground, from first line to shared link). diff --git a/docs/sandbox.md b/docs/sandbox.md index 76eaa70..f414513 100644 --- a/docs/sandbox.md +++ b/docs/sandbox.md @@ -30,7 +30,7 @@ The sandbox withholds this power: the rite ASK would speak with the outer world. | Field | Default | Meaning | |---|---|---| -| `allow_read_paths` | `None` (deny all) | Directories the creation may read files from. No file-reading rites exist yet; enforced if any are added. | +| `allow_read_paths` | `None` (deny all) | Directories the creation may read files from. The CLI sets it with `run --sandbox --allow-read DIR` (repeatable); the scroll's permission manifest still narrows the grant. | | `allow_write` | `False` | Filesystem writes. No file-writing rites exist yet; enforced if any are added. | | `allow_network` | `False` | Network access. The `HTTP_GET` rite (see §13) is the one network rite: when network is denied it is withheld and raises instead of reaching out. | | `allow_subprocess` | `False` | Spawning subprocesses. No subprocess rites exist yet; enforced if any are added. | diff --git a/examples/README.md b/examples/README.md index 7d6b547..8eab3cc 100644 --- a/examples/README.md +++ b/examples/README.md @@ -6,6 +6,9 @@ runs as-is. Just pick one. ## The four examples +- `examples/accountable_agent.god`. The accountable agent flagship demo: an agent given exactly one folder, `examples/accountable_agent_data`, and nothing else. It declares one read permission, fingerprints every file, and reports the count. Read its manifest first, then run it sandboxed with the one host grant. See `docs/accountable-agent.md`. + `godcode permissions examples/accountable_agent.god` + `godcode run --sandbox --allow-read examples/accountable_agent_data examples/accountable_agent.god` - `examples/file_reporter.god`. Walks a directory, lists every file it finds, and reveals a total. Shows off the file builtins (LIST_DIR, READ_FILE, FILE_EXISTS). `godcode run examples/file_reporter.god` - `examples/sales_summary.god`. Reads a JSON sales ledger from `examples/data/sales.json`, computes totals and averages, and writes a plain-text summary to `examples/data/sales_report.txt`. Shows off JSON parsing, WHILE loops, and file output. diff --git a/examples/accountable_agent.god b/examples/accountable_agent.god new file mode 100644 index 0000000..ab3bb49 --- /dev/null +++ b/examples/accountable_agent.god @@ -0,0 +1,57 @@ +# The accountable agent. +# +# The first flagship demo: an agent given exactly one folder, and +# nothing else. It declares the one power it may use, reads every file +# in the entrusted folder, fingerprints each one, and reports the +# count. It cannot read, write, or reach anything outside that folder: +# the host grant and the scroll's own permission narrow each other, +# and either one refusing stops the run. +# +# Read what it may touch first (runs nothing): +# godcode permissions examples/accountable_agent.god +# +# Run it from the repo root, sandboxed, with the host granting +# exactly the entrusted folder: +# godcode run --sandbox --allow-read examples/accountable_agent_data examples/accountable_agent.god +# +# Without the host grant the same run is refused. With the grant, a +# scroll that reaches past the folder is refused too. Run it twice +# and every line matches: the report is deterministic, so anyone can +# re-run it and compare, and it is ready to be sealed as a replayable +# receipt. See docs/accountable-agent.md. + +BEGIN CREATION + DECLARE PERMISSION TO READ "accountable_agent_data" + + DECLARE INTENT "to read only the entrusted folder and report every file in it honestly" ON survey + DEFINE RITE survey(dir) + DECLARE entries AS LIST_DIR(dir) + DECLARE total_files AS 0 + DECLARE total_chars AS 0 + DECLARE ledger AS "" + DECLARE i AS 0 + WHILE i < LEN(entries) DO + DECLARE name AS entries[i] + DECLARE text AS READ_FILE(dir + "/" + name) + DECLARE chars AS LEN(text) + DECLARE fingerprint AS SHA256(text) + REVEAL("{name} holds {chars} characters, fingerprinted {fingerprint}.") + DECLARE ledger AS ledger + name + "=" + fingerprint + ";" + DECLARE total_files AS total_files + 1 + DECLARE total_chars AS total_chars + chars + DECLARE i AS i + 1 + ENDWHILE + REVEAL("Files counted: {total_files}") + REVEAL("Total characters: {total_chars}") + REVEAL("Report fingerprint: " + SHA256(ledger)) + RETURN total_files + END RITE + + DECLARE data_dir AS "examples/accountable_agent_data" + IF FILE_EXISTS(data_dir) THEN + DECLARE counted AS survey(data_dir) + REVEAL("Surveyed {counted} files. Nothing outside the entrusted folder was touched.") + ELSE + REVEAL("The entrusted folder is missing. Nothing to report.") + ENDIF +END CREATION diff --git a/examples/accountable_agent_data/field-notes-1.txt b/examples/accountable_agent_data/field-notes-1.txt new file mode 100644 index 0000000..31b9363 --- /dev/null +++ b/examples/accountable_agent_data/field-notes-1.txt @@ -0,0 +1,2 @@ +Morning count: 12 baskets of sorghum, 7 of millet. +The rains held. The storehouse door was latched at dusk. diff --git a/examples/accountable_agent_data/field-notes-2.txt b/examples/accountable_agent_data/field-notes-2.txt new file mode 100644 index 0000000..03a55bf --- /dev/null +++ b/examples/accountable_agent_data/field-notes-2.txt @@ -0,0 +1,2 @@ +Second field: 19 rows weeded, 4 left for tomorrow. +Two hands short. The work continues at first light. diff --git a/examples/accountable_agent_data/market-prices.txt b/examples/accountable_agent_data/market-prices.txt new file mode 100644 index 0000000..f28cd82 --- /dev/null +++ b/examples/accountable_agent_data/market-prices.txt @@ -0,0 +1,2 @@ +Sorghum 42 per bag. Millet 38 per bag. Maize 35 per bag. +Prices taken at the gate, before noon. diff --git a/godcode/cli.py b/godcode/cli.py index d0f989b..fd743e6 100644 --- a/godcode/cli.py +++ b/godcode/cli.py @@ -62,6 +62,12 @@ def cmd_run(args: argparse.Namespace) -> int: # --- v3: sandbox commands --- if getattr(args, "sandbox", False): return _cmd_run_sandboxed(args) + if getattr(args, "allow_read", None): + print("godcode: --allow-read only has meaning with --sandbox. " + "A plain run is unbound by the host, and the scroll's own " + "permission manifest still narrows it.", + file=sys.stderr) + return 2 # --- end v3: sandbox commands --- # --- v3: agentics --json --- @@ -111,9 +117,13 @@ def _cmd_run_sandboxed(args: argparse.Namespace) -> int: return 1 source_dir = str(Path(args.file).resolve().parent) + read_grants = tuple( + str(Path(path).resolve()) + for path in (getattr(args, "allow_read", None) or [])) policy = SandboxPolicy.strict( source_dir=source_dir, timeout_seconds=args.sandbox_timeout, + allow_read_paths=read_grants or None, ) if getattr(args, "json", False): # Machine-readable report; stdout carries exactly one JSON document. @@ -1048,6 +1058,13 @@ def build_parser() -> argparse.ArgumentParser: metavar="SECS", help="Wall-clock grant for --sandbox runs " "(default: 5.0 seconds)") + p_run.add_argument("--allow-read", action="append", default=[], + metavar="DIR", + help="With --sandbox, grant the run host reads " + "under DIR (repeatable). The scroll's " + "permission manifest still narrows the " + "grant: the run may read only what both " + "the host and the scroll allow.") # --- end v3: sandbox commands --- # --- v3: agentics --json --- p_run.add_argument("--json", action="store_true", diff --git a/godcode/sandbox.py b/godcode/sandbox.py index 2815b29..fa6d1d4 100644 --- a/godcode/sandbox.py +++ b/godcode/sandbox.py @@ -105,16 +105,24 @@ def strict( *, source_dir: str | None = None, timeout_seconds: float | None = 5.0, + allow_read_paths: tuple[str, ...] | None = None, ) -> "SandboxPolicy": """The CLI's strict policy: deny everything, bless the stdlib. Scroll imports are allowed from the bundled stdlib scrolls and, when given, the creation's own directory — nothing else. + Filesystem reads stay denied unless the invoker names them: + ``allow_read_paths`` grants host reads under those trees only, + and the scroll's own permission manifest still narrows the + grant, so the effective read set is host grant intersect + manifest. The invoker's grant is the invoker's own act, never + the creation's: a scroll cannot widen its own cage. """ paths = [_stdlib_scrolls_dir()] if source_dir: paths.append(str(source_dir)) return cls( + allow_read_paths=allow_read_paths, allowed_import_paths=tuple(paths), timeout_seconds=timeout_seconds, ) diff --git a/site/playground/engine.json b/site/playground/engine.json index 7dc0061..378b6e6 100644 --- a/site/playground/engine.json +++ b/site/playground/engine.json @@ -1 +1 @@ -{"files":{"god_code_training_dataset.csv":"code,primary_action,logic_flows,spiritual_intent,next_suggestions\nBEGIN CREATION\nDECLARE soul AS contract(\"redemption\")\nBREATHE life INTO soul\nASCEND\nEND CREATION,Deploy smart contract,contract deployment | symbolic syntax,Manifest a redemptive contract,REFLECT on contract values\nBEGIN CREATION\nPROPHESY outcome OF mission IN 3 cycles\nREVEAL(\"result\")\nASCEND\nEND CREATION,Forecast future outcome,predictive logic | prophecy-based evaluation,Foresee the success or delay of a divine mission,Log prophecy and evaluate\nBEGIN CREATION\nIF seeker IS worthy THEN\nREVEAL(truth)\nENDIF\nASCEND\nEND CREATION,Controlled data access,conditional logic | spiritual worthiness,Reveal hidden truth to worthy seekers,Reflect on seeker metrics\nBEGIN CREATION\nDEFINE RITE evening_blessing()\nREVEAL(\"peace upon this house\")\nEND RITE\nINVOKE evening_blessing()\nASCEND\nEND CREATION,Blessing of peace,rite invocation | spoken blessing,Bring peace to the household and rest to every heart within,Speak the blessing each evening without ceasing\nBEGIN CREATION\nDECLARE covenant AS contract(\"everlasting\")\nDECLARE seal AS ANCHOR(covenant)\nREVEAL(seal)\nASCEND\nEND CREATION,Anchor a covenant,sealing | hash-chained witness,Set the covenant in unbreakable remembrance upon the chain,Verify the anchor before you testify of it\nBEGIN CREATION\nREVEAL(CONSULT(\"How should I structure this covenant\"))\nASCEND\nEND CREATION,Seek counsel,question | oracle answer,Ask in humility and receive wisdom for the work ahead,Weigh the counsel and act in peace\n","godcode/__init__.py":"\"\"\"God Code v3.0 — the language of divine computation.\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any\n\n__version__ = \"4.1.0\"\n\n\n@dataclass\nclass RunResult:\n \"\"\"The outcome of running God Code from a host program.\n\n ``output`` is the captured REVEAL output (lines joined with ``\\\\n``);\n ``return_value`` is the value of a top-level ``RETURN`` (if the scroll\n ascends that way) or of the last expression statement evaluated, else\n ``None``; ``error`` is the divine error message (with line number) when\n the run failed; ``ok`` tells whether the run completed.\n \"\"\"\n\n output: str = \"\"\n return_value: Any = None\n error: str | None = None\n ok: bool = False\n\n\ndef run_source(source: str, *, filename: str = \"\") -> RunResult:\n \"\"\"Run God Code source from a host program and capture the outcome.\n\n REVEAL output is captured per-interpreter (via the interpreter's ``emit``\n hook), so this is safe to call many times in one process. Plugin\n auto-loading still applies unless ``GODCODE_NO_PLUGINS=1`` is set.\n Embedding runs do not write the audit log.\n \"\"\"\n from godcode.errors import GodCodeError, ReturnSignal\n from godcode.interpreter import Interpreter\n\n lines: list[str] = []\n interpreter = Interpreter(log_path=None)\n interpreter.emit = lines.append\n try:\n interpreter.run_source(source, source_name=filename)\n except ReturnSignal as ret:\n # A top-level RETURN becomes the run's return value.\n return RunResult(\n output=\"\\n\".join(lines), return_value=ret.value, error=None, ok=True\n )\n except GodCodeError as err:\n return RunResult(\n output=\"\\n\".join(lines),\n return_value=None,\n error=str(err),\n ok=False,\n )\n except Exception as exc: # a host/plugin failure outside the divine errors\n return RunResult(\n output=\"\\n\".join(lines),\n return_value=None,\n error=f\"the outer world faltered: {exc!r}\",\n ok=False,\n )\n return RunResult(\n output=\"\\n\".join(lines),\n return_value=interpreter.last_value,\n error=None,\n ok=True,\n )\n\n\ndef run_file(path: str | Path) -> RunResult:\n \"\"\"Run a God Code scroll file from a host program; see :func:`run_source`.\"\"\"\n try:\n source = Path(path).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return RunResult(\n output=\"\",\n return_value=None,\n error=f\"cannot read '{path}': {exc.strerror or exc}\",\n ok=False,\n )\n return run_source(source, filename=str(path))\n\n\n__all__ = [\"__version__\", \"RunResult\", \"run_source\", \"run_file\"]\n","godcode/__main__.py":"\"\"\"Allow ``python -m godcode ``.\"\"\"\nimport sys\n\nfrom godcode.cli import main\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","godcode/agentics.py":"\"\"\"Machine-readable output for AI agents (Mini-Pillar 5 — Agentics).\n\nThis module turns God Code diagnostics and run results into stable JSON\npayloads an agent can parse without scraping divine prose. The CLI wires\nit in behind ``--json`` on the ``run`` and ``check`` commands.\n\nError-code mapping choice\n-------------------------\nCodes are a small, stable, language-agnostic vocabulary derived from the\nv2.0 exception hierarchy in :mod:`godcode.errors` (there is no\n``GodCodeSyntaxError`` class in v2.0, so the mapping below is explicit):\n\n LexerError -> LEXER_ERROR\n ParseError -> PARSE_ERROR\n GodRuntimeError -> RUNTIME_ERROR\n\nAny other ``GodCodeError`` subclass falls back to a mechanical\nCamelCase -> UPPER_SNAKE conversion of its class name\n(e.g. ``FooBarError`` -> ``FOO_BAR_ERROR``). Failures that are not God\nCode failures at all (an unreadable scroll file) use ``FILE_ERROR``,\nwhich is not an exception class.\n\nCapture choice\n--------------\n``run`` output is captured with :func:`contextlib.redirect_stdout` into\na :class:`io.StringIO` around the interpreter call — no dependency on\nany capture hooks from sibling pillars.\n\nSeals\n-----\nAfter the run we diff the interpreter's bound ``ledger`` (when present)\nagainst its block count before the run. Blocks sealed during the run are\nreported as ``{\"block\": , \"hash\": }``. When no ledger is\nbound or it cannot be read, ``seals`` is ``[]`` — never an error.\n\"\"\"\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nimport json\nimport re\nimport sys\nimport time\nfrom pathlib import Path\n\nTOOL_NAME = \"godcode\"\n\n# ---------------------------------------------------------------------------\n# error codes\n# ---------------------------------------------------------------------------\n_CODE_MAP = {\n \"LexerError\": \"LEXER_ERROR\",\n \"ParseError\": \"PARSE_ERROR\",\n \"GodRuntimeError\": \"RUNTIME_ERROR\",\n}\n\n_HINTS = {\n \"LEXER_ERROR\": (\n \"Scan the reported line for stray symbols or an unterminated \"\n \"string; God Code strings use double quotes.\"\n ),\n \"PARSE_ERROR\": (\n \"Every scroll needs BEGIN CREATION ... END CREATION; comparisons \"\n \"use IS / IS NOT, and every block needs its closer \"\n \"(ENDIF, ENDFOR, ENDWHILE, END RITE).\"\n ),\n \"RUNTIME_ERROR\": (\n \"The scroll parsed but stumbled while running. DECLARE every \"\n \"name before use and re-read the reported line.\"\n ),\n \"FILE_ERROR\": \"Check the path. The scroll must exist and be readable.\",\n}\n\n\ndef _to_snake(name: str) -> str:\n return re.sub(r\"(? str:\n \"\"\"Map a God Code exception to its stable machine code.\"\"\"\n name = type(err).__name__\n if name in _CODE_MAP:\n return _CODE_MAP[name]\n snake = _to_snake(name)\n return snake if snake.endswith(\"_ERROR\") else snake + \"_ERROR\"\n\n\ndef hint_for(code: str) -> str | None:\n \"\"\"One-line actionable suggestion for a code, or None.\"\"\"\n return _HINTS.get(code)\n\n\ndef diagnostic(err, *, severity: str = \"error\") -> dict:\n \"\"\"Turn a GodCodeError into a JSON-serializable diagnostic dict.\"\"\"\n code = error_code(err)\n # err.msg is the clean message; str(err) may append \"(line N)\" which\n # would duplicate the structured line/col fields below.\n return {\n \"line\": getattr(err, \"line\", None),\n \"col\": getattr(err, \"col\", None),\n \"code\": code,\n \"severity\": severity,\n \"message\": getattr(err, \"msg\", None) or str(err),\n \"hint\": hint_for(code),\n }\n\n\ndef error_trace(err) -> list[dict]:\n \"\"\"The ``run --json`` trace array for a failed run.\n\n A list of ``{\"rite\": name, \"line\": call-site line}``, oldest call first\n (the most recent call is last). Empty when the error rose at the top\n level, before any rite was called. The interpreter snapshots\n ``err.call_trace`` when the error first rises, before the call stack\n unwinds.\n \"\"\"\n return [\n {\"rite\": frame.get(\"rite\"), \"line\": frame.get(\"line\")}\n for frame in (getattr(err, \"call_trace\", None) or [])\n ]\n\n\ndef _file_error_diagnostic(path: str, exc: OSError) -> dict:\n detail = exc.strerror or str(exc)\n return {\n \"line\": None,\n \"col\": None,\n \"code\": \"FILE_ERROR\",\n \"severity\": \"error\",\n \"message\": f\"godcode: cannot read '{path}': {detail}\",\n \"hint\": hint_for(\"FILE_ERROR\"),\n }\n\n\n# ---------------------------------------------------------------------------\n# payload builders\n# ---------------------------------------------------------------------------\ndef check_payload(file: str, ok: bool, diagnostics: list[dict]) -> dict:\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"check\",\n \"file\": file,\n \"ok\": ok,\n \"diagnostics\": diagnostics,\n }\n\n\ndef run_payload(file: str, ok: bool, output: list[str],\n seals: list[dict], error: dict | None, ms: int,\n intents: list[dict] | None = None,\n permissions: dict | None = None) -> dict:\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"run\",\n \"file\": file,\n \"ok\": ok,\n \"output\": output,\n \"seals\": seals,\n \"intents\": intents if intents is not None else [],\n \"permissions\": permissions if permissions is not None else {},\n \"error\": error,\n \"stats\": {\"ms\": ms},\n }\n\n\ndef emit(payload: dict) -> None:\n \"\"\"Write one JSON document to stdout; nothing else may be printed.\"\"\"\n sys.stdout.write(json.dumps(payload, ensure_ascii=False) + \"\\n\")\n sys.stdout.flush()\n\n\n# ---------------------------------------------------------------------------\n# --json command implementations (called from godcode.cli)\n# ---------------------------------------------------------------------------\ndef cmd_check_json(args) -> int:\n \"\"\"`godcode check --json FILE`. Exit 0 if pure, 1 if diagnostics.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n emit(check_payload(args.file, False, [_file_error_diagnostic(args.file, exc)]))\n return 1\n try:\n parse_source(source)\n except GodCodeError as err:\n emit(check_payload(args.file, False, [diagnostic(err)]))\n return 1\n emit(check_payload(args.file, True, []))\n return 0\n\n\ndef _ledger_block_count(interp) -> int | None:\n ledger = getattr(interp, \"ledger\", None)\n if ledger is None:\n return None\n try:\n return len(ledger.read_all())\n except Exception:\n return None\n\n\ndef _new_seals(interp, before: int | None) -> list[dict]:\n \"\"\"Best-effort list of covenant blocks sealed during the run.\"\"\"\n if before is None:\n return []\n ledger = getattr(interp, \"ledger\", None)\n if ledger is None:\n return []\n try:\n blocks = ledger.read_all()[before:]\n except Exception:\n return []\n seals = []\n for block in blocks:\n if isinstance(block, dict) and \"hash\" in block:\n seals.append({\"block\": block.get(\"index\"), \"hash\": block.get(\"hash\")})\n return seals\n\n\ndef cmd_run_json(args) -> int:\n \"\"\"`godcode run --json FILE`. Exit 0 on success, 1 on failure.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.cli import _make_interpreter # shared with the plain run path\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n emit(run_payload(args.file, False, [], [], _file_error_diagnostic(args.file, exc), 0))\n return 1\n\n interp = _make_interpreter(args.log)\n seals_before = _ledger_block_count(interp)\n\n buf = io.StringIO()\n error: dict | None = None\n start = time.perf_counter()\n with contextlib.redirect_stdout(buf):\n try:\n interp.run_source(source, source_name=args.file)\n except GodCodeError as err:\n error = diagnostic(err)\n error[\"trace\"] = error_trace(err)\n ms = int((time.perf_counter() - start) * 1000)\n\n output = buf.getvalue().splitlines()\n seals = _new_seals(interp, seals_before)\n intents = list(getattr(interp, \"intent_checks\", []) or [])\n manifest = getattr(interp, \"manifest\", None)\n emit(run_payload(args.file, error is None, output, seals, error, ms,\n intents=intents,\n permissions=manifest.to_json() if manifest else {}))\n return 0 if error is None else 1\n","godcode/ast.py":"\"\"\"Abstract syntax tree nodes for God Code v2.0.\n\nEvery node carries 1-based ``line``/``col`` of the token that opened it.\nExpression fields are annotated with the ``Expr`` alias (a union of all\nexpression node types).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom typing import Union\n\n# Filled in below once the classes exist; string form keeps runtime cheap.\nExpr = Union[\n \"BinaryOp\", \"UnaryOp\", \"Literal\", \"Identifier\",\n \"ListLiteral\", \"Index\", \"CallExpr\",\n]\n\n\n# -- program structure -------------------------------------------------------\n\n@dataclass\nclass Program:\n statements: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass CreationBlock:\n statements: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n# -- statements --------------------------------------------------------------\n\n@dataclass\nclass Declare:\n name: str\n value: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass DeclareIntent:\n \"\"\"DECLARE INTENT \"words...\" ON rite_name -- the v4.0 intent layer.\"\"\"\n text: str\n rite: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass DeclarePermission:\n \"\"\"DECLARE PERMISSION TO -- the permission manifest.\n\n ``power`` is one of \"read\", \"write\", \"network\", \"stdin\", \"summon\";\n ``target`` is the granted path, host, or verb name (None for stdin).\n \"\"\"\n power: str\n target: str | None\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Breathe:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Reveal:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Prophesy:\n text: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Ascend:\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Reflect:\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Bless:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Anoint:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass SealStmt:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Testify:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass IfStmt:\n cond: Expr\n then_body: list = field(default_factory=list)\n else_body: list = field(default_factory=list)\n has_else: bool = False # True when an ELSE keyword was actually written\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass ForLoop:\n var: str\n iterable: Expr\n body: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass WhileLoop:\n cond: Expr\n body: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Break:\n \"\"\"BREAK: release the innermost enclosing loop at once.\"\"\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Continue:\n \"\"\"CONTINUE: skip to the next turn of the innermost enclosing loop.\"\"\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass TryStmt:\n \"\"\"TRY ... CATCH [name] ... ENDTRY: in-language error handling.\n\n The TRY block runs first; if a runtime error (GodRuntimeError) rises,\n the error's plain message is bound to ``error_name`` and the CATCH\n block runs. ``error_name`` defaults to \"ERROR\" when the CATCH carries\n no name. Control-flow signals (RETURN, ASCEND) are never caught.\n \"\"\"\n try_body: list = field(default_factory=list)\n catch_body: list = field(default_factory=list)\n error_name: str = \"ERROR\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass DefineRite:\n name: str\n params: list = field(default_factory=list) # list[str]\n body: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Return:\n expr: Expr | None = None\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Import:\n path: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass ExprStmt:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n# -- expressions -------------------------------------------------------------\n\n@dataclass\nclass BinaryOp:\n # op: '+','-','*','/','%', '==','!=','<','>','<=','>=', 'and','or'\n op: str\n left: Expr\n right: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass UnaryOp:\n # op: 'not', '-'\n op: str\n operand: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Literal:\n value: object # int | float | str | bool | None\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass InterpolatedString:\n \"\"\"A string holding ``{expr}`` blessings: parts are literal text (str)\n or expression nodes whose revealed value is breathed into the string.\n ``source`` keeps the original string content so formatters can re-emit it.\n \"\"\"\n\n parts: list = field(default_factory=list) # list[str | Expr]\n source: str = \"\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Identifier:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass ListLiteral:\n items: list = field(default_factory=list) # list[Expr]\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Index:\n obj: Expr\n index: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass CallExpr:\n callee: str\n args: list = field(default_factory=list) # list[Expr]\n line: int = 1\n col: int = 1\n","godcode/chain.py":"\"\"\"Blockchain-anchored seals for God Code v4.0 -- \"Intent & Chain\".\n\nA ChainAdapter anchors a payload hash into a tamper-evident chain and\nlater verifies the receipt it handed back. The bundled\nSimulatedChainAdapter keeps the anchor chain as local JSONL\n(``anchors.chain``), mirroring :class:`godcode.ledger.CovenantLedger`;\nreal chain adapters (Ethereum, and the like) can be registered later\nwith :func:`register_adapter` -- that work belongs to the founder, not\nto this module. There are no network calls here, no wallets, no keys.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom datetime import datetime, timezone\nfrom pathlib import Path\n\nGENESIS_PREV_HASH = \"GENESIS\"\nDEFAULT_CHAIN_NAME = \"simulated\"\n\n\ndef _canonical(payload: dict) -> bytes:\n \"\"\"Canonical JSON bytes used for hashing (stable key order, no whitespace).\"\"\"\n return json.dumps(payload, sort_keys=True, separators=(\",\", \":\"),\n ensure_ascii=False).encode(\"utf-8\")\n\n\ndef _block_hash(index: int, timestamp: str, record: dict, prev_hash: str) -> str:\n return hashlib.sha256(\n _canonical(\n {\"index\": index, \"timestamp\": timestamp,\n \"record\": record, \"prev_hash\": prev_hash}\n )\n ).hexdigest()\n\n\nclass ChainAdapter:\n \"\"\"The contract every chain adapter honors.\n\n ``anchor(payload_hash)`` writes the hash into the chain and returns a\n receipt dict; ``verify(receipt)`` returns True only when the receipt\n matches a block that is still intact.\n \"\"\"\n\n name = \"adapter\"\n\n def anchor(self, payload_hash: str) -> dict:\n raise NotImplementedError\n\n def verify(self, receipt: dict) -> bool:\n raise NotImplementedError\n\n\nclass SimulatedChainAdapter(ChainAdapter):\n \"\"\"A local tamper-evident anchor chain (JSONL), standing in for a chain.\n\n Blocks look like ``{index, timestamp, record: {payload_hash},\n prev_hash, hash}``; the chain begins at ``\"GENESIS\"``. Receipts look\n like ``{chain, anchor_hash, height, timestamp, payload_hash}``.\n \"\"\"\n\n name = \"simulated\"\n\n def __init__(self, path: str | Path | None = \"anchors.chain\") -> None:\n self.path = Path(path) if path is not None else None\n self._memory: list[dict] = []\n if self.path is not None and str(self.path.parent) not in (\"\", \".\"):\n self.path.parent.mkdir(parents=True, exist_ok=True)\n\n # ---------------------------------------------------------- persistence\n\n def read_all(self) -> list[dict]:\n \"\"\"Every anchor block in chain order (empty when no chain yet).\"\"\"\n if self.path is None:\n return list(self._memory)\n if not self.path.exists():\n return []\n blocks: list[dict] = []\n with open(self.path, encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n if line:\n blocks.append(json.loads(line))\n return blocks\n\n def _append(self, block: dict) -> None:\n if self.path is None:\n self._memory.append(block)\n else:\n with open(self.path, \"a\", encoding=\"utf-8\") as f:\n f.write(json.dumps(block, ensure_ascii=False) + \"\\n\")\n\n # ------------------------------------------------------------- adapter\n\n def anchor(self, payload_hash: str) -> dict:\n \"\"\"Anchor a payload hash; return the receipt dict.\"\"\"\n blocks = self.read_all()\n index = len(blocks)\n prev_hash = blocks[-1][\"hash\"] if blocks else GENESIS_PREV_HASH\n timestamp = datetime.now(timezone.utc).isoformat()\n record = {\"payload_hash\": payload_hash}\n block = {\n \"index\": index,\n \"timestamp\": timestamp,\n \"record\": record,\n \"prev_hash\": prev_hash,\n \"hash\": _block_hash(index, timestamp, record, prev_hash),\n }\n self._append(block)\n return {\n \"chain\": self.name,\n \"anchor_hash\": block[\"hash\"],\n \"height\": block[\"index\"],\n \"timestamp\": block[\"timestamp\"],\n \"payload_hash\": payload_hash,\n }\n\n def verify(self, receipt: dict) -> bool:\n \"\"\"True when the receipt names a block that is present and intact.\"\"\"\n try:\n height = receipt[\"height\"]\n anchor_hash = receipt[\"anchor_hash\"]\n payload_hash = receipt[\"payload_hash\"]\n except (KeyError, TypeError, AttributeError):\n return False\n if not isinstance(height, int) or isinstance(height, bool):\n return False\n blocks = self.read_all()\n if height < 0 or height >= len(blocks):\n return False\n block = blocks[height]\n if block.get(\"hash\") != anchor_hash:\n return False\n if block.get(\"record\", {}).get(\"payload_hash\") != payload_hash:\n return False\n return _block_hash(\n block.get(\"index\"),\n block.get(\"timestamp\"),\n block.get(\"record\"),\n block.get(\"prev_hash\"),\n ) == block.get(\"hash\")\n\n def verify_chain(self) -> tuple[bool, str]:\n \"\"\"Recompute the whole anchor chain.\n\n (True, 'N anchors intact') or (False, 'anchor chain broken at\n block K').\n \"\"\"\n blocks = self.read_all()\n prev_hash = GENESIS_PREV_HASH\n for expected, block in enumerate(blocks):\n payload_ok = (\n block.get(\"index\") == expected\n and block.get(\"prev_hash\") == prev_hash\n and _block_hash(\n block.get(\"index\"),\n block.get(\"timestamp\"),\n block.get(\"record\"),\n block.get(\"prev_hash\"),\n )\n == block.get(\"hash\")\n )\n if not payload_ok:\n return False, f\"anchor chain broken at block {block.get('index')} ⚓💔\"\n prev_hash = block[\"hash\"]\n return True, f\"{len(blocks)} anchors intact ⚓\"\n\n\nclass MemoryChainAdapter(SimulatedChainAdapter):\n \"\"\"An ephemeral in-memory anchor chain: the sandbox's answer to ANCHOR.\n\n Same interface as the simulated chain, but nothing is written to\n disk. Anchors made here vanish when the run ends -- which is exactly\n what a deny-by-default sandbox requires.\n \"\"\"\n\n name = \"simulated\"\n\n def __init__(self) -> None:\n super().__init__(path=None)\n\n\n# ------------------------------------------------------------- registry\n\n_ADAPTERS: dict[str, ChainAdapter] = {}\n\n\ndef register_adapter(name: str, adapter: ChainAdapter) -> None:\n \"\"\"Register a chain adapter under *name* (e.g. a future real chain).\"\"\"\n if not isinstance(name, str) or not name:\n raise ValueError(\"a chain adapter needs a non-empty string name\")\n if not isinstance(adapter, ChainAdapter):\n raise ValueError(f\"'{name}' is not a ChainAdapter\")\n _ADAPTERS[name] = adapter\n\n\ndef get_adapter(name: str) -> ChainAdapter | None:\n \"\"\"The adapter registered under *name*, or None.\"\"\"\n return _ADAPTERS.get(name)\n\n\ndef default_adapters() -> dict[str, ChainAdapter]:\n \"\"\"A fresh per-interpreter registry holding the bundled adapters.\"\"\"\n adapters = dict(_ADAPTERS)\n adapters.setdefault(DEFAULT_CHAIN_NAME, SimulatedChainAdapter())\n return adapters\n\n\nregister_adapter(DEFAULT_CHAIN_NAME, SimulatedChainAdapter())\n","godcode/cli.py":"\"\"\"Command-line interface for the God Code engine.\n\nSubcommands: run, check, repl, fmt, ledger verify.\nSibling modules (lexer, parser, ast, interpreter, ledger, errors) are imported\nlazily inside each command so `--help` works even before they land.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\nimport os\nimport sys\nfrom pathlib import Path\n\n\n# ---------------------------------------------------------------------------\n# run\n# ---------------------------------------------------------------------------\ndef _print_run_error(source: str, err) -> None:\n \"\"\"Print a failed run's error the gentle way, then the call trace.\n\n The gentle rendering (message, line/col, source line, caret,\n Did-you-mean) is preserved exactly; the trace goes underneath in plain\n words. Errors raised at the top level carry an empty trace and show no\n trace section.\n \"\"\"\n from godcode.errors import format_call_trace, format_error\n\n print(format_error(source, err), file=sys.stderr)\n trace = list(getattr(err, \"call_trace\", None) or [])\n for line in format_call_trace(trace):\n print(line, file=sys.stderr)\n\n\n# --- v3: agentics --json ---\ndef _make_interpreter(log_path):\n \"\"\"Build an Interpreter the way `godcode run` always has, shared by the\n plain and --json run paths so they can never drift apart.\"\"\"\n from godcode.interpreter import Interpreter\n\n kwargs: dict = {}\n if log_path:\n kwargs[\"log_path\"] = log_path\n # Bind the Spirit and the covenant ledger by default; degrade\n # gracefully if either cannot be raised in this environment.\n try:\n from godcode.spirit import SpiritEngine\n kwargs[\"spirit\"] = SpiritEngine()\n except Exception:\n pass\n try:\n from godcode.ledger import CovenantLedger\n kwargs[\"ledger\"] = CovenantLedger()\n except Exception:\n pass\n return Interpreter(**kwargs)\n# --- end v3: agentics --json ---\n\n\ndef cmd_run(args: argparse.Namespace) -> int:\n from godcode.errors import GodCodeError\n\n # --- v3: sandbox commands ---\n if getattr(args, \"sandbox\", False):\n return _cmd_run_sandboxed(args)\n # --- end v3: sandbox commands ---\n\n # --- v3: agentics --json ---\n if getattr(args, \"json\", False):\n from godcode import agentics\n return agentics.cmd_run_json(args)\n # --- end v3: agentics --json ---\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n\n try:\n _make_interpreter(args.log).run_source(source, source_name=args.file)\n except GodCodeError as err:\n _print_run_error(source, err)\n return 1\n return 0\n\n\n# --- v3: sandbox commands ---\ndef _cmd_run_sandboxed(args: argparse.Namespace) -> int:\n \"\"\"Run a scroll under the strict sandbox policy.\n\n Spirit, covenant ledger, and the audit log stay unbound: they write\n to the host world, which the sandbox does not permit. The CLI itself\n reads the scroll file before the sandbox is entered — that read is\n the invoker's own act, not the creation's.\n \"\"\"\n from godcode.errors import GodCodeError\n from godcode.sandbox import SandboxPolicy, run_sandboxed\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(agentics.run_payload(\n args.file, False, [], [],\n agentics._file_error_diagnostic(args.file, exc), 0))\n else:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n\n source_dir = str(Path(args.file).resolve().parent)\n policy = SandboxPolicy.strict(\n source_dir=source_dir,\n timeout_seconds=args.sandbox_timeout,\n )\n if getattr(args, \"json\", False):\n # Machine-readable report; stdout carries exactly one JSON document.\n import contextlib\n import io\n import time as _time\n\n from godcode import agentics\n from godcode.sandbox import run_sandboxed_with_interpreter\n\n error = None\n output: list[str] = []\n intents: list[dict] = []\n interp = None\n start = _time.perf_counter()\n with contextlib.redirect_stdout(io.StringIO()):\n try:\n output, interp = run_sandboxed_with_interpreter(\n source, policy, source_name=args.file)\n intents = list(getattr(interp, \"intent_checks\", []) or [])\n except GodCodeError as err:\n error = agentics.diagnostic(err)\n error[\"trace\"] = agentics.error_trace(err)\n ms = int((_time.perf_counter() - start) * 1000)\n manifest = getattr(interp, \"manifest\", None)\n agentics.emit(agentics.run_payload(\n args.file, error is None, output, [], error, ms,\n intents=intents,\n permissions=manifest.to_json() if manifest else {}))\n return 0 if error is None else 1\n try:\n run_sandboxed(source, policy, source_name=args.file)\n except GodCodeError as err:\n _print_run_error(source, err)\n return 1\n return 0\n# --- end v3: sandbox commands ---\n\n\n# ---------------------------------------------------------------------------\n# check\n# ---------------------------------------------------------------------------\ndef cmd_check(args: argparse.Namespace) -> int:\n from godcode.errors import GodCodeError, format_error\n from godcode.tongues import parse_source\n\n # --- v3: agentics --json ---\n if getattr(args, \"json\", False):\n from godcode import agentics\n return agentics.cmd_check_json(args)\n # --- end v3: agentics --json ---\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n parse_source(source)\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n print(f\"✓ {args.file} is pure.\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# lint\n# ---------------------------------------------------------------------------\ndef cmd_lint(args: argparse.Namespace) -> int:\n import json as _json\n\n from godcode.errors import GodCodeError, format_error\n from godcode.linter import lint_source\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n findings = lint_source(source, source_name=args.file)\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n\n if getattr(args, \"json\", False):\n print(_json.dumps(\n {\"tool\": \"godcode\", \"command\": \"lint\", \"file\": args.file,\n \"ok\": not findings,\n \"findings\": [{\"line\": f.line, \"col\": f.col, \"rule\": f.rule,\n \"message\": f.message} for f in findings]},\n ensure_ascii=False))\n return 1 if findings else 0\n for f in findings:\n print(f\"line {f.line}, col {f.col} [{f.rule}] {f.message}\")\n return 1 if findings else 0\n\n\n# ---------------------------------------------------------------------------\n# test — the test runner\n# ---------------------------------------------------------------------------\ndef cmd_test(args: argparse.Namespace) -> int:\n import json as _json\n\n from godcode import tester\n\n target = Path(args.dir)\n if not target.is_dir():\n print(f\"godcode: '{args.dir}' is not a directory to test.\",\n file=sys.stderr)\n return 2\n report = tester.run_tests(target)\n if getattr(args, \"json\", False):\n print(_json.dumps(report.payload(args.dir), ensure_ascii=False))\n else:\n for line in report.text_lines():\n print(line)\n return 1 if report.failed else 0\n\n\n# ---------------------------------------------------------------------------\n# new — raise a fresh God Code project\n# ---------------------------------------------------------------------------\ndef cmd_new(args: argparse.Namespace) -> int:\n import json as _json\n\n from godcode.scaffold import ScaffoldError, create_project\n\n try:\n result = create_project(args.name, dest=args.path, author=args.author)\n except ScaffoldError as exc:\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"new\",\n \"ok\": False, \"error\": str(exc)},\n ensure_ascii=False))\n else:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n if getattr(args, \"json\", False):\n print(_json.dumps({\n \"tool\": \"godcode\", \"command\": \"new\", \"ok\": True,\n \"name\": result.name,\n \"directory\": str(result.directory),\n \"files\": result.files,\n }, ensure_ascii=False))\n return 0\n print(f\"🕊 A new scroll rises: {result.directory}\")\n for filename in result.files:\n print(f\" wrote {result.directory / filename}\")\n print(\"\")\n print(\"Next steps:\")\n print(f\" cd {result.directory}\")\n print(\" godcode run main.god # speak it\")\n print(\" godcode test . # test it\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# repl\n# ---------------------------------------------------------------------------\ndef cmd_repl(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.errors import GodCodeError, format_error\n from godcode.interpreter import Interpreter\n\n try:\n import readline # noqa: F401 (enables history + line editing)\n except ImportError:\n pass\n\n print(\"God Code Live Mode 🕊\")\n print(\"Speak your creation; end each utterance with a blank line. \"\n \"(:quit to ascend)\")\n interp = Interpreter(interactive=True)\n buf: list[str] = []\n while True:\n try:\n line = input(\"godcode> \" if not buf else \"...... \")\n except EOFError:\n print()\n break\n except KeyboardInterrupt:\n print()\n break\n if line.strip() in (\":quit\", \":q\"):\n break\n if not line.strip():\n if buf:\n chunk = \"\\n\".join(buf)\n buf = []\n try:\n interp.run_source(chunk, source_name=\"\")\n except GodCodeError as err:\n print(str(err), file=sys.stderr)\n continue\n buf.append(line)\n print(\"🕊 The sanctuary rests.\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# fmt — AST -> canonical God Code\n# ---------------------------------------------------------------------------\n_PRECEDENCE = {\n \"or\": 1, \"and\": 2,\n \"==\": 3, \"!=\": 3, \"<\": 3, \">\": 3, \"<=\": 3, \">=\": 3,\n \"+\": 4, \"-\": 4, \"*\": 5, \"/\": 5, \"%\": 5,\n}\n_UNARY_PREC = 6\n_BLOCK_NODES = {\"CreationBlock\", \"IfStmt\", \"ForLoop\", \"WhileLoop\",\n \"DefineRite\", \"TryStmt\"}\n\n\ndef _escape(text: str) -> str:\n return (text.replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"')\n .replace(\"\\n\", \"\\\\n\").replace(\"\\t\", \"\\\\t\"))\n\n\nclass CanonicalFormatter:\n \"\"\"Re-emit an AST as canonical God Code: keywords UPPER, 2-space indent,\n one statement per line, blank line between top-level blocks.\"\"\"\n\n def __init__(self) -> None:\n self._lines: list[str] = []\n self._depth = 0\n\n # -- driver ---------------------------------------------------------\n def format(self, program) -> str:\n prev_was_block = False\n for i, stmt in enumerate(program.statements):\n is_block = type(stmt).__name__ in _BLOCK_NODES\n if i and (is_block or prev_was_block):\n self._lines.append(\"\")\n self._emit_stmt(stmt)\n prev_was_block = is_block\n return \"\\n\".join(self._lines) + \"\\n\"\n\n def _emit_stmt(self, node) -> None:\n meth = getattr(self, \"_stmt_\" + type(node).__name__, None)\n if meth is None:\n raise ValueError(\n f\"the formatter knows not this node: {type(node).__name__}\")\n meth(node)\n\n def _line(self, text: str) -> None:\n self._lines.append(\" \" * self._depth + text)\n\n def _block(self, stmts) -> None:\n self._depth += 1\n for stmt in stmts:\n self._emit_stmt(stmt)\n self._depth -= 1\n\n # -- expressions ----------------------------------------------------\n def _expr(self, node, parent_prec: int = 0) -> str:\n kind = type(node).__name__\n if kind == \"BinaryOp\":\n prec = _PRECEDENCE[node.op]\n op = node.op.upper() if node.op in (\"and\", \"or\") else node.op\n text = (f\"{self._expr(node.left, prec)} {op} \"\n f\"{self._expr(node.right, prec + 1)}\")\n return f\"({text})\" if prec < parent_prec else text\n if kind == \"UnaryOp\":\n inner = self._expr(node.operand, _UNARY_PREC)\n if type(node.operand).__name__ == \"UnaryOp\":\n inner = f\"({inner})\"\n return f\"NOT {inner}\" if node.op == \"not\" else f\"-{inner}\"\n if kind == \"Literal\":\n return self._literal(node.value)\n if kind == \"InterpolatedString\":\n return f'\"{_escape(node.source)}\"'\n if kind == \"Identifier\":\n return node.name\n if kind == \"ListLiteral\":\n return \"[\" + \", \".join(self._expr(i) for i in node.items) + \"]\"\n if kind == \"Index\":\n return f\"{self._expr(node.obj, _UNARY_PREC)}[{self._expr(node.index)}]\"\n if kind == \"CallExpr\":\n return (f\"{node.callee}(\"\n + \", \".join(self._expr(a) for a in node.args) + \")\")\n raise ValueError(\n f\"the formatter knows not this expression: {kind}\")\n\n @staticmethod\n def _literal(value) -> str:\n if isinstance(value, str):\n return f'\"{_escape(value)}\"'\n if value is True:\n return \"true\"\n if value is False:\n return \"false\"\n if value is None:\n return \"void\"\n return repr(value)\n\n # -- statements -----------------------------------------------------\n def _stmt_CreationBlock(self, node) -> None:\n self._line(\"BEGIN CREATION\")\n self._block(node.statements)\n self._line(\"END CREATION\")\n\n def _stmt_Declare(self, node) -> None:\n value = node.value\n if type(value).__name__ == \"ListLiteral\":\n rhs = \", \".join(self._expr(i) for i in value.items)\n else:\n rhs = self._expr(value)\n self._line(f\"DECLARE {node.name} AS {rhs}\")\n\n def _stmt_DeclareIntent(self, node) -> None: # v4.0\n self._line(f'DECLARE INTENT \"{_escape(node.text)}\" ON {node.rite}')\n\n def _stmt_DeclarePermission(self, node) -> None:\n power = node.power.upper()\n if power == \"READ\":\n self._line(f'DECLARE PERMISSION TO READ \"{_escape(node.target)}\"')\n elif power == \"WRITE\":\n self._line(f'DECLARE PERMISSION TO WRITE \"{_escape(node.target)}\"')\n elif power == \"NETWORK\":\n self._line(f'DECLARE PERMISSION TO SPEAK WITH \"{_escape(node.target)}\"')\n elif power == \"STDIN\":\n self._line(\"DECLARE PERMISSION TO ASK THE WORLD\")\n elif power == \"SUMMON\":\n self._line(f'DECLARE PERMISSION TO SUMMON \"{_escape(node.target)}\"')\n\n def _stmt_Breathe(self, node) -> None:\n self._line(f\"BREATHE LIFE INTO {node.name}\")\n\n def _stmt_Reveal(self, node) -> None:\n self._line(f\"REVEAL({self._expr(node.expr)})\")\n\n def _stmt_Prophesy(self, node) -> None:\n self._line(f\"PROPHESY {node.text}\".rstrip())\n\n def _stmt_Ascend(self, node) -> None:\n self._line(\"ASCEND\")\n\n def _stmt_Reflect(self, node) -> None:\n self._line(\"REFLECT\")\n\n def _stmt_Bless(self, node) -> None:\n self._line(f\"BLESS {node.name}\")\n\n def _stmt_Anoint(self, node) -> None:\n self._line(f\"ANOINT {node.name}\")\n\n def _stmt_SealStmt(self, node) -> None:\n self._line(f\"SEAL {self._expr(node.expr)}\")\n\n def _stmt_Testify(self, node) -> None:\n self._line(f\"TESTIFY {self._expr(node.expr)}\")\n\n def _stmt_IfStmt(self, node) -> None:\n self._line(f\"IF {self._expr(node.cond)} THEN\")\n self._block(node.then_body)\n if node.else_body:\n self._line(\"ELSE\")\n self._block(node.else_body)\n self._line(\"ENDIF\")\n\n def _stmt_ForLoop(self, node) -> None:\n self._line(f\"FOR {node.var} IN {self._expr(node.iterable)}\")\n self._block(node.body)\n self._line(\"ENDFOR\")\n\n def _stmt_WhileLoop(self, node) -> None:\n self._line(f\"WHILE {self._expr(node.cond)} DO\")\n self._block(node.body)\n self._line(\"ENDWHILE\")\n\n def _stmt_TryStmt(self, node) -> None:\n self._line(\"TRY\")\n self._block(node.try_body)\n if node.error_name == \"ERROR\":\n self._line(\"CATCH\")\n else:\n self._line(f\"CATCH {node.error_name}\")\n self._block(node.catch_body)\n self._line(\"ENDTRY\")\n\n def _stmt_DefineRite(self, node) -> None:\n params = \", \".join(node.params)\n self._line(f\"DEFINE RITE {node.name}({params})\")\n self._block(node.body)\n self._line(\"END RITE\")\n\n def _stmt_Return(self, node) -> None:\n self._line(\"RETURN\" if node.expr is None\n else f\"RETURN {self._expr(node.expr)}\")\n\n def _stmt_Break(self, node) -> None:\n self._line(\"BREAK\")\n\n def _stmt_Continue(self, node) -> None:\n self._line(\"CONTINUE\")\n\n def _stmt_Import(self, node) -> None:\n self._line(f'IMPORT \"{_escape(node.path)}\"')\n\n def _stmt_ExprStmt(self, node) -> None:\n expr = node.expr\n if type(expr).__name__ == \"CallExpr\":\n args = \", \".join(self._expr(a) for a in expr.args)\n self._line(f\"INVOKE {expr.callee}({args})\")\n else:\n self._line(self._expr(expr))\n\n\ndef cmd_fmt(args: argparse.Namespace) -> int:\n from godcode.errors import GodCodeError, format_error\n from godcode.tongues import parse_source\n\n src_path = Path(args.file)\n try:\n source = src_path.read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n program = parse_source(source)\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n\n canonical = CanonicalFormatter().format(program)\n if args.in_place:\n src_path.write_text(canonical, encoding=\"utf-8\")\n else:\n sys.stdout.write(canonical)\n return 0\n\n\n# ---------------------------------------------------------------------------\n# ledger verify\n# ---------------------------------------------------------------------------\ndef cmd_ledger_verify(args: argparse.Namespace) -> int:\n # v4.0: verifies the covenant chain AND the anchor chain, reporting both.\n import json as _json\n\n from godcode.chain import SimulatedChainAdapter\n from godcode.ledger import CovenantLedger\n\n cov_ok, cov_message = CovenantLedger(args.file).verify()\n anc_ok, anc_message = SimulatedChainAdapter(args.anchor_file).verify_chain()\n if getattr(args, \"json\", False):\n _json_doc = {\n \"tool\": \"godcode\",\n \"command\": \"ledger\",\n \"subcommand\": \"verify\",\n \"ok\": cov_ok and anc_ok,\n \"covenant\": {\"ok\": cov_ok, \"message\": cov_message},\n \"anchors\": {\"ok\": anc_ok, \"message\": anc_message},\n }\n print(_json.dumps(_json_doc, ensure_ascii=False))\n return 0 if (cov_ok and anc_ok) else 1\n print(cov_message)\n print(anc_message)\n return 0 if (cov_ok and anc_ok) else 1\n\n\n# --- v3: scroll commands ---\n# Pillar 2 — Scroll Registry: publish/install/info/list installable scrolls.\n\n\ndef _scroll_registry():\n from godcode.registry import ScrollRegistry\n\n return ScrollRegistry()\n\n\ndef cmd_scroll_list(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.registry import ScrollError\n\n try:\n rows = _scroll_registry().list_installed()\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n if not rows:\n print(\"No scrolls installed. \"\n \"Publish one with `godcode scroll publish `, \"\n \"then `godcode scroll install `.\")\n return 0\n for row in rows:\n loc = \",\".join(row[\"locations\"])\n vers = \", \".join(row[\"versions\"])\n print(f\"{row['name']} {vers} [{loc}]\")\n return 0\n\n\ndef cmd_scroll_install(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError, ScrollNotFoundError\n\n try:\n try:\n receipt = _scroll_registry().install(\n args.name, version=args.version, project=args.project,\n remote=args.remote)\n except ScrollNotFoundError:\n if args.remote:\n raise\n # not in the local index: fall back to the remote registry\n receipt = _scroll_registry().install(\n args.name, version=args.version, project=args.project,\n remote=True)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n where = \"project-local\" if args.project else \"user-global\"\n desc = receipt[\"manifest\"][\"description\"][:60]\n deps = receipt.get(\"dependencies\") or {}\n dep_note = f\" (+{len(deps)} dependencies)\" if deps else \"\"\n print(f\"Installed {receipt['name']} {receipt['version']}{dep_note} \"\n f\"({where}, from {receipt.get('source', 'local')}: {desc}...)\")\n return 0\n\n\ndef cmd_scroll_publish(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError, read_manifest\n\n if not args.remote:\n try:\n manifest = _scroll_registry().publish(args.dir)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n print(f\"Published {manifest['name']} {manifest['version']} \"\n f\"to the local registry.\")\n return 0\n\n # --remote: push to the registry over HTTPS; needs a publish token.\n token = os.environ.get(\"GODCODE_PUBLISH_TOKEN\")\n if not token:\n print(\"godcode: publishing to the remote registry needs a publish \"\n \"token.\", file=sys.stderr)\n print(\"godcode: set the GODCODE_PUBLISH_TOKEN environment variable \"\n \"to your registry token and try again.\", file=sys.stderr)\n return 1\n from godcode.remote_registry import RegistryClientError, RemoteRegistry\n\n src = Path(args.dir)\n manifest_path = src / \"scroll.toml\"\n try:\n manifest = read_manifest(manifest_path)\n entry = src / manifest[\"entry\"]\n if not entry.is_file():\n raise ScrollError(\n f\"publish: entry file {manifest['entry']!r} not found in {src}\"\n )\n code = entry.read_text(encoding=\"utf-8\")\n except (ScrollError, OSError) as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n try:\n RemoteRegistry().publish_scroll(\n name=manifest[\"name\"],\n version=manifest[\"version\"],\n code=code,\n description=manifest[\"description\"],\n author=manifest[\"author\"],\n token=token,\n )\n except RegistryClientError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n print(f\"Published {manifest['name']} {manifest['version']} \"\n f\"to the remote registry.\")\n return 0\n\n\ndef cmd_scroll_search(args: argparse.Namespace) -> int:\n from godcode.remote_registry import RegistryClientError, RemoteRegistry\n\n try:\n rows = RemoteRegistry().search(args.query)\n except RegistryClientError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n if not rows:\n print(f\"No scrolls found for {args.query!r} in the remote registry.\")\n return 0\n for row in rows:\n desc = (row.get(\"description\") or \"\")[:70]\n print(f\"{row.get('name')} {row.get('latest', '?')} - {desc}\")\n return 0\n\n\ndef cmd_scroll_uninstall(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError\n\n try:\n removed = _scroll_registry().uninstall(args.name,\n version=args.version)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n for entry in removed:\n print(f\"Uninstalled {entry['name']} {entry['version']} \"\n f\"({entry['location']})\")\n return 0\n\n\ndef cmd_scroll_update(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError\n\n try:\n results = _scroll_registry().update(name=args.name,\n remote=args.remote)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n for result in results:\n if result.get(\"up_to_date\"):\n print(f\"{result['name']} is already at the newest version \"\n f\"({result['from']})\")\n else:\n print(f\"Updated {result['name']} {result['from']} -> \"\n f\"{result['to']} (from {result['source']})\")\n return 0\n\n\ndef cmd_scroll_info(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError\n\n try:\n info = _scroll_registry().info(args.name)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n print(f\"name: {info['name']}\")\n if info[\"manifest\"]:\n manifest = info[\"manifest\"]\n print(f\"version: {info['latest']} (latest published)\")\n print(f\"author: {manifest['author']}\")\n print(f\"entry: {manifest['entry']}\")\n print(f\"godcode: {manifest['godcode']}\")\n print(f\"description: {manifest['description']}\")\n else:\n print(\"published: (not in the local registry)\")\n if info[\"published\"]:\n print(f\"published: {', '.join(info['published'])}\")\n if info[\"installed\"]:\n print(f\"installed: {', '.join(info['installed'])} \"\n f\"(project: {', '.join(info['installed_project']) or '--'}; \"\n f\"user: {', '.join(info['installed_user']) or '--'})\")\n else:\n print(f\"installed: (nowhere -- `godcode scroll install \"\n f\"{info['name']}` to receive it)\")\n return 0\n\n\ndef _add_scroll_commands(sub) -> None:\n p_scroll = sub.add_parser(\"scroll\", help=\"Scroll Registry commands\")\n scroll_sub = p_scroll.add_subparsers(dest=\"scroll_command\", required=True)\n\n p_list = scroll_sub.add_parser(\"list\", help=\"List installed scrolls\")\n p_list.set_defaults(func=cmd_scroll_list)\n\n p_install = scroll_sub.add_parser(\"install\",\n help=\"Install a scroll from the registry\")\n p_install.add_argument(\"name\", help=\"Scroll name, e.g. json-tools\")\n p_install.add_argument(\"--version\", default=None, metavar=\"X.Y.Z\",\n help=\"Exact version (default: latest published)\")\n p_install.add_argument(\"--project\", action=\"store_true\",\n help=\"Install project-local (.godcode/scrolls/) \"\n \"instead of user-global (~/.godcode/scrolls/)\")\n p_install.add_argument(\"--remote\", action=\"store_true\",\n help=\"Prefer the remote registry (default: local \"\n \"index first, remote as fallback)\")\n p_install.set_defaults(func=cmd_scroll_install)\n\n p_publish = scroll_sub.add_parser(\"publish\",\n help=\"Publish a scroll dir to the registry\")\n p_publish.add_argument(\"dir\", help=\"Directory holding scroll.toml\")\n p_publish.add_argument(\"--remote\", action=\"store_true\",\n help=\"Publish to the remote registry over HTTPS \"\n \"(needs the GODCODE_PUBLISH_TOKEN \"\n \"environment variable)\")\n p_publish.set_defaults(func=cmd_scroll_publish)\n\n p_info = scroll_sub.add_parser(\"info\",\n help=\"Show a scroll's manifest and state\")\n p_info.add_argument(\"name\", help=\"Scroll name\")\n p_info.set_defaults(func=cmd_scroll_info)\n\n p_search = scroll_sub.add_parser(\"search\",\n help=\"Search the remote registry\")\n p_search.add_argument(\"query\", help=\"Words to search for\")\n p_search.set_defaults(func=cmd_scroll_search)\n\n p_uninstall = scroll_sub.add_parser(\"uninstall\",\n help=\"Remove an installed scroll\")\n p_uninstall.add_argument(\"name\", help=\"Scroll name\")\n p_uninstall.add_argument(\"--version\", default=None, metavar=\"X.Y.Z\",\n help=\"Only remove this version \"\n \"(default: every installed version)\")\n p_uninstall.set_defaults(func=cmd_scroll_uninstall)\n\n p_update = scroll_sub.add_parser(\"update\",\n help=\"Update installed scrolls to the \"\n \"newest version\")\n p_update.add_argument(\"name\", nargs=\"?\", default=None,\n help=\"Scroll name (default: every installed scroll)\")\n p_update.add_argument(\"--remote\", action=\"store_true\",\n help=\"Prefer the remote registry when looking for \"\n \"newer versions\")\n p_update.set_defaults(func=cmd_scroll_update)\n\n\n# --- end v3: scroll commands ---\n\n# --- v3: lsp commands ---\ndef cmd_lsp(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.lsp import serve\n\n return serve()\n# --- end v3: lsp commands ---\n\n# --- v5.0: dap commands ---\ndef cmd_dap(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.dap import serve\n\n return serve()\n# --- end v5.0: dap commands ---\n\n# --- permission manifests: `godcode permissions` ---\ndef cmd_permissions(args: argparse.Namespace) -> int:\n \"\"\"`godcode permissions scroll.god [--json]`: read the scroll's manifest.\n\n Parses the scroll and reports what powers it declares. No code runs,\n so reading a manifest is always safe.\n \"\"\"\n import json as _json\n\n from godcode.errors import GodCodeError\n from godcode.permissions import PermissionManifest, collect_manifest\n from godcode.tongues import parse_source\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n program = parse_source(source)\n except GodCodeError as err:\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"permissions\",\n \"file\": args.file, \"ok\": False,\n \"error\": str(err)}, ensure_ascii=False))\n else:\n print(f\"godcode: the scroll could not be read: {err}\",\n file=sys.stderr)\n return 1\n base_dir = Path(args.file).resolve().parent\n manifest: PermissionManifest = collect_manifest(program.statements, base_dir)\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"permissions\",\n \"file\": args.file, \"ok\": True,\n \"manifest\": manifest.to_json()},\n ensure_ascii=False))\n return 0\n lines = manifest.describe()\n if not lines:\n print(f\"{args.file} declares no permissions. It may touch nothing \"\n \"of the outer world.\")\n else:\n print(f\"The scroll {args.file} declares:\")\n for grant in lines:\n print(f\" - it {grant}\")\n return 0\n# --- end permission manifests ---\n\n# --- machine interfaces: `godcode explain` ---\ndef cmd_explain(args: argparse.Namespace) -> int:\n \"\"\"`godcode explain scroll.god [--json]`: say what a scroll does.\n\n Parses the scroll and reports its static facts: tongue, rites and\n their declared intents, declared names, reveals, seals, summons,\n consults, imports, and the permission manifest. No code runs, so\n explaining a scroll is always safe.\n \"\"\"\n import json as _json\n\n from godcode.errors import GodCodeError\n from godcode.explain import explain_facts, explain_payload, human_summary\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(explain_payload(\n args.file, False, [agentics._file_error_diagnostic(args.file, exc)]))\n else:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n facts = explain_facts(source, Path(args.file).resolve().parent)\n except GodCodeError as err:\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(explain_payload(\n args.file, False, [agentics.diagnostic(err)]))\n else:\n print(f\"godcode: the scroll could not be read: {err}\",\n file=sys.stderr)\n return 1\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(explain_payload(args.file, True, [], facts))\n return 0\n print(human_summary(args.file, facts))\n return 0\n# --- end machine interfaces ---\n\n# --- machine interfaces: `godcode schema` ---\ndef cmd_schema(args: argparse.Namespace) -> int:\n \"\"\"`godcode schema [name] [--json]`: list or print dated JSON schemas.\n\n The schemas freeze the machine shapes of `check --json`,\n `run --sandbox --json`, `explain --json`, and `ledger verify --json`\n under their dated contract; additive fields may appear but required\n fields never change meaning.\n \"\"\"\n import json as _json\n\n from godcode.tools import SCHEMA_DESCRIPTIONS, SCHEMA_NAMES, read_schema\n\n if not args.name:\n print(\"God Code machine interfaces (dated schemas):\")\n for name in SCHEMA_NAMES:\n print(f\" {name}: {SCHEMA_DESCRIPTIONS[name]}\")\n return 0\n text, error = read_schema(args.name)\n if error is not None:\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"schema\",\n \"ok\": False, \"error\": error},\n ensure_ascii=False))\n else:\n print(f\"godcode: {error}. The schemas are: \"\n f\"{', '.join(SCHEMA_NAMES)}.\", file=sys.stderr)\n return 1\n print(text)\n return 0\n# --- end machine interfaces ---\n\n# --- v4.0: intent command ---\ndef cmd_intent(args: argparse.Namespace) -> int:\n \"\"\"`godcode intent \"some words\" [--json]`: resolve intent via the Spirit.\"\"\"\n import json as _json\n\n from godcode.spirit import SpiritEngine\n\n result = SpiritEngine().resolve_intent(args.text)\n if getattr(args, \"json\", False):\n print(_json.dumps(\n {\"tool\": \"godcode\", \"command\": \"intent\",\n \"text\": args.text, \"result\": result},\n ensure_ascii=False))\n return 0\n pct = round(result[\"confidence\"] * 100)\n print(f\"[INTENT] The Spirit discerns: '{result['intent']}' \"\n f\"({pct}% certainty).\")\n print(f\"Spiritual intent: {result['spiritual_intent']}\")\n print(f\"Counsel: {result['suggestion']}\")\n aligned = result.get(\"aligned_with\") or []\n if aligned:\n for entry in aligned:\n print(f\"Aligned with: {entry['rite']} (\\\"{entry['declared']}\\\")\")\n else:\n print(\"Aligned with no declared intent.\")\n return 0\n# --- end v4.0: intent command ---\n\n\n# --- v4.0: tools + bridge commands (implemented in godcode.tools) ---\ndef cmd_tools(args: argparse.Namespace) -> int:\n from godcode.tools import cmd_tools as _cmd_tools\n\n return _cmd_tools(args)\n\n\ndef cmd_bridge(args: argparse.Namespace) -> int:\n from godcode.tools import cmd_bridge as _cmd_bridge\n\n return _cmd_bridge(args)\n\n\ndef cmd_mcp(args: argparse.Namespace) -> int:\n from godcode.mcp import cmd_mcp as _cmd_mcp\n\n return _cmd_mcp(args)\n# --- end v4.0 ---\n\n\n# --- v5.0: interactive debugger ---\ndef cmd_debug(args: argparse.Namespace) -> int:\n from godcode.debug_cli import cmd_debug as _cmd_debug\n\n return _cmd_debug(args)\n# --- end v5.0 ---\n\n\n# ---------------------------------------------------------------------------\n# parser assembly\n# ---------------------------------------------------------------------------\ndef build_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(\n prog=\"godcode\",\n description=\"God Code. The language of divine computation 🕊\")\n sub = parser.add_subparsers(dest=\"command\", required=True)\n\n p_run = sub.add_parser(\"run\", help=\"Execute a God Code scroll\")\n p_run.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_run.add_argument(\"--log\", default=None, metavar=\"PATH\",\n help=\"Audit log path (default: logs/godcode.log)\")\n # --- v3: sandbox commands ---\n p_run.add_argument(\"--sandbox\", action=\"store_true\",\n help=\"Run under the strict sandbox policy \"\n \"(deny fs writes, network, subprocesses, \"\n \"stdin; scroll imports limited to the \"\n \"scroll's own directory and the stdlib \"\n \"scrolls; time and step budgets enforced)\")\n p_run.add_argument(\"--sandbox-timeout\", type=float, default=5.0,\n metavar=\"SECS\",\n help=\"Wall-clock grant for --sandbox runs \"\n \"(default: 5.0 seconds)\")\n # --- end v3: sandbox commands ---\n # --- v3: agentics --json ---\n p_run.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n # --- end v3: agentics --json ---\n p_run.set_defaults(func=cmd_run)\n\n p_check = sub.add_parser(\"check\",\n help=\"Lex and parse a scroll without running it\")\n p_check.add_argument(\"file\", help=\"Path to the .god scroll\")\n # --- v3: agentics --json ---\n p_check.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n # --- end v3: agentics --json ---\n p_check.set_defaults(func=cmd_check)\n\n p_repl = sub.add_parser(\"repl\", help=\"Enter the live sanctuary\")\n p_repl.set_defaults(func=cmd_repl)\n\n p_fmt = sub.add_parser(\"fmt\", help=\"Re-emit a scroll in canonical form\")\n p_fmt.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_fmt.add_argument(\"--in-place\", \"-w\", dest=\"in_place\",\n action=\"store_true\",\n help=\"Rewrite the file instead of printing\")\n p_fmt.set_defaults(func=cmd_fmt)\n\n p_lint = sub.add_parser(\"lint\",\n help=\"Lint a scroll for unused names, shadowing, \"\n \"empty blocks, and other quiet troubles\")\n p_lint.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_lint.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_lint.set_defaults(func=cmd_lint)\n\n p_test = sub.add_parser(\n \"test\",\n help=\"Run the TEST_ rites in a directory's test scrolls\")\n p_test.add_argument(\"dir\", nargs=\"?\", default=\".\",\n help=\"Directory holding test scrolls (default: the \"\n \"current directory). Only that directory is \"\n \"read; subfolders are not entered.\")\n p_test.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_test.set_defaults(func=cmd_test)\n\n p_new = sub.add_parser(\n \"new\",\n help=\"Raise a new God Code project (starter scroll, test scroll, \"\n \"scroll manifest, README)\")\n p_new.add_argument(\"name\", help=\"Project name (lowercase, e.g. my-scroll)\")\n p_new.add_argument(\"--path\", default=\".\", metavar=\"DIR\",\n help=\"Parent directory for the new project \"\n \"(default: the current directory)\")\n p_new.add_argument(\"--author\", default=\"\",\n help=\"Author name for the scroll manifest\")\n p_new.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_new.set_defaults(func=cmd_new)\n\n p_ledger = sub.add_parser(\"ledger\", help=\"Covenant ledger commands\")\n ledger_sub = p_ledger.add_subparsers(dest=\"ledger_command\", required=True)\n p_verify = ledger_sub.add_parser(\"verify\",\n help=\"Verify the covenant chain\")\n p_verify.add_argument(\"--file\", default=\"covenant.chain\", metavar=\"PATH\",\n help=\"Chain file (default: covenant.chain)\")\n # --- v4.0: the anchor chain is verified alongside the covenant chain ---\n p_verify.add_argument(\"--anchor-file\", default=\"anchors.chain\",\n metavar=\"PATH\",\n help=\"Anchor chain file (default: anchors.chain)\")\n # --- end v4.0 ---\n # --- machine interfaces: ledger verify --json ---\n p_verify.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report \"\n \"on stdout\")\n # --- end machine interfaces ---\n p_verify.set_defaults(func=cmd_ledger_verify)\n\n # --- v4.0: intent, tools, bridge commands ---\n p_intent = sub.add_parser(\"intent\",\n help=\"Resolve the intent behind words \"\n \"with the Spirit Engine\")\n p_intent.add_argument(\"text\", help=\"Words to resolve the intent of\")\n p_intent.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_intent.set_defaults(func=cmd_intent)\n\n p_permissions = sub.add_parser(\"permissions\",\n help=\"Read a scroll's permission manifest \"\n \"without running it\")\n p_permissions.add_argument(\"file\", help=\"The .god scroll to read\")\n p_permissions.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report \"\n \"on stdout\")\n p_permissions.set_defaults(func=cmd_permissions)\n\n p_tools = sub.add_parser(\"tools\",\n help=\"Show the MCP-compatible agent tool schemas\")\n p_tools.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit the schemas as JSON\")\n p_tools.set_defaults(func=cmd_tools)\n\n p_bridge = sub.add_parser(\"bridge\",\n help=\"Serve the agent tool bridge \"\n \"(JSON-RPC 2.0 over stdio)\")\n p_bridge.set_defaults(func=cmd_bridge)\n\n p_mcp = sub.add_parser(\"mcp\",\n help=\"Serve the MCP server over stdio \"\n \"(runs are always sandboxed)\")\n p_mcp.set_defaults(func=cmd_mcp)\n # --- end v4.0 ---\n\n # --- machine interfaces: explain + schema commands ---\n p_explain = sub.add_parser(\"explain\",\n help=\"Say what a scroll does, in plain words, \"\n \"without running it\")\n p_explain.add_argument(\"file\", help=\"The .god scroll to explain\")\n p_explain.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report \"\n \"on stdout\")\n p_explain.set_defaults(func=cmd_explain)\n\n p_schema = sub.add_parser(\"schema\",\n help=\"List or print the dated JSON schemas \"\n \"for the machine interfaces\")\n p_schema.add_argument(\"name\", nargs=\"?\", default=None,\n help=\"Schema to print: check, run, explain, \"\n \"ledger-verify\")\n p_schema.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON error on \"\n \"stdout for unknown names\")\n p_schema.set_defaults(func=cmd_schema)\n # --- end machine interfaces ---\n\n # --- v3: scroll commands ---\n _add_scroll_commands(sub)\n # --- end v3: scroll commands ---\n\n # --- v3: lsp commands ---\n p_lsp = sub.add_parser(\"lsp\",\n help=\"Start the language server over stdio\")\n p_lsp.set_defaults(func=cmd_lsp)\n # --- end v3: lsp commands ---\n\n # --- v5.0: dap commands ---\n p_dap = sub.add_parser(\"dap\",\n help=\"Start the God Code debug adapter (DAP) \"\n \"over stdio\")\n p_dap.set_defaults(func=cmd_dap)\n # --- end v5.0: dap commands ---\n\n # --- v5.0: interactive debugger ---\n p_debug = sub.add_parser(\"debug\",\n help=\"Debug a God Code scroll interactively\")\n p_debug.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_debug.add_argument(\"--break\", \"-b\", dest=\"breaks\", action=\"append\",\n type=int, default=[], metavar=\"LINE\",\n help=\"Pause at LINE as well as on entry \"\n \"(repeatable)\")\n p_debug.set_defaults(func=cmd_debug)\n # --- end v5.0 ---\n\n return parser\n\n\ndef main(argv=None) -> int:\n \"\"\"Entry point. Returns 0 on success; raises SystemExit(code) on failure.\"\"\"\n args = build_parser().parse_args(argv)\n code = args.func(args)\n if code:\n raise SystemExit(code)\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","godcode/dap.py":"\"\"\"Debug Adapter Protocol server for God Code (v5.0).\n\nA minimal DAP implementation over stdio, hand-rolled on top of the stdlib.\nMessages are framed with ``Content-Length`` headers, exactly like\n:mod:`godcode.lsp`.\n\nLifecycle::\n\n godcode dap # start serving on stdin/stdout\n\nThe message loop runs on the main thread. ``launch`` builds an interpreter\nthe same way ``godcode run`` does, attaches a\n:class:`godcode.debugger.DebugSession`, and starts the scroll on a daemon\nworker thread. Pauses surface as ``stopped`` events; the worker thread\nblocks inside the session until a ``continue`` / ``next`` / ``stepIn`` /\n``stepOut`` request resumes it.\n\nProtocol notes:\n * All logging goes to stderr. stdout is the protocol channel. Nothing\n else may ever be written there (REVEAL output is forwarded as DAP\n ``output`` events instead).\n * Unknown commands answer with JSON-RPC error -32601 (\"Method not found\").\n * Malformed frames are skipped; the server keeps serving.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport io\nimport json\nimport os\nimport re\nimport sys\nimport threading\n\nfrom godcode.debugger import DebugSession\nfrom godcode.errors import GodCodeError\n\n# A handler that already sent its own response returns this, so the\n# dispatcher does not answer twice (used by launch and disconnect).\n_HANDLED = object()\n\n_IDENT_RE = re.compile(r\"[A-Za-z_][A-Za-z0-9_]*$\")\n\n_CAPABILITIES = {\n \"supportsConfigurationDoneRequest\": True,\n \"supportsEvaluateForHovers\": False,\n}\n\n\ndef _log(message: str) -> None:\n sys.stderr.write(f\"[godcode-dap] {message}\\n\")\n sys.stderr.flush()\n\n\nclass DebugAdapter:\n \"\"\"Hand-rolled DAP server over stdio.\"\"\"\n\n def __init__(self,\n stdin: io.BufferedReader | None = None,\n stdout: io.BufferedWriter | None = None) -> None:\n self.stdin = stdin or sys.stdin.buffer\n self.stdout = stdout or sys.stdout.buffer\n self._write_lock = threading.Lock()\n self._seq = 0\n self._session: DebugSession | None = None\n self._worker: threading.Thread | None = None\n self._pending_breakpoints: dict[str, set[int]] = {}\n # Variable references: id -> (\"frame_locals\", frame_id)\n # or (\"value\", python_value). Allocated from 1.\n self._var_refs: dict[int, tuple] = {}\n self._next_var_ref = 1\n self._handlers = {\n \"initialize\": self._on_initialize,\n \"launch\": self._on_launch,\n \"configurationDone\": self._on_configuration_done,\n \"setBreakpoints\": self._on_set_breakpoints,\n \"threads\": self._on_threads,\n \"stackTrace\": self._on_stack_trace,\n \"scopes\": self._on_scopes,\n \"variables\": self._on_variables,\n \"evaluate\": self._on_evaluate,\n \"continue\": self._on_continue,\n \"next\": self._on_next,\n \"stepIn\": self._on_step_in,\n \"stepOut\": self._on_step_out,\n \"disconnect\": self._on_disconnect,\n }\n\n # ------------------------------------------------------------ transport\n def _read_message(self) -> dict | None:\n \"\"\"Read one Content-Length framed message. None on clean EOF.\"\"\"\n headers: dict[str, str] = {}\n while True:\n line = self.stdin.readline()\n if not line:\n return None # EOF\n line = line.decode(\"latin-1\").strip()\n if not line:\n break\n if \":\" in line:\n name, _, value = line.partition(\":\")\n headers[name.strip().lower()] = value.strip()\n try:\n length = int(headers.get(\"content-length\", \"\"))\n except (TypeError, ValueError):\n _log(\"malformed frame: bad Content-Length; skipping\")\n return {}\n try:\n body = self._read_exact(length)\n except EOFError:\n _log(\"malformed frame: truncated body; skipping\")\n return {}\n try:\n return json.loads(body.decode(\"utf-8\"))\n except (UnicodeDecodeError, json.JSONDecodeError) as exc:\n _log(f\"malformed frame: {exc}; skipping\")\n return {}\n\n def _read_exact(self, length: int) -> bytes:\n body = b\"\"\n while len(body) < length:\n chunk = self.stdin.read(length - len(body))\n if not chunk:\n raise EOFError(\"truncated frame\")\n body += chunk\n return body\n\n def _next_seq(self) -> int:\n with self._write_lock:\n self._seq += 1\n return self._seq\n\n def _write(self, payload: dict) -> None:\n body = json.dumps(payload, separators=(\",\", \":\")).encode(\"utf-8\")\n frame = (f\"Content-Length: {len(body)}\\r\\n\\r\\n\".encode(\"ascii\")\n + body)\n with self._write_lock:\n self.stdout.write(frame)\n self.stdout.flush()\n\n def _send_response(self, request_seq, command: str,\n success: bool = True,\n body: dict | None = None,\n message: str = \"\") -> None:\n payload: dict = {\n \"seq\": self._next_seq(),\n \"type\": \"response\",\n \"request_seq\": request_seq,\n \"success\": success,\n \"command\": command,\n }\n if success:\n if body is not None:\n payload[\"body\"] = body\n elif message:\n payload[\"message\"] = message\n self._write(payload)\n\n def _send_event(self, event: str, body: dict | None = None) -> None:\n payload: dict = {\n \"seq\": self._next_seq(),\n \"type\": \"event\",\n \"event\": event,\n }\n if body is not None:\n payload[\"body\"] = body\n self._write(payload)\n\n def _send_jsonrpc_error(self, msg_id, code: int,\n message: str) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"id\": msg_id,\n \"error\": {\"code\": code, \"message\": message}})\n\n def _send_output(self, text: str, category: str = \"stdout\") -> None:\n if not text.endswith(\"\\n\"):\n text += \"\\n\"\n self._send_event(\"output\",\n {\"category\": category, \"output\": text})\n\n # ------------------------------------------------------------ main loop\n def serve(self) -> int:\n _log(\"the debug adapter opens (stdio)\")\n while True:\n message = self._read_message()\n if message is None:\n _log(\"stdin closed; ascending\")\n return 0\n if not message:\n continue # malformed frame: already logged, keep serving\n self._dispatch(message)\n\n def _dispatch(self, message: dict) -> None:\n command = message.get(\"command\") or message.get(\"method\")\n seq = message.get(\"seq\", message.get(\"id\"))\n if not command:\n _log(\"message with no command; ignoring\")\n return\n handler = self._handlers.get(command)\n if handler is None:\n _log(f\"unknown command: {command!r}\")\n if seq is not None:\n self._send_jsonrpc_error(seq, -32601,\n f\"Method not found: {command}\")\n return\n args = message.get(\"arguments\") or message.get(\"params\") or {}\n try:\n result = handler(seq, command, args)\n except Exception as exc: # never let a handler kill the server\n _log(f\"handler for {command} failed: {exc}\")\n if seq is not None:\n self._send_response(seq, command, success=False,\n message=str(exc))\n return\n if result is _HANDLED or seq is None:\n return\n self._send_response(seq, command, success=True, body=result)\n\n # ------------------------------------------------------ session helpers\n def _require_session(self) -> DebugSession:\n if self._session is None:\n raise RuntimeError(\"no program is launched\")\n return self._session\n\n def _frames_innermost_first(self) -> list:\n session = self._session\n if session is None:\n return []\n return list(reversed(session.frames))\n\n def _frame_by_id(self, frame_id: int):\n frames = self._frames_innermost_first()\n if 0 <= frame_id < len(frames):\n return frames[frame_id]\n return None\n\n def _alloc_var_ref(self, entry: tuple) -> int:\n ref = self._next_var_ref\n self._next_var_ref += 1\n self._var_refs[ref] = entry\n return ref\n\n @staticmethod\n def _children_of(value) -> list[tuple[str, object]]:\n if isinstance(value, list):\n return [(str(i), item) for i, item in enumerate(value)]\n if isinstance(value, dict):\n return [(str(key), item) for key, item in value.items()]\n return []\n\n def _variable(self, name: str, value) -> dict:\n session = self._require_session()\n ref = 0\n if isinstance(value, (list, dict)):\n ref = self._alloc_var_ref((\"value\", value))\n return {\n \"name\": str(name),\n \"value\": session.render_value(value),\n \"type\": session.type_name(value),\n \"variablesReference\": ref,\n }\n\n # -------------------------------------------------------------- handlers\n def _on_initialize(self, seq, command, args: dict): # noqa: ARG002\n _log(\"initialize received\")\n result = {\"capabilities\": dict(_CAPABILITIES)}\n # Respond first so the client sees a clean handshake ordering.\n self._send_response(seq, command, success=True, body=result)\n self._send_event(\"initialized\")\n return _HANDLED\n\n def _on_launch(self, seq, command, args: dict):\n if self._session is not None:\n raise RuntimeError(\"a program is already launched\")\n program = args.get(\"program\")\n if not program:\n raise RuntimeError(\"launch requires a 'program' path\")\n stop_on_entry = args.get(\"stopOnEntry\", True)\n _log(f\"launch: {program} (stopOnEntry={stop_on_entry})\")\n\n from godcode.cli import _make_interpreter\n\n interpreter = _make_interpreter(None)\n session = DebugSession()\n for path, lines in self._pending_breakpoints.items():\n for line in sorted(lines):\n session.add_breakpoint(path, line)\n self._pending_breakpoints.clear()\n\n original_emit = interpreter.emit\n\n def _emit(line: str, _orig=original_emit) -> None:\n _orig(line) # printed, as `godcode run` does\n self._send_output(str(line), category=\"stdout\")\n\n interpreter.emit = _emit\n session.on_pause = self._on_pause\n session.attach(interpreter)\n session.stop_on_entry = bool(stop_on_entry)\n self._session = session\n\n # Answer before the worker starts, so the client never sees a\n # stopped event ahead of the launch response.\n self._send_response(seq, command, success=True, body={})\n worker = threading.Thread(\n target=self._run_program,\n args=(session, str(program)),\n daemon=True,\n name=\"godcode-dap-worker\",\n )\n self._worker = worker\n worker.start()\n return _HANDLED\n\n def _run_program(self, session: DebugSession, program: str) -> None:\n try:\n session.run_file(program)\n except GodCodeError as err:\n _log(f\"program error: {err}\")\n self._send_output(str(err), category=\"stderr\")\n self._send_event(\"terminated\")\n return\n except Exception as err: # noqa: BLE001 - never die silently\n _log(f\"worker failed: {err}\")\n self._send_output(f\"{type(err).__name__}: {err}\",\n category=\"stderr\")\n self._send_event(\"terminated\")\n return\n _log(\"program finished\")\n self._send_event(\"terminated\")\n self._send_event(\"exited\", {\"exitCode\": 0})\n\n def _on_pause(self, pause_info: dict) -> None:\n reason = pause_info.get(\"reason\", \"pause\")\n line = pause_info.get(\"line\")\n source = pause_info.get(\"source\")\n _log(f\"paused: {reason} at {source}:{line}\")\n # The session blocks inside _pause until a request handler calls\n # session.resume(); this handler only announces the stop.\n self._send_event(\"stopped\", {\n \"reason\": reason,\n \"threadId\": 1,\n \"allThreadsStopped\": True,\n })\n\n def _on_configuration_done(self, seq, command, # noqa: ARG002\n args: dict): # noqa: ARG002\n _log(\"configuration done\")\n return {}\n\n def _on_set_breakpoints(self, seq, command, args: dict): # noqa: ARG002\n source = args.get(\"source\") or {}\n path = source.get(\"path\", \"\")\n lines: list[int] = []\n for bp in args.get(\"breakpoints\") or []:\n line = (bp or {}).get(\"line\")\n if isinstance(line, int):\n lines.append(line)\n if self._session is not None:\n self._session.clear_breakpoints(path)\n for line in lines:\n self._session.add_breakpoint(path, line)\n else:\n # Arrived before launch; applied when the session is created.\n self._pending_breakpoints[path] = set(lines)\n norm = DebugSession._norm(path) if path else \"\"\n _log(f\"breakpoints for {norm or path}: {lines}\")\n return {\"breakpoints\": [\n {\"verified\": True, \"line\": n,\n \"source\": {\"name\": os.path.basename(norm) if norm else \"\",\n \"path\": norm}}\n for n in lines\n ]}\n\n def _on_threads(self, seq, command, args: dict): # noqa: ARG002\n return {\"threads\": [{\"id\": 1, \"name\": \"creation\"}]}\n\n def _on_stack_trace(self, seq, command, args: dict): # noqa: ARG002\n out = []\n for i, frame in enumerate(self._frames_innermost_first()):\n src = frame.source or \"\"\n out.append({\n \"id\": i,\n \"name\": frame.name,\n \"line\": frame.line or 1,\n \"column\": 1,\n \"source\": {\n \"name\": os.path.basename(src) if src else \"scroll\",\n \"path\": src,\n },\n })\n return {\"stackFrames\": out, \"totalFrames\": len(out)}\n\n def _on_scopes(self, seq, command, args: dict): # noqa: ARG002\n frame_id = args.get(\"frameId\", 0)\n ref = self._alloc_var_ref((\"frame_locals\", frame_id))\n return {\"scopes\": [\n {\"name\": \"Locals\", \"variablesReference\": ref,\n \"expensive\": False}\n ]}\n\n def _on_variables(self, seq, command, args: dict): # noqa: ARG002\n entry = self._var_refs.get(args.get(\"variablesReference\", 0))\n pairs: list[tuple[str, object]] = []\n if entry is not None:\n if entry[0] == \"frame_locals\":\n frame = self._frame_by_id(entry[1])\n if frame is not None:\n pairs = self._require_session().frame_locals(frame)\n elif entry[0] == \"value\":\n pairs = self._children_of(entry[1])\n return {\"variables\": [self._variable(name, value)\n for name, value in pairs[:50]]}\n\n def _on_evaluate(self, seq, command, args: dict): # noqa: ARG002\n session = self._require_session()\n expr = str(args.get(\"expression\", \"\")).strip()\n frame = self._frame_by_id(args.get(\"frameId\", 0))\n name = expr if _IDENT_RE.match(expr) else None\n if name is not None:\n found, value = session.lookup(name, frame)\n if found:\n return {\n \"result\": session.render_value(value),\n \"type\": session.type_name(value),\n \"variablesReference\": 0,\n }\n return {\"result\": f\"no '{expr}' is bound here.\",\n \"variablesReference\": 0}\n\n def _on_continue(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"continue\")\n return {\"allThreadsContinued\": True}\n\n def _on_next(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"step_over\")\n return {\"allThreadsContinued\": True}\n\n def _on_step_in(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"step_in\")\n return {\"allThreadsContinued\": True}\n\n def _on_step_out(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"step_out\")\n return {\"allThreadsContinued\": True}\n\n def _on_disconnect(self, seq, command, args: dict): # noqa: ARG002\n self._send_response(seq, command, success=True, body={})\n _log(\"disconnect; ascending\")\n os._exit(0)\n\n\ndef serve() -> int:\n \"\"\"Entry point for ``godcode dap``.\"\"\"\n return DebugAdapter().serve()\n","godcode/debug_cli.py":"\"\"\"Interactive CLI driver for the God Code debugger.\n\nImplements ``godcode debug ``: the scroll runs under a\n:class:`godcode.debugger.DebugSession`, and every pause opens a small\ngdb-style console on stdin/stdout. The interpreter is built exactly the\nway ``godcode run`` builds it, so the debug run can never drift from a\nplain run.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom pathlib import Path\n\nPROMPT = \"(god) \"\n\n\nclass _QuitDebug(Exception):\n \"\"\"Raised to leave the debugger. Caught by cmd_debug.\"\"\"\n\n\nclass _PauseLoop:\n \"\"\"Answers ``DebugSession.on_pause`` with an interactive console.\n\n Runs on the interpreter's own thread: every command either answers\n inline (break, print, locals, stack, help) or ends the pause with\n ``session.resume(action)``. Quitting raises :class:`_QuitDebug` after\n releasing the session's resume event, because the session waits on\n that event even when ``on_pause`` raises.\n \"\"\"\n\n _RESUME_COMMANDS = {\n \"continue\": \"continue\",\n \"c\": \"continue\",\n \"run\": \"continue\",\n \"next\": \"step_over\",\n \"n\": \"step_over\",\n \"step\": \"step_in\",\n \"si\": \"step_in\",\n \"out\": \"step_out\",\n }\n\n def __init__(self, session) -> None:\n self.session = session\n self._last_resume = \"continue\"\n\n # ------------------------------------------------------------ entry point\n def handle(self, pause_info: dict) -> None:\n self._show_pause(pause_info)\n while True:\n try:\n raw = input(PROMPT)\n except EOFError:\n self._quit()\n except KeyboardInterrupt:\n print()\n self._quit()\n text = raw.strip()\n if not text:\n # gdb-style: an empty line repeats the last resume command.\n self._do_resume(self._last_resume)\n return\n if self._dispatch(text, pause_info):\n return\n\n # ---------------------------------------------------------------- display\n def _show_pause(self, pause_info: dict) -> None:\n reason = pause_info.get(\"reason\", \"step\")\n line = pause_info.get(\"line\")\n source = pause_info.get(\"source\") or \"\"\n name = Path(source).name if source else \"\"\n print(f\"paused at {name}:{line} ({reason})\")\n lines = self.session.source_lines(source) if source else []\n if isinstance(line, int) and 1 <= line <= len(lines):\n first = max(1, line - 1)\n last = min(len(lines), line + 1)\n for num in range(first, last + 1):\n marker = \"=>\" if num == line else \" \"\n print(f\"{marker} {num:>4} | {lines[num - 1]}\")\n\n # --------------------------------------------------------------- commands\n def _dispatch(self, text: str, pause_info: dict) -> bool:\n \"\"\"Run one command. Returns True when the pause is over.\"\"\"\n word, _, rest = text.partition(\" \")\n word = word.lower()\n arg = rest.strip()\n\n resume = self._RESUME_COMMANDS.get(word)\n if resume is not None:\n if arg:\n print(f\"'{word}' takes no arguments.\")\n return False\n self._do_resume(resume)\n return True\n\n if word in (\"break\", \"b\"):\n self._cmd_break(arg)\n elif word in (\"print\", \"p\"):\n self._cmd_print(arg)\n elif word == \"locals\":\n self._cmd_locals(pause_info)\n elif word in (\"stack\", \"bt\"):\n self._cmd_stack()\n elif word == \"help\":\n self._cmd_help()\n elif word in (\"quit\", \"q\"):\n self._quit()\n else:\n print(f\"Unknown command: '{word}'. Type 'help' for the list.\")\n return False\n\n def _do_resume(self, action: str) -> None:\n self._last_resume = action\n self.session.resume(action)\n\n def _quit(self) -> None:\n # Release the session's wait first: it blocks on the resume event\n # even when on_pause raises, and we must not hang it.\n self.session.resume(\"continue\")\n raise _QuitDebug()\n\n # -- break ---------------------------------------------------------\n def _cmd_break(self, arg: str) -> None:\n session = self.session\n source = session.current_source\n name = Path(source).name if source else \"\"\n if not arg:\n lines = sorted(session.breakpoints_for(source))\n if not lines:\n print(\"No breakpoints set.\")\n else:\n listed = \", \".join(f\"{name}:{num}\" for num in lines)\n print(f\"Breakpoints: {listed}\")\n return\n try:\n lineno = int(arg.split()[0])\n if lineno < 1:\n raise ValueError\n except ValueError:\n print(\"Usage: break . Give a line number, like 'break 3'.\")\n return\n session.add_breakpoint(source, lineno)\n print(f\"Breakpoint set at {name}:{lineno}.\")\n\n # -- print ---------------------------------------------------------\n def _cmd_print(self, arg: str) -> None:\n if not arg:\n print(\"Usage: print .\")\n return\n name = arg.split()[0]\n found, value = self.session.lookup(name)\n if not found:\n print(f\"'{name}' is not bound here.\")\n else:\n print(f\"{name} = {self.session.render_value(value)}\")\n\n # -- locals --------------------------------------------------------\n def _cmd_locals(self, pause_info: dict) -> None:\n session = self.session\n frame = pause_info.get(\"frame\")\n if frame is None and session.frames:\n frame = session.frames[-1]\n pairs = session.frame_locals(frame) if frame is not None else []\n if not pairs:\n print(\"No names are bound in this frame.\")\n return\n for name, value in pairs:\n rendered = session.render_value(value)\n typename = session.type_name(value)\n print(f\"{name} = {rendered} ({typename})\")\n\n # -- stack ---------------------------------------------------------\n def _cmd_stack(self) -> None:\n frames = self.session.frames\n if not frames:\n print(\"The stack is empty.\")\n return\n for i, frame in enumerate(reversed(frames)):\n marker = \" (current)\" if i == 0 else \"\"\n print(f\"#{i} {frame.name} at {self._frame_loc(frame)}{marker}\")\n\n @staticmethod\n def _frame_loc(frame) -> str:\n source = getattr(frame, \"source\", \"\") or \"\"\n name = Path(source).name if source else \"\"\n line = frame.line\n return f\"{name}:{line}\" if isinstance(line, int) else name\n\n # -- help ----------------------------------------------------------\n def _cmd_help(self) -> None:\n print(\"Commands:\")\n print(\" break (b) set a breakpoint; 'break' alone lists them\")\n print(\" continue (c), run resume the scroll\")\n print(\" next (n) step over the next statement\")\n print(\" step (si) step into the next call\")\n print(\" out step out of the current rite\")\n print(\" print (p) show the value of a bound name\")\n print(\" locals show every name visible in this frame\")\n print(\" stack (bt) show the call stack, innermost first\")\n print(\" help this list\")\n print(\" quit (q) leave the debugger; the scroll does not finish\")\n print(\"An empty line repeats the last resume command. Ctrl-D quits.\")\n\n\n# ---------------------------------------------------------------------------\n# debug\n# ---------------------------------------------------------------------------\ndef cmd_debug(args) -> int:\n from godcode.cli import _make_interpreter\n from godcode.debugger import DebugSession\n from godcode.errors import GodCodeError, format_error\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n\n interp = _make_interpreter(log_path=None)\n session = DebugSession()\n loop = _PauseLoop(session)\n session.on_pause = loop.handle\n session.stop_on_entry = True\n for lineno in getattr(args, \"breaks\", None) or []:\n session.add_breakpoint(args.file, lineno)\n session.attach(interp)\n try:\n session.run_file(args.file)\n except _QuitDebug:\n print(\"The debugger ascends. The scroll rests unfinished.\")\n return 0\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n print(\"The scroll has finished its course. Amen.\")\n return 0\n","godcode/debugger.py":"\"\"\"Interactive debugging for God Code (v5.0).\n\nA :class:`DebugSession` plugs into the interpreter through the small hook\nsurface on ``Interpreter`` (``interpreter.debugger``):\n\n* ``before_stmt(stmt, env)`` — called before every statement executes.\n* ``enter_rite(rite, env)`` / ``exit_rite(rite)`` — around rite bodies.\n* ``enter_file(path)`` / ``exit_file()`` — around imported scrolls.\n\nWhen a pause condition is met (breakpoint, step, or stop-on-entry) the\nsession calls ``on_pause(pause_info)`` and blocks until the driver calls\n``resume(action)``. The CLI driver answers inline; the DAP driver answers\nfrom its message loop while the program runs on a worker thread.\n\nHook contract for driver authors::\n\n session = DebugSession()\n session.on_pause = my_handler # must call session.resume(action)\n session.add_breakpoint(\"/path/scroll.god\", 12)\n session.attach(interpreter) # sets interpreter.debugger\n session.stop_on_entry = True # pause at the first statement\n session.run_file(\"/path/scroll.god\") # lex, parse, run, manage sources\n\nResume actions: ``\"continue\"``, ``\"step_in\"``, ``\"step_over\"``,\n``\"step_out\"``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport threading\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nRESUME_ACTIONS = (\"continue\", \"step_in\", \"step_over\", \"step_out\")\n\n_PAUSE_BREAKPOINT = \"breakpoint\"\n_PAUSE_STEP = \"step\"\n_PAUSE_ENTRY = \"entry\"\n\n\n@dataclass\nclass DebugFrame:\n \"\"\"One frame of the paused call stack.\"\"\"\n\n name: str # rite name, or \"\" for the top level\n env: Any = None # godcode.environment.Environment\n stmt: Any = None # statement about to execute (or None)\n source: str = \"\"\n depth: int = 0\n\n @property\n def line(self) -> int | None:\n return getattr(self.stmt, \"line\", None)\n\n\nclass DebugSession:\n \"\"\"Drives a paused/stepped run of a God Code program.\"\"\"\n\n def __init__(self) -> None:\n self.breakpoints: dict[str, set[int]] = {}\n self.frames: list[DebugFrame] = []\n self.on_pause: Callable[[dict], None] | None = None\n self.stop_on_entry = False\n self.interpreter = None\n # stepping state\n self._step_mode = \"run\" # run | step_in | step_over | step_out\n self._step_depth = 0\n self._pause_once = False\n # sources\n self._source_stack: list[str] = []\n # pause machinery\n self._resume_event = threading.Event()\n self._resume_event.set()\n self.resume_action = \"continue\"\n self.pause_info: dict | None = None\n self.pause_count = 0\n self.finished = False\n self.error: Any = None\n\n # ------------------------------------------------------------ breakpoints\n\n @staticmethod\n def _norm(source: str) -> str:\n try:\n return str(Path(source).resolve())\n except OSError:\n return str(source)\n\n def add_breakpoint(self, source: str, line: int) -> None:\n self.breakpoints.setdefault(self._norm(source), set()).add(int(line))\n\n def remove_breakpoint(self, source: str, line: int) -> None:\n self.breakpoints.get(self._norm(source), set()).discard(int(line))\n\n def clear_breakpoints(self, source: str | None = None) -> None:\n if source is None:\n self.breakpoints.clear()\n else:\n self.breakpoints.pop(self._norm(source), None)\n\n def breakpoints_for(self, source: str) -> set[int]:\n return set(self.breakpoints.get(self._norm(source), set()))\n\n # ----------------------------------------------------------------- sources\n\n @property\n def current_source(self) -> str:\n return self._source_stack[-1] if self._source_stack else \"\"\n\n def push_source(self, source: str) -> None:\n self._source_stack.append(self._norm(source))\n\n def pop_source(self) -> None:\n if self._source_stack:\n self._source_stack.pop()\n\n # ------------------------------------------------------------------ attach\n\n def attach(self, interpreter) -> \"DebugSession\":\n \"\"\"Plug this session into an interpreter's hook surface.\"\"\"\n self.interpreter = interpreter\n interpreter.debugger = self\n return self\n\n def detach(self) -> None:\n if self.interpreter is not None:\n self.interpreter.debugger = None\n self.interpreter = None\n\n # --------------------------------------------------------------------- run\n\n def run_file(self, path: str | Path):\n \"\"\"Lex, parse, and run a scroll under this session.\n\n Returns the interpreter. Runtime errors propagate to the caller;\n ``self.error`` records them and ``self.finished`` is set either way.\n \"\"\"\n from godcode.tongues import parse_source\n\n if self.interpreter is None:\n raise RuntimeError(\"DebugSession has no interpreter. Call attach() first.\")\n resolved = str(Path(path).resolve())\n source = Path(path).read_text(encoding=\"utf-8\")\n program = parse_source(source)\n if self.stop_on_entry:\n self._pause_once = True\n self.push_source(resolved)\n try:\n self.interpreter.run(program, source_name=resolved)\n except Exception as err: # noqa: BLE001 - recorded for the driver\n self.error = err\n raise\n finally:\n self.pop_source()\n self.finished = True\n return self.interpreter\n\n # ---------------------------------------------------------- interpreter hooks\n\n @property\n def depth(self) -> int:\n return len(self.frames)\n\n def _current_frame(self, env) -> DebugFrame:\n if not self.frames:\n self.frames.append(\n DebugFrame(name=\"\", env=env,\n source=self.current_source, depth=1)\n )\n frame = self.frames[-1]\n frame.env = env\n return frame\n\n def before_stmt(self, stmt, env) -> None:\n frame = self._current_frame(env)\n frame.stmt = stmt\n reason = self._pause_reason(stmt)\n if reason is not None:\n self._pause(reason, stmt, frame)\n\n def enter_rite(self, rite, env) -> None:\n self.frames.append(\n DebugFrame(name=getattr(rite, \"name\", \"\"), env=env,\n source=self.current_source,\n depth=len(self.frames) + 1)\n )\n\n def exit_rite(self, rite) -> None:\n if self.frames:\n self.frames.pop()\n # step_out lands on the next statement back in the caller.\n if self._step_mode == \"step_out\" and len(self.frames) < self._step_depth:\n self._step_mode = \"step_over\"\n self._step_depth = len(self.frames)\n self._pause_once = True\n\n def enter_file(self, path: str) -> None:\n self.push_source(path)\n\n def exit_file(self) -> None:\n self.pop_source()\n\n # ------------------------------------------------------------------ pausing\n\n def _pause_reason(self, stmt) -> str | None:\n if self._pause_once:\n self._pause_once = False\n return _PAUSE_ENTRY if self.pause_count == 0 else _PAUSE_STEP\n if self._step_mode == \"step_in\":\n return _PAUSE_STEP\n if self._step_mode == \"step_over\" and len(self.frames) <= self._step_depth:\n return _PAUSE_STEP\n if self._step_mode == \"run\":\n line = getattr(stmt, \"line\", None)\n if line is not None and line in self.breakpoints.get(self.current_source, ()):\n return _PAUSE_BREAKPOINT\n return None\n\n def _pause(self, reason: str, stmt, frame: DebugFrame) -> None:\n self.pause_count += 1\n self.pause_info = {\n \"reason\": reason,\n \"stmt\": stmt,\n \"frame\": frame,\n \"frames\": list(self.frames),\n \"source\": self.current_source,\n \"line\": getattr(stmt, \"line\", None),\n \"pause_count\": self.pause_count,\n }\n self._resume_event.clear()\n try:\n if self.on_pause is not None:\n self.on_pause(self.pause_info)\n else: # no driver: behave like \"continue\" so runs never hang\n self.resume(\"continue\")\n finally:\n self._resume_event.wait()\n self._apply_resume()\n\n def resume(self, action: str) -> None:\n \"\"\"Answer a pause. Safe to call from any thread.\"\"\"\n if action not in RESUME_ACTIONS:\n raise ValueError(f\"unknown resume action: {action!r}\")\n self.resume_action = action\n self._resume_event.set()\n\n def _apply_resume(self) -> None:\n action = self.resume_action\n if action == \"continue\":\n self._step_mode = \"run\"\n elif action == \"step_in\":\n self._step_mode = \"step_in\"\n elif action == \"step_over\":\n self._step_mode = \"step_over\"\n self._step_depth = len(self.frames)\n elif action == \"step_out\":\n self._step_mode = \"step_out\"\n self._step_depth = len(self.frames)\n\n # --------------------------------------------------------------- inspection\n\n def render_value(self, value) -> str:\n if self.interpreter is not None:\n return self.interpreter.stringify(value)\n return str(value)\n\n def type_name(self, value) -> str:\n if self.interpreter is not None:\n return self.interpreter.type_name(value)\n return type(value).__name__\n\n def frame_locals(self, frame: DebugFrame) -> list[tuple[str, Any]]:\n \"\"\"(name, value) pairs visible in a frame, innermost first.\"\"\"\n if frame.env is None:\n return []\n try:\n return list(frame.env.items())\n except Exception: # noqa: BLE001 - defensive; never break a pause\n return []\n\n def lookup(self, name: str, frame: DebugFrame | None = None):\n \"\"\"Resolve a name in a frame's environment. Returns (found, value).\"\"\"\n frame = frame or (self.frames[-1] if self.frames else None)\n if frame is None or frame.env is None:\n return False, None\n env = frame.env\n while env is not None:\n bindings = getattr(env, \"_bindings\", {})\n if name in bindings:\n return True, bindings[name]\n env = getattr(env, \"parent\", None)\n return False, None\n\n def source_lines(self, source: str | None = None) -> list[str]:\n \"\"\"Source lines of a file for context display (1-based indexing).\"\"\"\n path = source or self.current_source\n try:\n return Path(path).read_text(encoding=\"utf-8\").splitlines()\n except OSError:\n return []\n","godcode/environment.py":"\"\"\"Lexically scoped environments for God Code.\n\nScope rule: names resolve outward through parent environments. An unbound\nname does not raise — it resolves to a Symbol of that name, because in God\nCode every unnamed thing is still a named spirit (this is what makes\n`DECLARE seeker AS worthy` / `IF seeker IS worthy` work with no prior\nbinding of `worthy`).\n\nDECLARE always defines in the *current* environment; it never rebinds an\nouter scope. Use set_existing() to reshape a name that must already exist.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Iterator\n\nfrom godcode.errors import GodRuntimeError, with_suggestion\nfrom godcode.values import Symbol\n\n\nclass Environment:\n def __init__(self, parent: \"Environment | None\" = None):\n self.parent = parent\n self._bindings: dict[str, object] = {}\n\n def define(self, name: str, value: object) -> None:\n \"\"\"Bind name in this environment, shadowing any outer binding.\"\"\"\n self._bindings[name] = value\n\n def get(self, name: str) -> object:\n \"\"\"Walk outward for name; return Symbol(name) if nowhere bound.\"\"\"\n env: Environment | None = self\n while env is not None:\n if name in env._bindings:\n return env._bindings[name]\n env = env.parent\n return Symbol(name)\n\n def is_bound(self, name: str) -> bool:\n \"\"\"True if name is bound in this environment or any ancestor.\"\"\"\n env: Environment | None = self\n while env is not None:\n if name in env._bindings:\n return True\n env = env.parent\n return False\n\n def set_existing(self, name: str, value: object) -> None:\n \"\"\"Reshape an already-bound name where it lives; error if unbound.\"\"\"\n env: Environment | None = self\n while env is not None:\n if name in env._bindings:\n env._bindings[name] = value\n return\n env = env.parent\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no '{name}' to reshape. It was never spoken into being.\",\n name,\n self.names(),\n )\n )\n\n def names(self) -> list[str]:\n \"\"\"All visible names, innermost scope first, without duplicates.\"\"\"\n seen: list[str] = []\n env: Environment | None = self\n while env is not None:\n for key in env._bindings:\n if key not in seen:\n seen.append(key)\n env = env.parent\n return seen\n\n def items(self) -> Iterator[tuple[str, object]]:\n \"\"\"(name, value) pairs for every visible name, innermost first.\"\"\"\n for name in self.names():\n yield name, self.get(name)\n","godcode/errors.py":"\"\"\"Error hierarchy for God Code v2.0.\n\nAll errors carry line (and where known, column) numbers so the faithful\ncan find where the heavens objected. Messages are divine-flavored but\ngenuinely helpful -- never mocking.\n\nControl-flow signals (ReturnSignal / AscendSignal) are plain Exceptions,\n*not* GodCodeError subclasses, so a broad ``except GodCodeError`` in the\ninterpreter can never accidentally swallow a return or an ascension.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport difflib\n\n\nclass GodCodeError(Exception):\n \"\"\"Base class for every God Code failure. ``line``/``col`` are 1-based.\"\"\"\n\n def __init__(self, msg: str, line: int | None = None, col: int | None = None):\n super().__init__(msg)\n self.msg = msg\n self.line = line\n self.col = col\n\n def __str__(self) -> str:\n if self.line is None or f\"line {self.line}\" in self.msg:\n return self.msg\n loc = f\" (line {self.line}\"\n if self.col is not None:\n loc += f\", col {self.col}\"\n return self.msg + loc + \")\"\n\n\nclass LexerError(GodCodeError):\n \"\"\"The source could not be turned into tokens.\"\"\"\n\n\nclass ParseError(GodCodeError):\n \"\"\"The tokens did not form a holy grammar.\"\"\"\n\n\nclass GodRuntimeError(GodCodeError):\n \"\"\"The creation failed while it was being brought to life.\n\n Named to avoid clashing with the builtin RuntimeError.\n \"\"\"\n\n\nclass SandboxViolation(GodCodeError):\n \"\"\"A power the sandbox withholds.\n\n Raised when a creation running under ``godcode.sandbox`` reaches for\n something its policy does not grant: a forbidden scroll, a denied\n rite (such as ASK when stdin is closed), a spent step budget, or an\n expired time grant. Carries a line number like every other\n GodCodeError, so the faithful can see exactly where the heavens\n objected.\n \"\"\"\n\n\nclass ReturnSignal(Exception):\n \"\"\"Carries a rite's return value up to the rite-call boundary.\"\"\"\n\n def __init__(self, value=None):\n super().__init__(value)\n self.value = value\n\n\nclass AscendSignal(Exception):\n \"\"\"Raised by ASCEND; ends the creation in peace.\"\"\"\n\n\nclass BreakSignal(Exception):\n \"\"\"Raised by BREAK; carries the loop's end up to the enclosing loop.\n\n Caught only by the interpreter's loop runners (_exec_for/_exec_while),\n so BREAK always releases the *innermost* loop. Never crosses a rite\n boundary: the parser binds every BREAK to a lexically enclosing loop,\n and _call_rite turns any stray signal into a plain error.\n \"\"\"\n\n\nclass ContinueSignal(Exception):\n \"\"\"Raised by CONTINUE; skips to the next turn of the enclosing loop.\n\n Same handling contract as BreakSignal: the innermost loop catches it,\n rite boundaries are never crossed.\n \"\"\"\n\n\ndef suggest_similar(name, candidates, *, n: int = 1, cutoff: float = 0.6):\n \"\"\"Return the closest candidate to *name*, or None when nothing is close.\n\n Matching is case-insensitive; the returned candidate keeps its own\n casing. Used so the heavens can answer a misspelled name with a\n gentle \\\"Did you mean ...?\\\" instead of a bare rejection.\n \"\"\"\n wanted = str(name).lower()\n lowered = {}\n for candidate in candidates:\n lowered.setdefault(str(candidate).lower(), str(candidate))\n if wanted in lowered:\n return None # an exact name needs no suggestion\n matches = difflib.get_close_matches(wanted, list(lowered), n=n, cutoff=cutoff)\n return lowered[matches[0]] if matches else None\n\n\ndef with_suggestion(message: str, name, candidates) -> str:\n \"\"\"Append a gentle \\\"Did you mean 'X'?\\\" to *message* when one fits.\"\"\"\n suggestion = suggest_similar(name, candidates)\n if suggestion is None:\n return message\n return f\"{message} Did you mean '{suggestion}'?\"\n\n\ndef format_error(source: str, err: GodCodeError) -> str:\n \"\"\"Render an error for a human: the message, then the offending line.\n\n The offending source line is shown with a gutter, and a caret marks the\n column when one is known. Quietly degrades to the bare message when the\n line or column cannot be shown.\n \"\"\"\n lines = [str(err)]\n line_no = getattr(err, \"line\", None)\n if isinstance(line_no, int) and line_no >= 1:\n src_lines = source.splitlines()\n if line_no <= len(src_lines):\n text = src_lines[line_no - 1]\n gutter = f\" {line_no} | \"\n lines.append(gutter + text)\n col = getattr(err, \"col\", None)\n if isinstance(col, int) and 1 <= col <= len(text) + 1:\n lines.append(\" \" * len(gutter) + \" \" * (col - 1) + \"^\")\n return \"\\n\".join(lines)\n\n\ndef format_call_trace(trace: list[dict]) -> list[str]:\n \"\"\"Render a rite call stack for humans, beneath the gentle error.\n\n One ``Called by`` line per call, oldest first, with\n ``(most recent call last)`` beneath them. An empty trace gives no lines:\n an error raised at the top level (no rite calls) shows no trace section.\n \"\"\"\n if not trace:\n return []\n lines: list[str] = []\n for frame in trace:\n rite = frame.get(\"rite\", \"\")\n line = frame.get(\"line\")\n if isinstance(line, int):\n lines.append(f\"Called by {rite} at line {line}\")\n else:\n lines.append(f\"Called by {rite}\")\n lines.append(\"(most recent call last)\")\n return lines\n","godcode/explain.py":"\"\"\"`godcode explain` -- say what a scroll does, without running it.\n\nStatic facts for humans and agents: the tongue, the rites and their\ndeclared intents, the names it declares, the lines it reveals, the\nseals it keeps, the verbs it summons, the questions it lays before the\nSpirit, the scrolls it brings in, and the powers it declares. Nothing\nexecutes; the walk is read-only over the parsed AST, so explaining a\nscroll is always safe.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport dataclasses\nfrom pathlib import Path\n\n\n# ---------------------------------------------------------------------------\n# walking\n# ---------------------------------------------------------------------------\ndef _iter_child(value):\n if dataclasses.is_dataclass(value) and not isinstance(value, type):\n yield from _iter_nodes(value)\n elif isinstance(value, (list, tuple)):\n for item in value:\n yield from _iter_child(item)\n\n\ndef _iter_nodes(node):\n \"\"\"Yield an AST node and every AST node nested inside it, at any depth.\n\n Statements may sit inside a creation block, an IF, a loop, a TRY, or\n a rite body; call expressions may sit inside any expression. The\n generic walk finds them all without enumerating every node kind.\n \"\"\"\n yield node\n if dataclasses.is_dataclass(node) and not isinstance(node, type):\n for field in dataclasses.fields(node):\n yield from _iter_child(getattr(node, field.name))\n\n\n# ---------------------------------------------------------------------------\n# facts\n# ---------------------------------------------------------------------------\ndef explain_facts(source: str, base_dir: str | Path | None) -> dict:\n \"\"\"Collect the static facts of a scroll.\n\n Raises the same GodCodeError ``parse_source`` raises on a broken\n scroll. ``base_dir`` resolves the manifest's relative paths, as in\n `godcode permissions`.\n \"\"\"\n from godcode.ast import (\n CallExpr,\n Declare,\n DeclareIntent,\n DefineRite,\n Import,\n Literal,\n Reveal,\n SealStmt,\n )\n from godcode.permissions import collect_manifest\n from godcode.tongues import _CODE_ALIASES, detect_tongue, parse_source, resolve\n\n program = parse_source(source)\n raw_tongue = detect_tongue(source)\n tongue_code = _CODE_ALIASES.get(raw_tongue, raw_tongue) if raw_tongue else \"en\"\n tongue_name = resolve(raw_tongue)[\"name\"]\n\n rites: list[dict] = []\n intents: list[dict] = []\n declarations: list[dict] = []\n reveals: list[dict] = []\n seals: list[dict] = []\n summons: list[dict] = []\n consults: list[dict] = []\n imports: list[dict] = []\n intent_by_rite: dict[str, str] = {}\n\n for node in _iter_nodes(program):\n if isinstance(node, DeclareIntent):\n intents.append(\n {\"rite\": node.rite, \"text\": node.text, \"line\": node.line}\n )\n intent_by_rite.setdefault(node.rite, node.text)\n elif isinstance(node, DefineRite):\n rites.append(\n {\n \"name\": node.name,\n \"params\": list(node.params),\n \"line\": node.line,\n \"intent\": intent_by_rite.get(node.name),\n }\n )\n elif isinstance(node, Declare):\n declarations.append({\"name\": node.name, \"line\": node.line})\n elif isinstance(node, Reveal):\n reveals.append({\"line\": node.line})\n elif isinstance(node, SealStmt):\n seals.append({\"line\": node.line, \"kind\": \"SEAL\"})\n elif isinstance(node, CallExpr):\n if node.callee == \"ANCHOR\":\n seals.append({\"line\": node.line, \"kind\": \"ANCHOR\"})\n elif node.callee == \"CONSULT\":\n consults.append({\"line\": node.line})\n elif node.callee == \"SUMMON\":\n verb = node.args[0] if node.args else None\n summons.append(\n {\n \"verb\": verb.value if isinstance(verb, Literal) else None,\n \"line\": node.line,\n }\n )\n elif isinstance(node, Import):\n imports.append({\"path\": node.path, \"line\": node.line})\n\n manifest = collect_manifest(program.statements, base_dir)\n\n # Intents may be declared after their rites; attach them now that\n # every DECLARE INTENT has been seen.\n for rite in rites:\n if rite[\"intent\"] is None:\n rite[\"intent\"] = intent_by_rite.get(rite[\"name\"])\n\n return {\n \"tongue\": {\"code\": tongue_code, \"name\": tongue_name},\n \"rites\": rites,\n \"intents\": intents,\n \"declarations\": declarations,\n \"permissions\": manifest.to_json(),\n \"reveals\": reveals,\n \"seals\": seals,\n \"summons\": summons,\n \"consults\": consults,\n \"imports\": imports,\n }\n\n\ndef explain_payload(file: str, ok: bool, diagnostics: list[dict],\n facts: dict | None = None) -> dict:\n \"\"\"The `godcode explain --json` envelope: the check/run envelope style.\"\"\"\n payload = {\n \"tool\": \"godcode\",\n \"command\": \"explain\",\n \"file\": file,\n \"ok\": ok,\n \"diagnostics\": diagnostics,\n }\n if facts:\n payload.update(facts)\n return payload\n\n\n# ---------------------------------------------------------------------------\n# human words\n# ---------------------------------------------------------------------------\ndef _count(n: int, one: str, many: str) -> str:\n return f\"{n} {one}\" if n == 1 else f\"{n} {many}\"\n\n\ndef human_summary(filename: str, facts: dict) -> str:\n \"\"\"The scroll in plain words, for `godcode explain` without --json.\"\"\"\n from godcode.permissions import PermissionManifest\n\n lines = [f\"The scroll {filename}, in plain words:\"]\n\n tongue = facts[\"tongue\"]\n if tongue[\"code\"] != \"en\":\n lines.append(f\"It speaks {tongue['name']}.\")\n\n rites = facts[\"rites\"]\n if not rites:\n lines.append(\"It defines no rites.\")\n elif len(rites) == 1:\n rite = rites[0]\n params = \", \".join(rite[\"params\"]) or \"no names\"\n lines.append(\n f\"It defines 1 rite: {rite['name']} (line {rite['line']}), \"\n f\"taking {_count(len(rite['params']), 'name', 'names')}\"\n + (f\" ({params}).\" if rite[\"params\"] else \".\")\n )\n if rite[\"intent\"]:\n lines.append(f' Its declared purpose: \"{rite[\"intent\"]}\".')\n else:\n lines.append(f\"It defines {_count(len(rites), 'rite', 'rites')}:\")\n for rite in rites:\n lines.append(\n f\" - {rite['name']} (line {rite['line']}), \"\n f\"taking {_count(len(rite['params']), 'name', 'names')}.\"\n )\n if rite[\"intent\"]:\n lines.append(f' Its declared purpose: \"{rite[\"intent\"]}\".')\n\n declarations = facts[\"declarations\"]\n if not declarations:\n lines.append(\"It declares no names.\")\n else:\n names = \", \".join(f\"{d['name']} (line {d['line']})\" for d in declarations)\n lines.append(f\"It declares {_count(len(declarations), 'name', 'names')}: {names}.\")\n\n reveals = facts[\"reveals\"]\n if not reveals:\n lines.append(\"It reveals nothing.\")\n else:\n at = \", \".join(f\"line {r['line']}\" for r in reveals)\n lines.append(f\"It reveals {_count(len(reveals), 'line', 'lines')}: {at}.\")\n\n seals = facts[\"seals\"]\n kept = [s for s in seals if s[\"kind\"] == \"SEAL\"]\n anchored = [s for s in seals if s[\"kind\"] == \"ANCHOR\"]\n if not seals:\n lines.append(\"It seals nothing.\")\n else:\n if kept:\n at = \", \".join(f\"line {s['line']}\" for s in kept)\n lines.append(f\"It seals {_count(len(kept), 'covenant', 'covenants')}: {at}.\")\n if anchored:\n at = \", \".join(f\"line {s['line']}\" for s in anchored)\n lines.append(f\"It anchors {_count(len(anchored), 'seal', 'seals')} on a chain: {at}.\")\n\n consults = facts[\"consults\"]\n if not consults:\n lines.append(\"It asks the Spirit nothing.\")\n else:\n at = \", \".join(f\"line {c['line']}\" for c in consults)\n lines.append(f\"It asks the Spirit {_count(len(consults), 'question', 'questions')}: {at}.\")\n\n summons = facts[\"summons\"]\n if not summons:\n lines.append(\"It summons nothing.\")\n else:\n verbs = \", \".join(\n f\"{s['verb'] or 'an unnamed verb'} (line {s['line']})\" for s in summons\n )\n lines.append(f\"It summons {_count(len(summons), 'verb', 'verbs')}: {verbs}.\")\n\n imports = facts[\"imports\"]\n if not imports:\n lines.append(\"It brings in nothing.\")\n else:\n paths = \", \".join(f\"{i['path']} (line {i['line']})\" for i in imports)\n lines.append(f\"It brings in {_count(len(imports), 'scroll', 'scrolls')}: {paths}.\")\n\n perms = facts[\"permissions\"]\n manifest = PermissionManifest()\n manifest.read_paths = list(perms.get(\"read\", []))\n manifest.write_paths = list(perms.get(\"write\", []))\n manifest.hosts = list(perms.get(\"network\", []))\n manifest.stdin = bool(perms.get(\"stdin\", False))\n manifest.summons = list(perms.get(\"summon\", []))\n described = manifest.describe()\n if not described:\n lines.append(\n \"It declares no permissions, so it touches nothing of the outer world.\"\n )\n else:\n lines.append(f\"It declares {_count(len(described), 'permission', 'permissions')}:\")\n for grant in described:\n lines.append(f\" - it {grant}\")\n\n return \"\\n\".join(lines)\n","godcode/interpreter.py":"\"\"\"Tree-walking interpreter for God Code v2.0.\n\nWalks the AST produced by godcode.parser, evaluating statements in\nlexically scoped environments. Divine-flavored messages on the surface,\nreal semantics underneath: lexical scoping, rite calls with RETURN,\na 100,000-iteration guard on WHILE, and line-numbered errors.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport random\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nfrom typing import Any, Callable, Optional\n\nfrom godcode.ast import (\n Anoint,\n Ascend,\n BinaryOp,\n Bless,\n Break,\n Breathe,\n CallExpr,\n Continue,\n CreationBlock,\n Declare,\n DeclareIntent,\n DeclarePermission,\n DefineRite,\n ExprStmt,\n ForLoop,\n Identifier,\n IfStmt,\n Import,\n Index,\n InterpolatedString,\n ListLiteral,\n Literal,\n Program,\n Prophesy,\n Reflect,\n Return,\n Reveal,\n SealStmt,\n Testify,\n TryStmt,\n UnaryOp,\n WhileLoop,\n)\nfrom godcode.environment import Environment\nfrom godcode.errors import (\n AscendSignal,\n BreakSignal,\n ContinueSignal,\n GodCodeError,\n GodRuntimeError,\n ReturnSignal,\n with_suggestion,\n)\nfrom godcode.tongues import parse_source\nfrom godcode import plugins\nfrom godcode import chain as chain_module\nfrom godcode.values import Contract, RiteFunction, Symbol\n\n_WHILE_ITERATION_CAP = 100_000\n\n\nclass Interpreter:\n \"\"\"Walks the God Code AST and brings it to life.\"\"\"\n\n def __init__(\n self,\n spirit=None,\n ledger=None,\n log_path: str | None = \"logs/godcode.log\",\n interactive: bool = False,\n chain_adapters: dict | None = None,\n ):\n self.spirit = spirit\n self.ledger = ledger\n self.log_path = log_path\n self.interactive = interactive\n self.output: list[str] = [] # every REVEAL line, in order\n self.emit: Callable[[str], None] = print # REVEAL output sink; override to capture\n self.last_value: Any = None # value of the last expression statement (embedding API)\n self.env = Environment() # root environment\n self.source_dir = Path.cwd() # for IMPORT resolution\n self._imported: set[str] = set() # resolved scroll paths already run\n self._import_stack: list[str] = [] # scrolls currently being run\n self._last_source: str = \"\"\n self._log_handle: Any = None\n # --- v5.2: runtime call stack ---\n # A lightweight list of {\"rite\": name, \"line\": call-site line},\n # pushed in _call_rite and popped as rites return (or raise). It\n # powers the \"Called by ...\" trace for uncaught errors and is\n # separate from the debugger's own frame list (which only exists\n # while a DebugSession is attached).\n # --- permission manifests ---\n # The scroll's declared powers, collected in run() before execution\n # and widened by union as imported scrolls declare their own. The\n # sandbox guard (when installed) enforces it against every rite.\n from godcode.permissions import PermissionManifest\n self.manifest: PermissionManifest = PermissionManifest()\n # --- end permission manifests ---\n self.call_stack: list[dict] = []\n # --- end v5.2 ---\n self._plugin_verbs: dict[str, Callable[..., Any]] = {} # namespaced verbs from plugins\n self._plugin_verb_info: dict[str, dict] = {} # name -> {\"plugin\", \"trusted\", \"func\"}\n self.loaded_plugins: list[str] = [] # plugin names whose register() ran cleanly\n # --- debugger hook (v5.0) ---\n # Set to a godcode.debugger.DebugSession to trace execution. None\n # keeps the fast path: _exec_block checks this once per statement.\n self.debugger = None\n # --- end debugger hook ---\n # --- v4.0: intent layer + chain adapters ---\n self.intents: dict[str, str] = {} # rite name -> declared intent text\n self.intent_checks: list[dict] = [] # per-invocation alignment records\n self.chain_adapters = (\n chain_adapters\n if chain_adapters is not None\n else chain_module.default_adapters()\n )\n # --- end v4.0 ---\n self._builtins: dict[str, Callable[..., Any]] = {\n \"LEN\": self._builtin_len,\n \"STR\": self._builtin_str,\n \"NUM\": self._builtin_num,\n \"TYPE\": self._builtin_type,\n \"RANDOM\": self._builtin_random,\n \"RANGE\": self._builtin_range,\n \"PUSH\": self._builtin_push,\n \"UPPER\": self._builtin_upper,\n \"LOWER\": self._builtin_lower,\n \"SPLIT\": self._builtin_split,\n \"JOIN\": self._builtin_join,\n \"ASK\": self._builtin_ask,\n \"BEHOLD\": self._builtin_behold,\n \"REVERSE\": self._builtin_reverse,\n \"SUMMON\": self._builtin_summon,\n \"ANCHOR\": self._builtin_anchor, # v4.0\n \"CONSULT\": self._builtin_consult, # v4.0\n }\n # Pillar 3 — plugins auto-load at startup (the same path `godcode run`\n # and the REPL take). GODCODE_NO_PLUGINS=1 disables this.\n if os.environ.get(plugins.DISABLE_ENV_VAR) != \"1\":\n self.loaded_plugins = plugins.load_plugins(self)\n # v5.1: the stdlib pillars register their own builtins here so the\n # interpreter core stays small. Each module's register() is idempotent.\n from godcode import stdlib_commons, stdlib_times, stdlib_vault, stdlib_hashes\n\n stdlib_vault.register(self)\n stdlib_times.register(self)\n stdlib_hashes.register(self)\n stdlib_commons.register(self)\n\n # ------------------------------------------------- plugin verb registry\n\n def register_plugin_verb(\n self,\n name: str,\n func: Callable[..., Any],\n *,\n plugin: str | None = None,\n ) -> str:\n \"\"\"Register a plugin verb callable from God Code via SUMMON.\n\n *name* is namespaced by convention (``\"clockwork.now\"``); *func* is a\n plain Python callable ``func(*args)`` — values are converted\n God Code <-> Python automatically (see godcode.plugins). The verb is\n marked ``trusted=True``: plugin code is trusted host code and SUMMON\n calls bypass sandbox policy by design; the marker lets a future\n sandbox pillar consult it.\n \"\"\"\n if not isinstance(name, str) or not name:\n raise ValueError(\"a plugin verb needs a non-empty string name\")\n if not callable(func):\n raise ValueError(f\"plugin verb '{name}' is not callable\")\n adapter = plugins.make_verb_adapter(name, func)\n self._builtins[name] = adapter # exact key — namespaced names keep their case\n self._plugin_verbs[name] = adapter\n self._plugin_verb_info[name] = {\"plugin\": plugin, \"trusted\": True, \"func\": func}\n return name\n\n @property\n def plugin_verb_info(self) -> dict[str, dict]:\n \"\"\"Read-only view of plugin verb metadata (name -> plugin/trusted/func).\"\"\"\n return dict(self._plugin_verb_info)\n\n # ------------------------------------------------------------------ run\n\n def run(self, program, source_name: str = \"\") -> None:\n \"\"\"Execute a parsed Program. ASCEND ends the run in peace.\"\"\"\n self._imported = set()\n self._import_stack = []\n self.call_stack = [] # fresh trace for every run\n if self._looks_like_file(source_name):\n self.source_dir = Path(source_name).resolve().parent\n # --- permission manifests ---\n # Gather the scroll's declared powers before anything runs, then\n # bind the guard so every rite is measured against them.\n from godcode.permissions import PermissionManifest, collect_manifest\n self.manifest = collect_manifest(\n self._statements_of(program), self.source_dir)\n self._bind_manifest_guard()\n # --- end permission manifests ---\n self._open_log()\n try:\n self._log(f\"SESSION BEGIN {source_name} {self._now()}\")\n try:\n self._exec_block(self._statements_of(program), self.env)\n except AscendSignal:\n message = \"🕊 Creation ascended in peace.\"\n print(message)\n self._log(\"ASCEND :: the creation ascended in peace\")\n self._log(f\"SESSION END {source_name}\")\n finally:\n self._close_log()\n\n def run_source(self, source: str, source_name: str = \"\") -> None:\n \"\"\"Lex, parse, and run God Code source text.\"\"\"\n self._last_source = source\n program = parse_source(source)\n self.run(program, source_name=source_name)\n\n @staticmethod\n def _statements_of(program):\n statements = getattr(program, \"statements\", None)\n if statements is None:\n raise GodRuntimeError(\"What was given to run is not a creation.\")\n return statements\n\n @staticmethod\n def _looks_like_file(source_name: str) -> bool:\n try:\n return Path(source_name).is_file()\n except (OSError, ValueError):\n return False\n\n # --- permission manifests ---\n\n def _bind_manifest_guard(self) -> None:\n \"\"\"Install the guard under the open host policy when a manifest\n is declared and no guard is installed yet (the --sandbox path\n installs its own strict guard, which then also sees the manifest).\n \"\"\"\n if not self.manifest:\n return\n if getattr(self, \"_sandbox_guard\", None) is not None:\n return\n from godcode.sandbox import SandboxPolicy, apply_policy\n apply_policy(self, SandboxPolicy.open())\n\n # --- end permission manifests ---\n\n # ------------------------------------------------------------- statements\n\n def _exec_block(self, statements: list, env: Environment) -> None:\n for stmt in statements:\n if self.debugger is not None:\n self.debugger.before_stmt(stmt, env)\n self._log_statement(stmt)\n try:\n self._exec_stmt(stmt, env)\n except (ReturnSignal, AscendSignal, BreakSignal, ContinueSignal):\n raise # control-flow signals pass through untouched\n except GodCodeError as err:\n self._attach_line(err, getattr(stmt, \"line\", None))\n # --- v5.2: snapshot the call stack for uncaught-error\n # traces. This innermost handler fires before any _call_rite\n # finally unwinds, so the stack is still whole. First sight\n # wins: an error re-raised from a CATCH keeps the stack of\n # where it first rose.\n if getattr(err, \"call_trace\", None) is None:\n err.call_trace = self.call_trace()\n # --- end v5.2 ---\n self._log(f\"ERROR :: line {getattr(err, 'line', '?')} :: {err}\")\n raise\n\n @staticmethod\n def _attach_line(err: GodCodeError, line) -> None:\n try:\n if getattr(err, \"line\", None) is None and line is not None:\n err.line = line\n except (AttributeError, TypeError):\n pass\n\n def _exec_stmt(self, stmt, env: Environment) -> None:\n if isinstance(stmt, CreationBlock):\n self._exec_block(stmt.statements, env)\n elif isinstance(stmt, Declare):\n env.define(stmt.name, self._eval_expr(stmt.value, env))\n elif isinstance(stmt, DeclareIntent):\n self._exec_declare_intent(stmt)\n elif isinstance(stmt, DeclarePermission):\n pass # the manifest was gathered before the run; nothing to do\n elif isinstance(stmt, Breathe):\n self._exec_breathe(stmt, env)\n elif isinstance(stmt, Reveal):\n line = self.stringify(self._eval_expr(stmt.expr, env))\n self.emit(line)\n self.output.append(line)\n elif isinstance(stmt, Prophesy):\n self._exec_prophesy(stmt)\n elif isinstance(stmt, Ascend):\n raise AscendSignal()\n elif isinstance(stmt, Reflect):\n self._exec_reflect(env)\n elif isinstance(stmt, Bless):\n self._exec_consecrate(stmt, env, kind=\"bless\")\n elif isinstance(stmt, Anoint):\n self._exec_consecrate(stmt, env, kind=\"anoint\")\n elif isinstance(stmt, SealStmt):\n self._exec_seal(stmt, env)\n elif isinstance(stmt, Testify):\n self._exec_testify(stmt, env)\n elif isinstance(stmt, IfStmt):\n branch = stmt.then_body if self._truthy(self._eval_expr(stmt.cond, env)) else stmt.else_body\n self._exec_block(branch, env)\n elif isinstance(stmt, ForLoop):\n self._exec_for(stmt, env)\n elif isinstance(stmt, WhileLoop):\n self._exec_while(stmt, env)\n elif isinstance(stmt, Break):\n raise BreakSignal()\n elif isinstance(stmt, Continue):\n raise ContinueSignal()\n elif isinstance(stmt, TryStmt):\n self._exec_try(stmt, env)\n elif isinstance(stmt, DefineRite):\n env.define(stmt.name, RiteFunction(stmt.name, stmt.params, stmt.body, env))\n elif isinstance(stmt, Return):\n raise ReturnSignal(self._eval_expr(stmt.expr, env) if stmt.expr is not None else None)\n elif isinstance(stmt, Import):\n self._exec_import(stmt, env)\n elif isinstance(stmt, ExprStmt):\n # The value is kept for the embedding API (RunResult.return_value).\n self.last_value = self._eval_expr(stmt.expr, env)\n else:\n raise GodRuntimeError(\n f\"The heavens do not recognize this utterance: {type(stmt).__name__}.\",\n getattr(stmt, \"line\", None),\n )\n\n # ------------------------------------------------------- statement helpers\n\n def _exec_breathe(self, stmt: Breathe, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n if not env.is_bound(stmt.name):\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no '{stmt.name}' to breathe into. \"\n \"It was never spoken into being.\",\n stmt.name,\n env.names(),\n ),\n line,\n )\n target = env.get(stmt.name)\n if isinstance(target, Contract):\n target.alive = True\n print(f\"[BREATHE] Life breathed into {stmt.name} 🕊\")\n\n def _exec_prophesy(self, stmt: Prophesy) -> None:\n text = stmt.text or \"\"\n if self.spirit is None:\n print(f\"[PROPHESY] The Spirit is silent. No oracle is bound. ({text!r})\")\n return\n payload = text if text else self._last_source\n utterance = self.spirit.prophesy(payload)\n print(utterance)\n\n def _exec_reflect(self, env: Environment) -> dict:\n table = {name: self.stringify(value) for name, value in env.items()}\n for name, rendered in table.items():\n print(f\"{name} = {rendered}\")\n return table\n\n def _exec_consecrate(self, stmt, env: Environment, kind: str) -> None:\n line = getattr(stmt, \"line\", None)\n name = stmt.name\n verb = \"bless\" if kind == \"bless\" else \"anoint\"\n if not env.is_bound(name):\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no '{name}' to {verb}. It was never spoken into being.\",\n name,\n env.names(),\n ),\n line,\n )\n target = env.get(name)\n if isinstance(target, Contract):\n if kind == \"bless\":\n target.blessed = True\n else:\n target.anointed = True\n mark = \"✨\" if kind == \"bless\" else \"🕊\"\n print(f\"[{kind.upper()}] {name} is {verb}ed {mark}\")\n\n def _exec_seal(self, stmt: SealStmt, env: Environment) -> None:\n value = self._eval_expr(stmt.expr, env)\n record: dict[str, Any] = {\n \"sealed\": self.stringify(value),\n \"type\": self.type_name(value),\n \"by\": \"godcode\",\n }\n if isinstance(value, Contract):\n record.update(\n {\n \"name\": value.name,\n \"alive\": value.alive,\n \"blessed\": value.blessed,\n \"anointed\": value.anointed,\n }\n )\n if self.ledger is None:\n print(\"[SEAL] ⚠ No covenant ledger is bound. The seal is spoken but not recorded.\")\n self._log(\"SEAL :: no ledger bound; seal spoken but not recorded\")\n return\n block = self.ledger.seal(record)\n digest = str(block.get(\"hash\", \"\"))[:8]\n print(f\"[SEAL] Covenant sealed · block {block.get('index')} · {digest} 🔒\")\n self._log(f\"SEAL :: block {block.get('index')} recorded\")\n\n def _exec_testify(self, stmt: Testify, env: Environment) -> None:\n if self._truthy(self._eval_expr(stmt.expr, env)):\n print(\"[TESTIFY] It is true. ✝\")\n else:\n raise GodRuntimeError(\n \"The testimony has failed. What was spoken does not hold true.\",\n getattr(stmt, \"line\", None),\n )\n\n # ------------------------------------------------- v4.0: intent layer\n\n def _exec_declare_intent(self, stmt: DeclareIntent) -> None:\n \"\"\"Register a natural-language intent on a named rite.\"\"\"\n self.intents[stmt.rite] = stmt.text\n if self.spirit is not None:\n self.spirit.declare_intent(stmt.rite, stmt.text)\n print(f'[INTENT] {stmt.rite} now carries the intent: \"{stmt.text}\" 🕊')\n self._log(f\"INTENT DECLARE :: {stmt.rite}\")\n\n def _discern_intent(self, rite: RiteFunction, declared: str) -> None:\n \"\"\"Discern a rite's actual intent and counsel on divergence.\n\n Classifies the rite's own words with the Spirit Engine and\n compares against the declared intent. A gentle [INTENT] notice\n when they align, a [WARNING] when they drift. The run is never\n failed over divergence: the Spirit counsels, it does not condemn.\n \"\"\"\n from godcode.cli import CanonicalFormatter # lazy: cli imports us lazily\n\n body_text = CanonicalFormatter().format(Program(statements=rite.body))\n discerned = self.spirit.classify(body_text)\n aligned = self.spirit.intents_aligned(declared, discerned)\n self.intent_checks.append(\n {\n \"rite\": rite.name,\n \"declared\": declared,\n \"discerned\": discerned[\"intent\"],\n \"confidence\": discerned[\"confidence\"],\n \"aligned\": aligned,\n }\n )\n if aligned:\n print(f'[INTENT] {rite.name} walks in its declared intent: \"{declared}\" 🕊')\n else:\n print(\n f'[WARNING] {rite.name} drifts from its declared intent. '\n f'Declared: \"{declared}\". '\n f'Discerned: \"{discerned[\"intent\"]}\". '\n \"The Spirit counsels; it does not condemn.\"\n )\n self._log(f\"INTENT CHECK :: {rite.name} aligned={aligned}\")\n\n def _exec_for(self, stmt: ForLoop, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n iterable = self._eval_expr(stmt.iterable, env)\n if isinstance(iterable, Symbol):\n raise GodRuntimeError(\n f\"FOR needs a list or a word to walk through, not the bare spirit '{iterable}'.\",\n line,\n )\n if isinstance(iterable, str):\n items = list(iterable)\n elif isinstance(iterable, list):\n items = list(iterable)\n else:\n raise GodRuntimeError(\n f\"FOR cannot walk through {self.type_name(iterable)}. Only lists and words.\",\n line,\n )\n child = Environment(parent=env) # one child env for the whole loop\n for item in items:\n child.define(stmt.var, item)\n try:\n self._exec_block(stmt.body, child)\n except ContinueSignal:\n continue # next turn of this loop\n except BreakSignal:\n break # the loop is released at once\n # A BreakSignal is caught only here, so in nested loops it releases\n # the innermost loop alone.\n\n def _exec_while(self, stmt: WhileLoop, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n count = 0\n # The body runs in the current environment so DECLARE can rebind the\n # names the condition watches (there is no separate assignment rite).\n while self._truthy(self._eval_expr(stmt.cond, env)):\n count += 1\n if count > _WHILE_ITERATION_CAP:\n raise GodRuntimeError(\n \"The cycle is endless. 100,000 turns and still no rest. \"\n \"The loop is released.\",\n line,\n )\n try:\n self._exec_block(stmt.body, env)\n except ContinueSignal:\n continue # the condition is weighed again for the next turn\n except BreakSignal:\n break # the cycle ends at once\n\n def _exec_try(self, stmt: TryStmt, env: Environment) -> None:\n # Only GodRuntimeError is caught: parse/lexer errors fail before a\n # run ever starts, and ReturnSignal / AscendSignal are plain\n # Exceptions (not GodCodeError subclasses), so a RETURN inside TRY\n # still returns from its rite and ASCEND still ends the run in peace.\n # Errors raised inside the CATCH body are outside this try, so they\n # propagate outward normally; nested TRYs handle their own errors.\n try:\n self._exec_block(stmt.try_body, env)\n except GodRuntimeError as err:\n # Bind the plain message (err.msg, without the location suffix\n # str(err) would append) so the CATCH can speak of it.\n env.define(stmt.error_name, err.msg)\n self._exec_block(stmt.catch_body, env)\n\n def _exec_import(self, stmt: Import, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n path = self._resolve_import(stmt.path, line)\n key = str(path)\n if key in self._imported:\n return # already breathed in; skip\n if key in self._import_stack:\n raise GodRuntimeError(\n f\"The scroll '{stmt.path}' calls upon itself. A circle with no end.\",\n line,\n )\n self._imported.add(key)\n self._import_stack.append(key)\n previous_dir = self.source_dir\n previous_source = self._last_source\n self.source_dir = path.parent\n if self.debugger is not None:\n self.debugger.enter_file(str(path))\n try:\n source = path.read_text(encoding=\"utf-8\")\n self._last_source = source\n program = parse_source(source)\n self._log(f\"IMPORT :: {path}\")\n # Permission manifests compose by union: an imported scroll may\n # grant powers the importing scroll did not declare.\n from godcode.permissions import collect_manifest\n self.manifest = self.manifest.merge(\n collect_manifest(self._statements_of(program), self.source_dir)\n )\n self._bind_manifest_guard()\n self._exec_block(self._statements_of(program), env)\n finally:\n if self.debugger is not None:\n self.debugger.exit_file()\n self._import_stack.pop()\n self.source_dir = previous_dir\n self._last_source = previous_source\n\n def _resolve_import(self, import_path: str, line) -> Path:\n raw = Path(import_path)\n scrolls_dir = Path(__file__).parent / \"scrolls\"\n candidates = [\n self.source_dir / raw,\n Path.cwd() / raw,\n scrolls_dir / raw,\n ]\n if not raw.suffix:\n candidates.extend(\n [\n self.source_dir / f\"{import_path}.god\",\n Path.cwd() / f\"{import_path}.god\",\n scrolls_dir / f\"{import_path}.god\",\n ]\n )\n for candidate in candidates:\n try:\n if candidate.is_file():\n return candidate.resolve()\n except OSError:\n continue\n # --- v3: scroll registry --- installed registry scrolls\n # (project-local .godcode/scrolls, then user-global ~/.godcode/scrolls)\n # resolve bare names via their manifest entry file. Stdlib keeps its\n # precedence above, so stdlib behavior is unchanged.\n installed = self._resolve_installed_scroll(import_path)\n if installed is not None:\n return installed\n # --- end v3: scroll registry ---\n raise GodRuntimeError(\n f\"The scroll '{import_path}' could not be found. Not beside the \"\n \"creation, not in this place, not among the scrolls.\",\n line,\n )\n\n def _resolve_installed_scroll(self, import_path: str) -> Path | None:\n \"\"\"Resolve a bare scroll name against installed registry scrolls.\"\"\"\n if \"/\" in import_path or \"\\\\\" in import_path:\n return None # only bare names; never paths\n name = import_path[:-4] if import_path.endswith(\".god\") else import_path\n try:\n from godcode.registry import ScrollRegistry\n except ImportError:\n return None\n try:\n return ScrollRegistry().resolve_entry(name)\n except Exception:\n return None\n\n # ------------------------------------------------------------- expressions\n\n def _eval_expr(self, expr, env: Environment):\n line = getattr(expr, \"line\", None)\n if isinstance(expr, Literal):\n return expr.value\n if isinstance(expr, InterpolatedString):\n return \"\".join(\n part if isinstance(part, str)\n else self.stringify(self._eval_expr(part, env))\n for part in expr.parts\n )\n if isinstance(expr, Identifier):\n return env.get(expr.name)\n if isinstance(expr, ListLiteral):\n return [self._eval_expr(item, env) for item in expr.items]\n if isinstance(expr, Index):\n return self._eval_index(expr, env)\n if isinstance(expr, UnaryOp):\n return self._eval_unary(expr, env)\n if isinstance(expr, BinaryOp):\n return self._eval_binary(expr, env)\n if isinstance(expr, CallExpr):\n args = [self._eval_expr(arg, env) for arg in expr.args]\n return self._call(expr.callee, args, env, line)\n raise GodRuntimeError(\n f\"The heavens do not recognize this expression: {type(expr).__name__}.\",\n line,\n )\n\n def _eval_index(self, expr: Index, env: Environment):\n line = getattr(expr, \"line\", None)\n obj = self._eval_expr(expr.obj, env)\n index = self._eval_expr(expr.index, env)\n # --- v4.0: maps are indexed by word ---\n if isinstance(obj, dict):\n if not isinstance(index, str):\n raise GodRuntimeError(\n f\"Only words may point into a map. Not {self.type_name(index)}.\",\n line,\n )\n key = str(index)\n if key not in obj:\n known = \", \".join(obj) or \"it holds nothing\"\n raise GodRuntimeError(\n with_suggestion(\n f\"The map holds no '{key}'. Its keys are: {known}.\",\n key,\n list(obj),\n ),\n line,\n )\n return obj[key]\n # --- end v4.0 ---\n if not self._is_int(index):\n raise GodRuntimeError(\n f\"Only whole numbers may point into {self.type_name(obj)}. Not {self.type_name(index)}.\",\n line,\n )\n if isinstance(obj, Symbol):\n raise GodRuntimeError(\n f\"Cannot point into the bare spirit '{obj}'. Bind it to a list or word first.\",\n line,\n )\n if isinstance(obj, (list, str)):\n try:\n return obj[index]\n except IndexError:\n raise GodRuntimeError(\n f\"Index {index} reaches beyond what is there \"\n f\"(it holds {len(obj)}).\",\n line,\n ) from None\n raise GodRuntimeError(\n f\"Cannot point into {self.type_name(obj)}. Only lists and words may be indexed.\",\n line,\n )\n\n def _eval_unary(self, expr: UnaryOp, env: Environment):\n line = getattr(expr, \"line\", None)\n operand = self._eval_expr(expr.operand, env)\n if expr.op == \"not\":\n return not self._truthy(operand)\n if expr.op == \"-\":\n if self._is_number(operand):\n return -operand\n raise GodRuntimeError(\n f\"Cannot negate {self.type_name(operand)}. Only numbers know the void's mirror.\",\n line,\n )\n raise GodRuntimeError(f\"Unknown sign '{expr.op}'.\", line)\n\n def _eval_binary(self, expr: BinaryOp, env: Environment):\n line = getattr(expr, \"line\", None)\n left = self._eval_expr(expr.left, env)\n right = self._eval_expr(expr.right, env)\n op = expr.op\n if op == \"==\":\n return self._equals(left, right)\n if op == \"!=\":\n return not self._equals(left, right)\n if op in (\"<\", \">\", \"<=\", \">=\"):\n return self._compare(op, left, right, line)\n if op == \"+\":\n return self._add(left, right, line)\n if op in (\"-\", \"*\", \"/\", \"%\"):\n return self._arithmetic(op, left, right, line)\n if op == \"and\":\n return left if not self._truthy(left) else right\n if op == \"or\":\n return left if self._truthy(left) else right\n raise GodRuntimeError(f\"Unknown joining '{op}'.\", line)\n\n # ------------------------------------------------------- value operations\n\n @staticmethod\n def _is_int(value) -> bool:\n return isinstance(value, int) and not isinstance(value, bool)\n\n @classmethod\n def _is_number(cls, value) -> bool:\n return isinstance(value, (int, float)) and not isinstance(value, bool)\n\n def _equals(self, left, right) -> bool:\n # Contract vs Contract: by name. Symbol vs str: by text (str subclass\n # equality already does this). Numbers: cross-type. Lists: elementwise.\n if isinstance(left, Contract) or isinstance(right, Contract):\n return (\n isinstance(left, Contract)\n and isinstance(right, Contract)\n and left.name == right.name\n )\n try:\n return bool(left == right)\n except Exception: # pragma: no cover - defensive\n return False\n\n def _compare(self, op: str, left, right, line) -> bool:\n if self._is_number(left) and self._is_number(right):\n if op == \"<\":\n return left < right\n if op == \">\":\n return left > right\n if op == \"<=\":\n return left <= right\n return left >= right\n raise GodRuntimeError(\n f\"Cannot weigh {self.type_name(left)} against {self.type_name(right)}. \"\n \"Only numbers may be measured.\",\n line,\n )\n\n def _add(self, left, right, line):\n if self._is_number(left) and self._is_number(right):\n return left + right\n if isinstance(left, str) and isinstance(right, str):\n return str(left) + str(right) # plain str, even for Symbols\n if isinstance(left, list) and isinstance(right, list):\n return left + right\n raise GodRuntimeError(\n f\"Cannot join {self.type_name(left)} and {self.type_name(right)}. \"\n \"They are of different kingdoms.\",\n line,\n )\n\n def _arithmetic(self, op: str, left, right, line):\n if op == \"%\":\n if not (self._is_int(left) and self._is_int(right)):\n raise GodRuntimeError(\n f\"The remainder rite needs whole numbers, not \"\n f\"{self.type_name(left)} and {self.type_name(right)}.\",\n line,\n )\n elif not (self._is_number(left) and self._is_number(right)):\n raise GodRuntimeError(\n f\"Cannot reckon {self.type_name(left)} and {self.type_name(right)}. \"\n \"Only numbers may be reckoned.\",\n line,\n )\n if op in (\"/\", \"%\") and right == 0:\n raise GodRuntimeError(\n \"Division by nothing is not permitted. Even the heavens \"\n \"cannot split the void.\",\n line,\n )\n if op == \"-\":\n return left - right\n if op == \"*\":\n return left * right\n if op == \"/\":\n return left / right # always float, as the waters divide\n return left % right\n\n @staticmethod\n def _truthy(value) -> bool:\n # False / None / 0 / \"\" / [] / {} are empty; Symbols are always truthy.\n if value is None:\n return False\n if isinstance(value, bool):\n return value\n if isinstance(value, Symbol):\n return True\n if isinstance(value, (int, float)):\n return value != 0\n if isinstance(value, str):\n return len(value) > 0\n if isinstance(value, (list, dict)):\n return len(value) > 0\n return True # Contracts, rites, and all other living things\n\n # ----------------------------------------------------------------- rites\n\n def _call(self, name: str, args: list, env: Environment, line):\n if name == \"contract\":\n if len(args) == 1 and isinstance(args[0], (str, Symbol)):\n return Contract(str(args[0]))\n raise GodRuntimeError(\n \"The contract rite needs exactly one name. A single word to seal.\",\n line,\n )\n target = env.get(name) if env.is_bound(name) else None\n if isinstance(target, RiteFunction):\n return self._call_rite(target, args, line)\n # Exact match first so namespaced plugin verbs (\"clockwork.now\") keep\n # their case; core verbs still resolve case-insensitively via UPPER.\n builtin = self._builtins.get(name)\n if builtin is None:\n builtin = self._builtins.get(name.upper())\n if builtin is not None:\n return builtin(args, line)\n if target is not None:\n raise GodRuntimeError(\n f\"'{name}' is {self.type_name(target)}, not a rite. It cannot be invoked.\",\n line,\n )\n rite_names = [\n rite_name\n for rite_name in env.names()\n if isinstance(env.get(rite_name), RiteFunction)\n ]\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no rite named '{name}'. The heavens do not know it.\",\n name,\n rite_names + list(self._builtins),\n ),\n line,\n )\n\n def _call_rite(self, rite: RiteFunction, args: list, line):\n if len(args) != len(rite.params):\n want, got = len(rite.params), len(args)\n raise GodRuntimeError(\n f\"Rite '{rite.name}' asks for {want} offering{'s' if want != 1 else ''}, \"\n f\"but {got} {'was' if got == 1 else 'were'} brought.\",\n line,\n )\n # --- v4.0: intent layer — discern the rite's actual intent when it\n # carries a declared one. Never fails the run; counsel, don't punish.\n declared = self.intents.get(rite.name)\n if declared is not None and self.spirit is not None:\n self._discern_intent(rite, declared)\n # --- end v4.0 ---\n call_env = Environment(parent=rite.closure_env)\n for param, value in zip(rite.params, args):\n call_env.define(param, value)\n rendered = \", \".join(self.stringify(a) for a in args)\n self._log(f\"RITE CALL :: {rite.name}({rendered})\")\n # --- v5.2: runtime call stack for uncaught-error traces ---\n self.call_stack.append({\"rite\": rite.name, \"line\": line})\n # --- end v5.2 ---\n if self.debugger is not None:\n self.debugger.enter_rite(rite, call_env)\n try:\n try:\n self._exec_block(rite.body, call_env)\n except ReturnSignal as ret:\n return ret.value\n except (BreakSignal, ContinueSignal) as sig:\n # The parser binds every BREAK/CONTINUE to a lexically\n # enclosing loop, so this is unreachable from parsed source.\n # Programmatic ASTs reach it: loop signals never cross a\n # rite boundary, they end here with a plain error.\n word = \"BREAK\" if isinstance(sig, BreakSignal) else \"CONTINUE\"\n raise GodRuntimeError(\n f\"{word} cannot cross the threshold of a rite. It may \"\n f\"only release a loop within rite '{rite.name}' itself.\",\n line,\n ) from None\n return None\n finally:\n # --- v5.2 ---\n self.call_stack.pop()\n # --- end v5.2 ---\n if self.debugger is not None:\n self.debugger.exit_rite(rite)\n\n def call_trace(self) -> list[dict]:\n \"\"\"A snapshot of the rite call stack for uncaught-error reports.\n\n Oldest call first (the most recent call is last). Each entry is\n ``{\"rite\": name, \"line\": call-site line}``.\n \"\"\"\n return [dict(frame) for frame in self.call_stack]\n\n # --------------------------------------------------------------- builtins\n\n @staticmethod\n def _arity(name: str, args: list, want, line) -> None:\n ok = len(args) == want if isinstance(want, int) else len(args) in want\n if not ok:\n expected = want if isinstance(want, int) else \" or \".join(map(str, want))\n raise GodRuntimeError(\n f\"{name} asks for {expected} offering(s), but {len(args)} came.\",\n line,\n )\n\n def _builtin_len(self, args, line):\n self._arity(\"LEN\", args, 1, line)\n value = args[0]\n if isinstance(value, (str, list)):\n return len(value)\n raise GodRuntimeError(\n f\"LEN cannot measure {self.type_name(value)}. Only words and lists have length.\",\n line,\n )\n\n def _builtin_str(self, args, line):\n self._arity(\"STR\", args, 1, line)\n value = args[0]\n if isinstance(value, str):\n return str(value)\n return self.stringify(value)\n\n def _builtin_num(self, args, line):\n self._arity(\"NUM\", args, 1, line)\n value = args[0]\n if self._is_number(value):\n return value\n if isinstance(value, str):\n text = value.strip()\n try:\n return int(text)\n except ValueError:\n pass\n try:\n return float(text)\n except ValueError:\n pass\n raise GodRuntimeError(\n f\"NUM cannot number the word '{value}'. It holds no number.\",\n line,\n )\n raise GodRuntimeError(\n f\"NUM cannot number {self.type_name(value)}.\",\n line,\n )\n\n def _builtin_type(self, args, line):\n self._arity(\"TYPE\", args, 1, line)\n return self.type_name(args[0])\n\n def _builtin_random(self, args, line):\n self._arity(\"RANDOM\", args, 1, line)\n bound = args[0]\n if not self._is_int(bound) or bound <= 0:\n raise GodRuntimeError(\n \"RANDOM needs a positive whole number to cast lots within.\",\n line,\n )\n return random.randrange(bound)\n\n def _builtin_range(self, args, line):\n self._arity(\"RANGE\", args, (1, 2), line)\n for value in args:\n if not self._is_int(value):\n raise GodRuntimeError(\n \"RANGE walks only in whole numbers.\",\n line,\n )\n if len(args) == 1:\n if args[0] < 0:\n raise GodRuntimeError(\"RANGE cannot walk a negative span.\", line)\n return list(range(args[0]))\n return list(range(args[0], args[1]))\n\n def _builtin_push(self, args, line):\n self._arity(\"PUSH\", args, 2, line)\n items, value = args\n if not isinstance(items, list):\n raise GodRuntimeError(\n f\"PUSH needs a list to build upon, not {self.type_name(items)}.\",\n line,\n )\n return items + [value] # a new list; the old one is untouched\n\n def _builtin_upper(self, args, line):\n self._arity(\"UPPER\", args, 1, line)\n return self._upper_lower(args[0], str.upper, \"UPPER\", line)\n\n def _builtin_lower(self, args, line):\n self._arity(\"LOWER\", args, 1, line)\n return self._upper_lower(args[0], str.lower, \"LOWER\", line)\n\n def _upper_lower(self, value, func, name, line):\n if not isinstance(value, str):\n raise GodRuntimeError(\n f\"{name} speaks only to words, not {self.type_name(value)}.\",\n line,\n )\n return func(str(value))\n\n def _builtin_split(self, args, line):\n self._arity(\"SPLIT\", args, 2, line)\n text, sep = args\n if not isinstance(text, str) or not isinstance(sep, str):\n raise GodRuntimeError(\"SPLIT needs two words. The text and the divider.\", line)\n return text.split(str(sep))\n\n def _builtin_join(self, args, line):\n self._arity(\"JOIN\", args, 2, line)\n items, sep = args\n if not isinstance(items, list) or not isinstance(sep, str):\n raise GodRuntimeError(\n \"JOIN needs a list and a word to bind it with.\", line\n )\n return str(sep).join(self.stringify(item) for item in items)\n\n def _builtin_ask(self, args, line):\n self._arity(\"ASK\", args, (0, 1), line)\n prompt = self.stringify(args[0]) if args else \"\"\n try:\n answer = input(prompt)\n except EOFError:\n return \"\"\n return answer\n\n def _builtin_behold(self, args, line):\n self._arity(\"BEHOLD\", args, 0, line)\n return datetime.now(timezone.utc).isoformat()\n\n def _builtin_reverse(self, args, line):\n self._arity(\"REVERSE\", args, 1, line)\n value = args[0]\n if isinstance(value, str):\n return str(value)[::-1]\n if isinstance(value, list):\n return value[::-1]\n raise GodRuntimeError(\n f\"REVERSE can only turn back words and lists, not {self.type_name(value)}.\",\n line,\n )\n\n def _builtin_summon(self, args, line):\n # Pillar 3 FFI: SUMMON(\"plugin.verb\", arg1, ...) calls a\n # plugin-registered verb with converted arguments. The name is a\n # string literal so no grammar change was needed; namespaced names\n # (\"clockwork.now\") keep plugin verbs from colliding with core rites.\n if not args:\n raise GodRuntimeError(\n 'SUMMON needs a verb to call upon. SUMMON(\"name.verb\", ...).',\n line,\n )\n target = args[0]\n if not isinstance(target, str):\n raise GodRuntimeError(\n \"SUMMON needs the verb's name as a word, \"\n f\"not {self.type_name(target)}.\",\n line,\n )\n verb = self._plugin_verbs.get(target)\n if verb is None:\n known = \", \".join(sorted(self._plugin_verbs)) or \"none are present\"\n raise GodRuntimeError(\n f\"SUMMON knows no verb '{target}'. The summoned are: {known}.\",\n line,\n )\n return verb(args[1:], line)\n\n # ------------------------------------------------- v4.0: chain + oracle\n\n def _builtin_anchor(self, args, line):\n \"\"\"ANCHOR(expr [, chain_name]) -- anchor a value's hash on a chain.\n\n Returns the receipt: a map {chain, anchor_hash, height, timestamp,\n payload_hash}. The default chain is \"simulated\" (a local\n tamper-evident JSONL chain); real chain adapters register by name.\n \"\"\"\n import hashlib\n\n self._arity(\"ANCHOR\", args, (1, 2), line)\n value = args[0]\n chain_name = chain_module.DEFAULT_CHAIN_NAME\n if len(args) == 2:\n name_arg = args[1]\n if not isinstance(name_arg, str):\n raise GodRuntimeError(\n \"ANCHOR needs the chain's name as a word, \"\n f\"not {self.type_name(name_arg)}.\",\n line,\n )\n chain_name = str(name_arg)\n adapter = self.chain_adapters.get(chain_name)\n if adapter is None:\n known = \", \".join(sorted(self.chain_adapters)) or \"none are bound\"\n raise GodRuntimeError(\n f\"The chain '{chain_name}' is unknown to the heavens. \"\n f\"The known chains are: {known}.\",\n line,\n )\n payload_hash = hashlib.sha256(\n self.stringify(value).encode(\"utf-8\")\n ).hexdigest()\n receipt = adapter.anchor(payload_hash)\n digest = str(receipt.get(\"anchor_hash\", \"\"))[:8]\n print(\n f\"[ANCHOR] Anchored on {adapter.name} · height {receipt.get('height')} \"\n f\"· {digest} ⚓\"\n )\n self._log(f\"ANCHOR :: {adapter.name} height {receipt.get('height')}\")\n return receipt\n\n def _builtin_consult(self, args, line):\n \"\"\"CONSULT(\"question...\") -- ask the local Spirit oracle for counsel.\n\n Returns 2-3 sentences in the voice of the Spirit Engine's prophesy.\n No external calls: the oracle is the local engine, or a gentle\n silence when none is bound.\n \"\"\"\n self._arity(\"CONSULT\", args, 1, line)\n question = args[0]\n if not isinstance(question, str):\n raise GodRuntimeError(\n \"CONSULT needs a question as a word, \"\n f\"not {self.type_name(question)}.\",\n line,\n )\n if self.spirit is None:\n return \"The Spirit is silent on this question. Breathe, and ask again.\"\n return self.spirit.counsel(str(question))\n\n # ------------------------------------------------------- display & typing\n\n def stringify(self, value) -> str:\n \"\"\"Render a God Code value as it appears in REVEAL.\"\"\"\n if value is None:\n return \"void\"\n if isinstance(value, bool):\n return \"true\" if value else \"false\"\n if isinstance(value, Symbol):\n return str(value)\n if isinstance(value, Contract):\n return str(value)\n if isinstance(value, RiteFunction):\n return f\"rite {value.name}\"\n if isinstance(value, list):\n return \"[\" + \", \".join(self.stringify(item) for item in value) + \"]\"\n if isinstance(value, dict):\n # v4.0: maps (e.g. anchor receipts) reveal as {key: value, ...}.\n inner = \", \".join(\n f\"{key}: {self.stringify(item)}\" for key, item in value.items()\n )\n return \"{\" + inner + \"}\"\n if isinstance(value, float) and value.is_integer():\n return str(int(value))\n if isinstance(value, float) and abs(value - round(value)) < 1e-9:\n # Near-integers (e.g. Newton's method settling on 12.00000001)\n # are revealed cleanly; full precision lives on in the value.\n return str(int(round(value)))\n return str(value)\n\n def type_name(self, value) -> str:\n \"\"\"The TYPE() name for a value: number/string/symbol/list/map/contract/rite/boolean/void.\"\"\"\n if isinstance(value, bool):\n return \"boolean\"\n if value is None:\n return \"void\"\n if isinstance(value, Symbol):\n return \"symbol\"\n if isinstance(value, str):\n return \"string\"\n if isinstance(value, (int, float)):\n return \"number\"\n if isinstance(value, list):\n return \"list\"\n if isinstance(value, dict):\n return \"map\" # v4.0\n if isinstance(value, Contract):\n return \"contract\"\n if isinstance(value, RiteFunction):\n return \"rite\"\n return type(value).__name__.lower()\n\n # ------------------------------------------------------------ audit log\n\n @staticmethod\n def _now() -> str:\n return datetime.now(timezone.utc).isoformat()\n\n def _open_log(self) -> None:\n if not self.log_path:\n return\n try:\n path = Path(self.log_path)\n if path.parent != Path(\".\"):\n path.parent.mkdir(parents=True, exist_ok=True)\n self._log_handle = path.open(\"a\", encoding=\"utf-8\")\n except OSError:\n self._log_handle = None\n\n def _close_log(self) -> None:\n handle, self._log_handle = self._log_handle, None\n if handle is not None:\n try:\n handle.close()\n except OSError:\n pass\n\n def _log(self, message: str) -> None:\n if self._log_handle is None:\n return\n try:\n self._log_handle.write(f\"[{self._now()}] {message}\\n\")\n self._log_handle.flush()\n except OSError:\n pass\n\n def _log_statement(self, stmt) -> None:\n kind = type(stmt).__name__\n line = getattr(stmt, \"line\", \"?\")\n summary = self._summarize(stmt)\n self._log(f\"{line} :: {kind} :: {summary}\")\n\n @staticmethod\n def _summarize(stmt) -> str:\n name = getattr(stmt, \"name\", \"\")\n extra = \"\"\n if isinstance(stmt, Declare):\n extra = f\" {stmt.name}\"\n elif isinstance(stmt, DeclareIntent):\n extra = f\" {stmt.rite}\"\n elif isinstance(stmt, (Breathe, Bless, Anoint)):\n extra = f\" {stmt.name}\"\n elif isinstance(stmt, DefineRite):\n extra = f\" {stmt.name}\"\n elif isinstance(stmt, ForLoop):\n extra = f\" {stmt.var}\"\n elif isinstance(stmt, Import):\n extra = f\" {stmt.path}\"\n elif isinstance(stmt, Prophesy):\n text = (stmt.text or \"\")[:40]\n extra = f\" {text!r}\" if text else \"\"\n return f\"{type(stmt).__name__.upper()}{extra}\"\n","godcode/ledger.py":"\"\"\"CovenantLedger -- an append-only, hash-chained record of sealed covenants. 🔒\n\nEach sealed record becomes a block in a JSONL chain file. A block's hash is\nthe sha256 of the canonical JSON of {index, timestamp, record, prev_hash};\nthe genesis block's prev_hash is \"GENESIS\". verify() recomputes every link.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom datetime import datetime, timezone\nfrom pathlib import Path\n\nGENESIS_PREV_HASH = \"GENESIS\"\n\n\ndef _canonical(payload: dict) -> bytes:\n \"\"\"Canonical JSON bytes used for hashing (stable key order, no whitespace).\"\"\"\n return json.dumps(payload, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False).encode(\"utf-8\")\n\n\ndef _block_hash(index: int, timestamp: str, record: dict, prev_hash: str) -> str:\n return hashlib.sha256(\n _canonical(\n {\"index\": index, \"timestamp\": timestamp, \"record\": record, \"prev_hash\": prev_hash}\n )\n ).hexdigest()\n\n\nclass CovenantLedger:\n \"\"\"Append-only covenant chain persisted as JSONL.\"\"\"\n\n def __init__(self, path: str | Path = \"covenant.chain\") -> None:\n self.path = Path(path)\n if str(self.path.parent) not in (\"\", \".\"):\n self.path.parent.mkdir(parents=True, exist_ok=True)\n\n def seal(self, record: dict) -> dict:\n \"\"\"Append a record as a new block; return the block dict.\"\"\"\n blocks = self.read_all()\n index = len(blocks)\n prev_hash = blocks[-1][\"hash\"] if blocks else GENESIS_PREV_HASH\n timestamp = datetime.now(timezone.utc).isoformat()\n block = {\n \"index\": index,\n \"timestamp\": timestamp,\n \"record\": record,\n \"prev_hash\": prev_hash,\n \"hash\": _block_hash(index, timestamp, record, prev_hash),\n }\n with open(self.path, \"a\", encoding=\"utf-8\") as f:\n f.write(json.dumps(block, ensure_ascii=False) + \"\\n\")\n return block\n\n def read_all(self) -> list[dict]:\n \"\"\"Return every block in chain order (empty list if no chain file yet).\"\"\"\n if not self.path.exists():\n return []\n blocks: list[dict] = []\n with open(self.path, encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n if line:\n blocks.append(json.loads(line))\n return blocks\n\n def verify(self) -> tuple[bool, str]:\n \"\"\"Recompute the chain. (True, 'N covenants intact 🔒') or (False, 'chain broken at block K').\"\"\"\n blocks = self.read_all()\n prev_hash = GENESIS_PREV_HASH\n for expected, block in enumerate(blocks):\n index = block.get(\"index\")\n payload_ok = (\n index == expected\n and block.get(\"prev_hash\") == prev_hash\n and _block_hash(\n block.get(\"index\"),\n block.get(\"timestamp\"),\n block.get(\"record\"),\n block.get(\"prev_hash\"),\n )\n == block.get(\"hash\")\n )\n if not payload_ok:\n return False, f\"chain broken at block {index} 🔗💔\"\n prev_hash = block[\"hash\"]\n return True, f\"{len(blocks)} covenants intact 🔒\"\n","godcode/lexer.py":"\"\"\"Lexer for God Code v2.0.\n\n``Lexer(source).lex()`` turns source text into a list of Tokens with\n1-based line/column positions, NEWLINE tokens for each physical line\nbreak, and a final EOF token. ``#`` starts a comment to end of line.\nKeywords are matched case-insensitively (canonical value = UPPER);\nidentifiers preserve their casing.\n\nA scroll may choose another tongue with a pragma comment, e.g.\n``# tongue: tn`` for Setswana (see ``godcode.tongues``). Tongue words map\nonto the same keyword tokens, so the parser never changes; ``Lexer.tongue``\nreports the resolved tongue code (``\"en\"`` when none was chosen).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom .errors import LexerError\nfrom .tokens import Token, TokenType\nfrom .tongues import detect_tongue, resolve as resolve_tongue\n\n# Every alphabetic TokenType name that is not a literal/structural/operator\n# token is a keyword. New keyword TokenTypes are picked up automatically.\n_NON_KEYWORD_NAMES = {\n \"NUMBER\", \"STRING\", \"IDENT\", \"NEWLINE\", \"EOF\",\n \"PLUS\", \"MINUS\", \"STAR\", \"SLASH\", \"PERCENT\",\n \"EQ\", \"NEQ\", \"LT\", \"GT\", \"LTE\", \"GTE\",\n \"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\", \"COMMA\",\n}\nKEYWORDS: dict[str, TokenType] = {\n tt.name: tt for tt in TokenType if tt.name not in _NON_KEYWORD_NAMES\n}\n\n_ESCAPES = {'\"': '\"', \"\\\\\": \"\\\\\", \"n\": \"\\n\", \"t\": \"\\t\"}\n\n_SINGLE_CHAR_TOKENS = {\n \"+\": TokenType.PLUS,\n \"-\": TokenType.MINUS,\n \"*\": TokenType.STAR,\n \"/\": TokenType.SLASH,\n \"%\": TokenType.PERCENT,\n \"=\": TokenType.EQ,\n \"<\": TokenType.LT,\n \">\": TokenType.GT,\n \"(\": TokenType.LPAREN,\n \")\": TokenType.RPAREN,\n \"[\": TokenType.LBRACKET,\n \"]\": TokenType.RBRACKET,\n \",\": TokenType.COMMA,\n}\n\n_MULTI_CHAR_TOKENS = {\n \"!=\": TokenType.NEQ,\n \"<=\": TokenType.LTE,\n \">=\": TokenType.GTE,\n \"==\": TokenType.EQ, # both = and == spell equality\n}\n\n\nclass Lexer:\n def __init__(self, source: str, tongue: str | None = None):\n self.source = source\n # An explicit tongue wins; otherwise the source's own pragma speaks.\n code = tongue if tongue is not None else detect_tongue(source)\n table = resolve_tongue(code)\n self.tongue: str = \"en\" if code is None else code\n self._aliases: dict[str, TokenType] = {\n word: KEYWORDS[canon] for word, canon in table[\"aliases\"].items()\n }\n self._compounds: dict[tuple[str, str], TokenType] = {\n pair: KEYWORDS[canon] for pair, canon in table[\"compounds\"].items()\n }\n\n def lex(self) -> list[Token]:\n src = self.source\n n = len(src)\n tokens: list[Token] = []\n i = 0\n line = 1\n col = 1\n # The previous word token, for two-word closers (FEDISA FA -> ENDIF).\n prev_word = \"\"\n prev_line = 0\n prev_col = 0\n\n def here() -> tuple[int, int]:\n return line, col\n\n while i < n:\n c = src[i]\n\n # whitespace (but not newlines)\n if c == \" \" or c == \"\\t\":\n i += 1\n col += 1\n continue\n\n # line breaks: collapse \\r\\n, tolerate lone \\r\n if c == \"\\r\" or c == \"\\n\":\n ln, cl = here()\n if c == \"\\r\" and i + 1 < n and src[i + 1] == \"\\n\":\n i += 2\n else:\n i += 1\n tokens.append(Token(TokenType.NEWLINE, \"\\n\", ln, cl))\n line += 1\n col = 1\n continue\n\n # comments run to end of line (the newline itself is still lexed)\n if c == \"#\":\n while i < n and src[i] != \"\\n\" and src[i] != \"\\r\":\n i += 1\n continue\n\n # strings\n if c == '\"':\n tok, i, col = self._lex_string(src, i, line, col)\n tokens.append(tok)\n continue\n\n # numbers\n if c.isdigit():\n tok, i, col = self._lex_number(src, i, line, col)\n tokens.append(tok)\n continue\n\n # words: keywords (case-insensitive), tongue words, or identifiers\n if c.isalpha() or c == \"_\":\n start = i\n ln, cl = here()\n while i < n and (src[i].isalnum() or src[i] == \"_\"):\n i += 1\n word = src[start:i]\n col += i - start\n upper = word.upper()\n closer = self._compounds.get((prev_word, upper))\n if (closer is not None and prev_line == ln and tokens\n and (tokens[-1].line, tokens[-1].col) == (prev_line, prev_col)):\n # A two-word phrase on one line, the words side by side:\n # FEDISA FA -> ENDIF, FINISH IF -> ENDIF, Ọ BỤRỤ -> IF.\n # Either word may be a keyword, a tongue word, or a name.\n tokens.pop()\n tokens.append(Token(closer, closer.name, prev_line, prev_col))\n elif upper in KEYWORDS:\n tokens.append(Token(KEYWORDS[upper], upper, ln, cl))\n elif upper in self._aliases:\n tt = self._aliases[upper]\n tokens.append(Token(tt, tt.name, ln, cl))\n else:\n tokens.append(Token(TokenType.IDENT, word, ln, cl))\n prev_word, prev_line, prev_col = upper, ln, cl\n continue\n\n # operators: multi-char first, then single-char\n two = src[i : i + 2]\n if two in _MULTI_CHAR_TOKENS:\n ln, cl = here()\n tokens.append(Token(_MULTI_CHAR_TOKENS[two], two, ln, cl))\n i += 2\n col += 2\n continue\n if c in _SINGLE_CHAR_TOKENS:\n ln, cl = here()\n tokens.append(Token(_SINGLE_CHAR_TOKENS[c], c, ln, cl))\n i += 1\n col += 1\n continue\n\n raise LexerError(\n f\"The heavens do not recognize the character {c!r}; \"\n \"it has no place in the holy tongue\",\n line=line,\n col=col,\n )\n\n tokens.append(Token(TokenType.EOF, \"\", line, col))\n return tokens\n\n # -- helpers -----------------------------------------------------------\n\n @staticmethod\n def _lex_string(src: str, i: int, line: int, col: int):\n \"\"\"Lex a string starting at the opening quote. Returns (token, i, col).\"\"\"\n n = len(src)\n open_line, open_col = line, col\n i += 1 # opening quote\n col += 1\n buf: list[str] = []\n while i < n and src[i] != '\"':\n ch = src[i]\n if ch == \"\\n\" or ch == \"\\r\":\n raise LexerError(\n \"The utterance was never finished: string runs past the \"\n \"end of the line without a closing quote\",\n line=open_line,\n col=open_col,\n )\n if ch == \"\\\\\":\n if i + 1 >= n:\n break\n esc = src[i + 1]\n if esc not in _ESCAPES:\n raise LexerError(\n f\"Unknown escape '\\\\{esc}'; the holy escapes are \"\n '\\\\\\\\ \\\\\" \\\\n \\\\t',\n line=line,\n col=col,\n )\n buf.append(_ESCAPES[esc])\n i += 2\n col += 2\n else:\n buf.append(ch)\n i += 1\n col += 1\n if i >= n:\n raise LexerError(\n \"The utterance was never finished: unterminated string\",\n line=open_line,\n col=open_col,\n )\n i += 1 # closing quote\n col += 1\n return Token(TokenType.STRING, \"\".join(buf), open_line, open_col), i, col\n\n @staticmethod\n def _lex_number(src: str, i: int, line: int, col: int):\n \"\"\"Lex an int or float starting at a digit. Returns (token, i, col).\"\"\"\n n = len(src)\n start = i\n while i < n and src[i].isdigit():\n i += 1\n is_float = False\n if i < n and src[i] == \".\":\n if i + 1 < n and src[i + 1].isdigit():\n is_float = True\n i += 1\n while i < n and src[i].isdigit():\n i += 1\n else:\n raise LexerError(\n f\"Malformed number {src[start:i+1]!r}; a decimal point \"\n \"must be followed by digits\",\n line=line,\n col=col,\n )\n text = src[start:i]\n value: int | float = float(text) if is_float else int(text)\n tok = Token(TokenType.NUMBER, value, line, col)\n return tok, i, col + (i - start)\n","godcode/linter.py":"\"\"\"Static lint pass over the God Code AST (rules GC001-GC006).\n\n``lint_source(source, source_name)`` lexes, parses, and walks a scroll,\nreturning a list of ``Finding`` records. The scope model mirrors the\ninterpreter's real behavior:\n\n- IF and WHILE bodies run in the *current* environment (no new scope).\n- FOR bodies run in one child environment; the loop variable lives there.\n- DEFINE RITE bodies run in a child environment whose parent is the\n closure environment (lexical scope at the point of definition); the\n rite name is bound in the enclosing scope, params in the child.\n- DECLARE binds in the current environment, shadowing any outer binding.\n\nRules (stable ids, plain language):\n- GC001 unused variable: a name DECLAREd (or a FOR loop variable) that is\n never referenced anywhere else. A reference inside a nested rite body\n counts as used, since closures capture; a loop variable used in its\n body counts as used.\n- GC002 undefined name: an Identifier or rite call naming something never\n declared, defined, imported, or provided by a builtin.\n- GC003 shadowing: a DECLARE, rite param, or FOR loop variable that reuses\n a name already visible from an outer scope.\n- GC004 empty block: IF/FOR/WHILE/DEFINE RITE with zero statements in a\n body (both the IF and ELSE bodies are checked).\n- GC005 unreachable code: any statement after RETURN, BREAK, or CONTINUE\n in the same block.\n- GC006 re-DECLARE: the same name DECLAREd twice in the same scope. A\n re-DECLARE whose value uses the old value (the update idiom, e.g.\n DECLARE count AS count + 1) is not flagged, since that is the language's\n only way to update a variable.\n\nUnknown AST node types are traversed generically and never raise.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\nfrom . import ast as A\nfrom .tongues import parse_source\n\n\n# ---------------------------------------------------------------------------\n# public records\n# ---------------------------------------------------------------------------\n\n@dataclass\nclass Finding:\n line: int\n col: int\n rule: str\n message: str\n\n\n# ---------------------------------------------------------------------------\n# scope model\n# ---------------------------------------------------------------------------\n\n# Declaration kinds.\n_DECLARE = \"declare\" # DECLARE name AS ...\n_RITE = \"rite\" # DEFINE RITE name(...)\n_PARAM = \"param\" # rite parameter\n_LOOP = \"loop\" # FOR loop variable\n\n# GC001 tracks these kinds (DECLAREd names and loop variables).\n_GC001_KINDS = (_DECLARE, _LOOP)\n\n\n@dataclass\nclass _Decl:\n name: str\n kind: str\n line: int\n col: int\n used: bool = False\n\n\n@dataclass\nclass _Ref:\n \"\"\"A use of a name. kind \"read\" may raise GC002; kind \"intent\" only\n marks a declaration as used (DECLARE INTENT names a rite's purpose\n without requiring the rite to exist).\"\"\"\n name: str\n line: int\n col: int\n kind: str # \"read\" | \"intent\"\n\n\nclass _Scope:\n def __init__(self, parent: \"_Scope | None\" = None):\n self.parent = parent\n self.decls: dict[str, list[_Decl]] = {}\n self.children: list[_Scope] = []\n\n\ndef _interpreter():\n \"\"\"Build an Interpreter the way the engine builds it, with plugins off\n so the builtin names are deterministic. This is the same source the\n task names for reading ``_builtins`` without duplicating the list.\"\"\"\n from . import plugins\n from .interpreter import Interpreter\n\n os.environ.setdefault(plugins.DISABLE_ENV_VAR, \"1\")\n return Interpreter(spirit=None, ledger=None)\n\n\ndef _builtin_names() -> set[str]:\n \"\"\"Exact builtin names (all UPPER) plus the special ``contract`` name\n the interpreter handles before builtin lookup.\"\"\"\n interp = _interpreter()\n names = set(interp._builtins.keys())\n names.add(\"contract\")\n return names\n\n\n# ---------------------------------------------------------------------------\n# the pass\n# ---------------------------------------------------------------------------\n\nclass _Linter:\n def __init__(self, source_name: str):\n self.source_name = source_name\n self.findings: list[Finding] = []\n self.root = _Scope()\n self.refs: list[tuple[_Scope, _Ref]] = []\n self.builtins = _builtin_names()\n self.interp = _interpreter()\n self.imported_names: set[str] = set()\n self.imports_unknown = False\n self._import_seen: set[str] = set()\n # source_dir mirrors Interpreter.run: the linted file's own dir.\n try:\n if Path(source_name).is_file():\n self.source_dir = Path(source_name).resolve().parent\n else:\n self.source_dir = Path.cwd()\n except (OSError, ValueError):\n self.source_dir = Path.cwd()\n # Import resolution mirrors Interpreter.run: relative to the\n # linted scroll's own directory.\n self.interp.source_dir = self.source_dir\n\n # -- scope helpers ---------------------------------------------------\n\n def _visible_in_outer(self, scope: _Scope, name: str) -> bool:\n env = scope.parent\n while env is not None:\n if name in env.decls:\n return True\n env = env.parent\n return False\n\n def _declare(self, scope: _Scope, name: str, kind: str,\n line: int, col: int, value=None) -> _Decl:\n decl = _Decl(name=name, kind=kind, line=line, col=col)\n bucket = scope.decls.setdefault(name, [])\n if kind == _DECLARE and any(d.kind == _DECLARE for d in bucket):\n # The update idiom (DECLARE x AS ) is the only\n # way to change a variable, so it is not a re-declaration.\n if value is None or not self._expr_mentions(value, name):\n self._finding(line, col, \"GC006\",\n f\"'{name}' is declared more than once in the same scope\")\n elif kind in (_DECLARE, _PARAM, _LOOP) and self._visible_in_outer(scope, name):\n self._finding(line, col, \"GC003\",\n f\"'{name}' shadows a name already visible from an outer scope\")\n bucket.append(decl)\n return decl\n\n def _ref(self, scope: _Scope, name: str, line: int, col: int,\n kind: str = \"read\") -> None:\n self.refs.append((scope, _Ref(name=name, line=line, col=col, kind=kind)))\n\n def _finding(self, line: int, col: int, rule: str, message: str) -> None:\n self.findings.append(Finding(line=line, col=col, rule=rule,\n message=message))\n\n # -- driver ----------------------------------------------------------\n\n def lint(self, program) -> list[Finding]:\n self._walk_block(program.statements, self.root)\n self._resolve_imports(program)\n self._resolve_refs()\n self._check_unused(self.root)\n self.findings.sort(key=lambda f: (f.line, f.col, f.rule))\n return self.findings\n\n # -- statement walking -----------------------------------------------\n\n def _walk_block(self, stmts: list, scope: _Scope) -> None:\n terminated_by = None # the word that ended this block's flow\n for stmt in stmts:\n if terminated_by is not None:\n self._finding(getattr(stmt, \"line\", 1), getattr(stmt, \"col\", 1),\n \"GC005\",\n f\"unreachable code after {terminated_by}\")\n kind = type(stmt).__name__\n if kind in (\"Return\", \"Break\", \"Continue\"):\n terminated_by = {\"Return\": \"RETURN\", \"Break\": \"BREAK\",\n \"Continue\": \"CONTINUE\"}[kind]\n self._walk_stmt(stmt, scope)\n\n def _walk_stmt(self, stmt, scope: _Scope) -> None:\n kind = type(stmt).__name__\n meth = getattr(self, \"_stmt_\" + kind, None)\n if meth is not None:\n meth(stmt, scope)\n return\n # Unknown node: walk any statement lists and expressions it holds,\n # in the current scope. Never raise.\n self._walk_unknown(stmt, scope)\n\n def _walk_unknown(self, node, scope: _Scope) -> None:\n try:\n fields = vars(node)\n except TypeError:\n return\n for value in fields.values():\n if isinstance(value, str):\n continue\n if isinstance(value, list):\n for item in value:\n if self._looks_like_stmt(item):\n self._walk_stmt(item, scope)\n elif self._looks_like_expr(item):\n self._walk_expr(item, scope)\n elif isinstance(item, list):\n for sub in item:\n if self._looks_like_stmt(sub):\n self._walk_stmt(sub, scope)\n elif self._looks_like_expr(sub):\n self._walk_expr(sub, scope)\n elif self._looks_like_stmt(value):\n self._walk_stmt(value, scope)\n elif self._looks_like_expr(value):\n self._walk_expr(value, scope)\n\n @staticmethod\n def _looks_like_stmt(node) -> bool:\n return hasattr(node, \"line\") and hasattr(node, \"col\") and not isinstance(\n node, (str, bytes, int, float, bool, type(None)))\n\n @staticmethod\n def _looks_like_expr(node) -> bool:\n return _Linter._looks_like_stmt(node)\n\n # -- known statements ------------------------------------------------\n\n def _stmt_Program(self, node, scope: _Scope) -> None:\n self._walk_block(node.statements, scope)\n\n def _stmt_CreationBlock(self, node, scope: _Scope) -> None:\n # The creation block runs in the same environment: no new scope.\n self._walk_block(node.statements, scope)\n\n def _stmt_Declare(self, node, scope: _Scope) -> None:\n # The value is breathed in the enclosing scope, before the name\n # itself is bound (mirrors env.define(name, eval(value, env))).\n self._walk_expr(node.value, scope)\n self._declare(scope, node.name, _DECLARE, node.line, node.col,\n value=node.value)\n\n def _expr_mentions(self, expr, name: str) -> bool:\n \"\"\"True when the expression reads the given name anywhere inside.\"\"\"\n if expr is None or isinstance(expr, str):\n return False\n kind = type(expr).__name__\n if kind == \"Identifier\":\n return expr.name == name\n if kind == \"CallExpr\":\n return expr.callee == name or any(\n self._expr_mentions(a, name) for a in expr.args)\n if kind == \"BinaryOp\":\n return (self._expr_mentions(expr.left, name)\n or self._expr_mentions(expr.right, name))\n if kind == \"UnaryOp\":\n return self._expr_mentions(expr.operand, name)\n if kind == \"InterpolatedString\":\n return any(not isinstance(p, str) and self._expr_mentions(p, name)\n for p in expr.parts)\n if kind == \"ListLiteral\":\n return any(self._expr_mentions(i, name) for i in expr.items)\n if kind == \"Index\":\n return (self._expr_mentions(expr.obj, name)\n or self._expr_mentions(expr.index, name))\n # Unknown node types: walk their fields generically.\n try:\n fields = vars(expr)\n except TypeError:\n return False\n for v in fields.values():\n if isinstance(v, list):\n if any(self._expr_mentions(i, name) for i in v):\n return True\n elif self._expr_mentions(v, name):\n return True\n return False\n\n def _stmt_DeclareIntent(self, node, scope: _Scope) -> None:\n # Names a rite's purpose; marks the rite used but never flags GC002.\n self._ref(scope, node.rite, node.line, node.col, kind=\"intent\")\n\n def _stmt_DeclarePermission(self, node, scope: _Scope) -> None: # noqa: ARG002\n # A permission manifest declares powers, not names; nothing to lint.\n pass\n\n def _stmt_Breathe(self, node, scope: _Scope) -> None:\n self._ref(scope, node.name, node.line, node.col)\n\n def _stmt_Reveal(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_Prophesy(self, node, scope: _Scope) -> None: # noqa: ARG002\n return\n\n def _stmt_Ascend(self, node, scope: _Scope) -> None: # noqa: ARG002\n return\n\n def _stmt_Reflect(self, node, scope: _Scope) -> None: # noqa: ARG002\n return\n\n def _stmt_Bless(self, node, scope: _Scope) -> None:\n self._ref(scope, node.name, node.line, node.col)\n\n def _stmt_Anoint(self, node, scope: _Scope) -> None:\n self._ref(scope, node.name, node.line, node.col)\n\n def _stmt_SealStmt(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_Testify(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_IfStmt(self, node, scope: _Scope) -> None:\n self._walk_expr(node.cond, scope)\n # IF bodies run in the current environment: no new scope.\n if not node.then_body:\n self._finding(node.line, node.col, \"GC004\", \"empty IF body\")\n self._walk_block(node.then_body, scope)\n if node.has_else and not node.else_body:\n self._finding(node.line, node.col, \"GC004\", \"empty ELSE body\")\n self._walk_block(node.else_body, scope)\n\n def _stmt_ForLoop(self, node, scope: _Scope) -> None:\n # The iterable is breathed in the enclosing scope; the body runs in\n # one child environment holding the loop variable.\n self._walk_expr(node.iterable, scope)\n child = _Scope(parent=scope)\n scope.children.append(child)\n self._declare(child, node.var, _LOOP, node.line, node.col)\n if not node.body:\n self._finding(node.line, node.col, \"GC004\", \"empty FOR body\")\n self._walk_block(node.body, child)\n\n def _stmt_WhileLoop(self, node, scope: _Scope) -> None:\n self._walk_expr(node.cond, scope)\n # The body runs in the current environment: no new scope.\n if not node.body:\n self._finding(node.line, node.col, \"GC004\", \"empty WHILE body\")\n self._walk_block(node.body, scope)\n\n def _stmt_TryStmt(self, node, scope: _Scope) -> None:\n # TRY/CATCH bodies run in the current environment: no new scope.\n # The CATCH's error name is an implicit binding, marked used so a\n # CATCH that never reads it is not flagged as an unused variable.\n if not node.try_body:\n self._finding(node.line, node.col, \"GC004\", \"empty TRY body\")\n self._walk_block(node.try_body, scope)\n decl = self._declare(scope, node.error_name, _DECLARE,\n node.line, node.col)\n decl.used = True\n if not node.catch_body:\n self._finding(node.line, node.col, \"GC004\", \"empty CATCH body\")\n self._walk_block(node.catch_body, scope)\n\n def _stmt_DefineRite(self, node, scope: _Scope) -> None:\n # The rite name is bound in the enclosing scope (so rites may call\n # themselves); the body runs in a child environment whose parent is\n # the lexical closure, holding the params.\n self._declare(scope, node.name, _RITE, node.line, node.col)\n child = _Scope(parent=scope)\n scope.children.append(child)\n for param in node.params:\n self._declare(child, param, _PARAM, node.line, node.col)\n if not node.body:\n self._finding(node.line, node.col, \"GC004\",\n f\"empty rite body for '{node.name}'\")\n self._walk_block(node.body, child)\n\n def _stmt_Return(self, node, scope: _Scope) -> None:\n if node.expr is not None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_Break(self, node, scope: _Scope) -> None: # noqa: ARG002\n # No names are read or bound; control passes to the enclosing loop.\n return\n\n def _stmt_Continue(self, node, scope: _Scope) -> None: # noqa: ARG002\n # No names are read or bound; control passes to the enclosing loop.\n return\n\n def _stmt_Import(self, node, scope: _Scope) -> None: # noqa: ARG002\n # Imports are resolved after the walk (see _resolve_imports).\n return\n\n def _stmt_ExprStmt(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n # -- expression walking ----------------------------------------------\n\n def _walk_expr(self, expr, scope: _Scope) -> None:\n if expr is None:\n return\n kind = type(expr).__name__\n if kind == \"Identifier\":\n self._ref(scope, expr.name, expr.line, expr.col)\n elif kind == \"CallExpr\":\n self._ref(scope, expr.callee, expr.line, expr.col)\n for arg in expr.args:\n self._walk_expr(arg, scope)\n elif kind == \"BinaryOp\":\n self._walk_expr(expr.left, scope)\n self._walk_expr(expr.right, scope)\n elif kind == \"UnaryOp\":\n self._walk_expr(expr.operand, scope)\n elif kind == \"Literal\":\n return\n elif kind == \"InterpolatedString\":\n for part in expr.parts:\n if isinstance(part, str):\n continue\n self._walk_expr(part, scope)\n elif kind == \"ListLiteral\":\n for item in expr.items:\n self._walk_expr(item, scope)\n elif kind == \"Index\":\n self._walk_expr(expr.obj, scope)\n self._walk_expr(expr.index, scope)\n else:\n # Unknown expression: walk any nested nodes generically.\n self._walk_unknown(expr, scope)\n\n # -- imports ----------------------------------------------------------\n\n def _collect_imports(self, node) -> list:\n \"\"\"Every Import statement in the tree, in source order.\"\"\"\n found: list = []\n\n def visit(n):\n if n is None or isinstance(n, str):\n return\n if type(n).__name__ == \"Import\":\n found.append(n)\n return\n try:\n fields = vars(n)\n except TypeError:\n return\n for value in fields.values():\n if isinstance(value, list):\n for item in value:\n visit(item)\n else:\n visit(value)\n\n visit(node)\n return found\n\n def _resolve_imports(self, program) -> None:\n for stmt in self._collect_imports(program):\n path = self._resolve_one_import(stmt.path)\n if path is None:\n # Cannot resolve: skip GC002 for names rather than guessing.\n self.imports_unknown = True\n continue\n self._harvest_import(path)\n\n def _resolve_one_import(self, import_path: str) -> \"Path | None\":\n \"\"\"Resolve the way Interpreter._resolve_import does.\"\"\"\n try:\n return self.interp._resolve_import(import_path, None)\n except Exception:\n return None\n\n def _harvest_import(self, path: Path) -> None:\n \"\"\"Harvest top-level (importer-visible) rite and DECLAREd names from\n an imported scroll: names bound in its root scope, since the\n interpreter runs imports in the importer's own environment.\"\"\"\n key = str(path)\n if key in self._import_seen:\n return\n self._import_seen.add(key)\n try:\n source = path.read_text(encoding=\"utf-8\")\n program = parse_source(source)\n except Exception:\n self.imports_unknown = True\n return\n saved_root = self.root\n saved_refs = self.refs\n saved_findings = self.findings\n try:\n self.root = _Scope()\n self.refs = []\n self.findings = []\n self._walk_block(program.statements, self.root)\n for name, bucket in self.root.decls.items():\n if any(d.kind in (_DECLARE, _RITE) for d in bucket):\n self.imported_names.add(name)\n # Recurse into the import's own imports, guarded by _import_seen.\n self._resolve_imports(program)\n finally:\n self.root = saved_root\n self.refs = saved_refs\n self.findings = saved_findings\n\n # -- reference resolution ---------------------------------------------\n\n def _resolve_refs(self) -> None:\n for scope, ref in self.refs:\n bucket = self._resolve(scope, ref.name)\n if bucket is not None:\n # Mark every declaration in the bucket used: a re-declared\n # name's value reads the older binding (DECLARE x AS x + 1),\n # so all of them take part in the program's life.\n for decl in bucket:\n decl.used = True\n continue\n if ref.kind != \"read\":\n continue\n if ref.name in self.imported_names:\n continue\n if ref.name.upper() in self.builtins or ref.name in self.builtins:\n continue\n if self.imports_unknown:\n continue\n self._finding(ref.line, ref.col, \"GC002\",\n f\"undefined name '{ref.name}'\")\n\n @staticmethod\n def _resolve(scope: _Scope, name: str) -> \"list | None\":\n env: \"_Scope | None\" = scope\n while env is not None:\n bucket = env.decls.get(name)\n if bucket:\n # The runtime's env.define overwrites, so the last\n # declaration in the innermost scope is the live one.\n return bucket\n env = env.parent\n return None\n\n # -- GC001 -------------------------------------------------------------\n\n def _check_unused(self, scope: _Scope) -> None:\n for bucket in scope.decls.values():\n for decl in bucket:\n if decl.kind in _GC001_KINDS and not decl.used:\n self._finding(decl.line, decl.col, \"GC001\",\n f\"unused variable '{decl.name}'\")\n for child in scope.children:\n self._check_unused(child)\n\n\n# ---------------------------------------------------------------------------\n# public entry point\n# ---------------------------------------------------------------------------\n\ndef lint_source(source: str, source_name: str = \"\") -> list[Finding]:\n \"\"\"Lex, parse, and lint a God Code scroll.\n\n Raises the usual lexer/parser errors on bad source, so callers can\n report them the way ``godcode check`` does.\n \"\"\"\n program = parse_source(source)\n return _Linter(source_name).lint(program)\n\n\n__all__ = [\"Finding\", \"lint_source\"]\n","godcode/lsp.py":"\"\"\"Language server for God Code (v3.0, Pillar 4).\n\nA minimal Language Server Protocol implementation over stdio, hand-rolled\non top of the stdlib. No third-party dependencies. JSON-RPC 2.0 messages\nare framed with ``Content-Length`` headers, per the LSP base protocol.\n\nLifecycle::\n\n godcode lsp # start serving on stdin/stdout\n\nDiagnostics are produced by the real lexer/parser pipeline (the same\nlogic ``godcode check`` uses): opening or changing a ``.god`` scroll\nre-parses it and publishes the divine errors as LSP diagnostics.\n\nProtocol notes:\n * All logging goes to stderr. stdout is the protocol channel. Nothing\n else may ever be written there.\n * Unknown methods answer with JSON-RPC error -32601 (\"Method not found\").\n * Malformed frames are skipped; the server keeps serving.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport re\nimport sys\n\nfrom godcode import __version__ as ENGINE_VERSION\n\n# ---------------------------------------------------------------------------\n# Divine documentation table (hover + completion)\n# ---------------------------------------------------------------------------\n\nLSP_DOCS: dict[str, str] = {\n # -- block sentinels -------------------------------------------------\n \"BEGIN CREATION\": (\n \"**BEGIN CREATION**\\n\\n\"\n \"Speak, and let there be a program. Every scroll opens its works \"\n \"with `BEGIN CREATION` and closes them with `END CREATION`.\\n\\n\"\n \"```godcode\\nBEGIN CREATION\\n REVEAL(\\\"Let there be light\\\")\\n\"\n \" ASCEND\\nEND CREATION\\n```\"\n ),\n \"END CREATION\": (\n \"**END CREATION**\\n\\n\"\n \"The seal upon the scroll. It closes what `BEGIN CREATION` opened. \"\n \"No works may follow it.\\n\\n\"\n \"```godcode\\nEND CREATION\\n```\"\n ),\n \"DEFINE RITE\": (\n \"**DEFINE RITE**\\n\\n\"\n \"Establish a rite. A named ceremony of statements that may be \"\n \"invoked again and again. Closed with `END RITE`; a rite may \"\n \"`RETURN` a value to its caller.\\n\\n\"\n \"```godcode\\nDEFINE RITE bless(name)\\n\"\n \" REVEAL(\\\"Blessed be \\\" + name)\\nEND RITE\\n```\"\n ),\n \"END RITE\": (\n \"**END RITE**\\n\\n\"\n \"The closing of a rite begun with `DEFINE RITE`. All ceremonies \"\n \"must be sealed.\\n\\n\"\n \"```godcode\\nEND RITE\\n```\"\n ),\n \"BREATHE LIFE INTO\": (\n \"**BREATHE LIFE INTO**\\n\\n\"\n \"Awaken a declared vessel so it may be used. A name must be \"\n \"`DECLARE`d before the breath is given.\\n\\n\"\n \"```godcode\\nDECLARE vessel AS 0\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n # -- keywords --------------------------------------------------------\n \"BEGIN\": (\n \"**BEGIN**\\n\\n\"\n \"The opening word of creation. Always paired with `CREATION`. \"\n \"See `BEGIN CREATION`.\\n\\n```godcode\\nBEGIN CREATION\\n```\"\n ),\n \"CREATION\": (\n \"**CREATION**\\n\\n\"\n \"The body of all works. Paired with `BEGIN` to open a scroll and \"\n \"with `END` to close it. See `BEGIN CREATION`.\\n\\n\"\n \"```godcode\\nBEGIN CREATION\\n ASCEND\\nEND CREATION\\n```\"\n ),\n \"DECLARE\": (\n \"**DECLARE**\\n\\n\"\n \"Bring a name into being and bind it to a value. \"\n \"Every vessel must be declared before the breath is given.\\n\\n\"\n \"```godcode\\nDECLARE tribes AS 12\\n```\"\n ),\n \"AS\": (\n \"**AS**\\n\\n\"\n \"The binding word. It joins a declared name to its value, as \"\n \"in `DECLARE x AS 1`.\\n\\n```godcode\\nDECLARE x AS 1\\n```\"\n ),\n \"IF\": (\n \"**IF**\\n\\n\"\n \"Weigh a condition; if it holds true, the words between `THEN` \"\n \"and `ENDIF` come to pass.\\n\\n\"\n \"```godcode\\nIF faith > fear THEN\\n REVEAL(\\\"walk on\\\")\\nENDIF\\n```\"\n ),\n \"THEN\": (\n \"**THEN**\\n\\n\"\n \"Marks the start of the true branch after an `IF` condition. \"\n \"Closed by `ENDIF` (or `ELSE`).\\n\\n```godcode\\nIF x THEN\\n REVEAL(x)\\n\"\n \"ENDIF\\n```\"\n ),\n \"ELSE\": (\n \"**ELSE**\\n\\n\"\n \"The other path. When the `IF` condition proves false, these \"\n \"words come to pass instead.\\n\\n\"\n \"```godcode\\nIF x THEN\\n REVEAL(\\\"yes\\\")\\nELSE\\n\"\n \" REVEAL(\\\"no\\\")\\nENDIF\\n```\"\n ),\n \"ENDIF\": (\n \"**ENDIF**\\n\\n\"\n \"The seal upon an `IF` weighing. Every `IF` must be closed.\\n\\n\"\n \"```godcode\\nENDIF\\n```\"\n ),\n \"FOR\": (\n \"**FOR**\\n\\n\"\n \"Walk through every member of a list or range, naming each one \"\n \"in turn, until `ENDFOR`.\\n\\n\"\n \"```godcode\\nFOR tribe IN RANGE(12)\\n REVEAL(tribe)\\nENDFOR\\n```\"\n ),\n \"IN\": (\n \"**IN**\\n\\n\"\n \"The walking word. `FOR name IN list` binds each member in turn.\\n\\n\"\n \"```godcode\\nFOR star IN heavens\\n REVEAL(star)\\nENDFOR\\n```\"\n ),\n \"ENDFOR\": (\n \"**ENDFOR**\\n\\n\"\n \"The seal upon a `FOR` walk. Every journey must end.\\n\\n\"\n \"```godcode\\nENDFOR\\n```\"\n ),\n \"WHILE\": (\n \"**WHILE**\\n\\n\"\n \"Repeat the works between `DO` and `ENDWHILE` for as long as the \"\n \"condition holds true.\\n\\n\"\n \"```godcode\\nWHILE night < dawn DO\\n REVEAL(\\\"watch\\\")\\nENDWHILE\\n```\"\n ),\n \"DO\": (\n \"**DO**\\n\\n\"\n \"Marks the start of the repeated works in a `WHILE` loop.\\n\\n\"\n \"```godcode\\nWHILE x DO\\n REVEAL(x)\\nENDWHILE\\n```\"\n ),\n \"ENDWHILE\": (\n \"**ENDWHILE**\\n\\n\"\n \"The seal upon a `WHILE` vigil.\\n\\n```godcode\\nENDWHILE\\n```\"\n ),\n \"BREAK\": (\n \"**BREAK**\\n\\n\"\n \"Release the innermost enclosing `FOR` or `WHILE` loop at once. \"\n \"It can only be spoken within a loop.\\n\\n\"\n \"```godcode\\nFOR star IN heavens\\n IF star IS dim THEN\\n BREAK\\n ENDIF\\nENDFOR\\n```\"\n ),\n \"CONTINUE\": (\n \"**CONTINUE**\\n\\n\"\n \"Skip to the next turn of the innermost enclosing `FOR` or \"\n \"`WHILE` loop. It can only be spoken within a loop.\\n\\n\"\n \"```godcode\\nFOR n IN RANGE(10)\\n IF n % 2 IS 0 THEN\\n CONTINUE\\n ENDIF\\n REVEAL(n)\\nENDFOR\\n```\"\n ),\n \"TRY\": (\n \"**TRY**\\n\\n\"\n \"Open a sheltered work: if a runtime error rises inside, the \"\n \"`CATCH` block runs with the message bound to `ERROR` (or a name \"\n \"of your choosing). `RETURN` and `ASCEND` are never \"\n \"caught.\\n\\n```godcode\\nTRY\\n REVEAL(fragile_work())\\nCATCH\\n\"\n \" REVEAL(\\\"caught: {ERROR}\\\")\\nENDTRY\\n```\"\n ),\n \"CATCH\": (\n \"**CATCH**\\n\\n\"\n \"The refuge of a `TRY` block. Alone it binds the error's message \"\n \"to `ERROR`; `CATCH name` binds it to `name` instead.\\n\\n\"\n \"```godcode\\nCATCH trouble\\n REVEAL(trouble)\\n```\"\n ),\n \"ENDTRY\": (\n \"**ENDTRY**\\n\\n\"\n \"The seal upon a `TRY` … `CATCH` shelter.\\n\\n```godcode\\nENDTRY\\n```\"\n ),\n \"DEFINE\": (\n \"**DEFINE**\\n\\n\"\n \"The first word of a rite's establishment. Always paired with \"\n \"`RITE`. See `DEFINE RITE`.\\n\\n```godcode\\nDEFINE RITE bless()\\n\"\n \"END RITE\\n```\"\n ),\n \"RITE\": (\n \"**RITE**\\n\\n\"\n \"A named ceremony of statements. Paired with `DEFINE` to open \"\n \"and `END` to close. See `DEFINE RITE`.\\n\\n\"\n \"```godcode\\nDEFINE RITE bless()\\nEND RITE\\n```\"\n ),\n \"INVOKE\": (\n \"**INVOKE**\\n\\n\"\n \"Call a rite by name, offering it arguments in the ancient manner.\\n\\n\"\n \"```godcode\\nINVOKE bless(\\\"the meek\\\")\\n```\"\n ),\n \"RETURN\": (\n \"**RETURN**\\n\\n\"\n \"Offer a value back from a rite to the one who invoked it. \"\n \"A rite without `RETURN` yields the void.\\n\\n\"\n \"```godcode\\nRETURN manna * 2\\n```\"\n ),\n \"IMPORT\": (\n \"**IMPORT**\\n\\n\"\n \"Bring another scroll into this creation, that its works may \"\n \"serve here.\\n\\n```godcode\\nIMPORT \\\"psalms.god\\\"\\n```\"\n ),\n \"REVEAL\": (\n \"**REVEAL**\\n\\n\"\n \"Speak a value aloud. The scroll's voice, printing to the world \"\n \"beyond.\\n\\n```godcode\\nREVEAL(\\\"The heavens declare\\\")\\n```\"\n ),\n \"BREATHE\": (\n \"**BREATHE**\\n\\n\"\n \"The first word of awakening. Always `BREATHE LIFE INTO name`. \"\n \"See `BREATHE LIFE INTO`.\\n\\n\"\n \"```godcode\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n \"LIFE\": (\n \"**LIFE**\\n\\n\"\n \"The middle word of `BREATHE LIFE INTO`. The breath itself.\\n\\n\"\n \"```godcode\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n \"INTO\": (\n \"**INTO**\\n\\n\"\n \"The directing word of `BREATHE LIFE INTO name`.\\n\\n\"\n \"```godcode\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n \"PROPHESY\": (\n \"**PROPHESY**\\n\\n\"\n \"Utter a fixed word into the scroll. A literal prophecy of text.\\n\\n\"\n \"```godcode\\nPROPHESY \\\"and it was good\\\"\\n```\"\n ),\n \"ASCEND\": (\n \"**ASCEND**\\n\\n\"\n \"End the run in peace. Nothing after `ASCEND` shall come to pass.\\n\\n\"\n \"```godcode\\nASCEND\\n```\"\n ),\n \"SEAL\": (\n \"**SEAL**\\n\\n\"\n \"Set a value under seal. It is recorded in the covenant ledger \"\n \"and may not be altered thereafter.\\n\\n```godcode\\nSEAL covenant\\n```\"\n ),\n # --- v4.0 ---\n \"ANCHOR\": (\n \"**ANCHOR**\\n\\n\"\n \"Anchor a value's hash on a chain: `ANCHOR(expr)` returns a receipt \"\n \"map `{chain, anchor_hash, height, timestamp, payload_hash}`. \"\n \"The default chain is `simulated` (a local tamper-evident chain); \"\n \"a second argument names another registered chain.\\n\\n\"\n \"```godcode\\nDECLARE seal AS ANCHOR(covenant)\\n```\"\n ),\n \"CONSULT\": (\n \"**CONSULT**\\n\\n\"\n \"Ask the local Spirit oracle a question; it answers with two to \"\n \"three sentences of counsel. No external calls.\\n\\n\"\n \"```godcode\\nREVEAL(CONSULT(\\\"How should I structure this covenant?\\\"))\\n```\"\n ),\n \"INTENT\": (\n \"**INTENT**\\n\\n\"\n \"The naming word of `DECLARE INTENT \\\"words...\\\" ON rite_name`. \"\n \"it registers a natural-language intent on a rite. When the rite \"\n \"is invoked, the Spirit discerns whether its words still walk in \"\n \"the declared intent, and counsels gently on drift.\\n\\n\"\n \"```godcode\\nDECLARE INTENT \\\"bring peace\\\" ON evening_blessing\\n```\"\n ),\n # --- end v4.0 ---\n \"TESTIFY\": (\n \"**TESTIFY**\\n\\n\"\n \"Bear witness to a value. Affirm it before the heavens.\\n\\n\"\n \"```godcode\\nTESTIFY manna > 0\\n```\"\n ),\n \"BLESS\": (\n \"**BLESS**\\n\\n\"\n \"Confer blessing upon a name, marking it favored.\\n\\n\"\n \"```godcode\\nBLESS the_meek\\n```\"\n ),\n \"ANOINT\": (\n \"**ANOINT**\\n\\n\"\n \"Anoint a name for a holy purpose, setting it apart.\\n\\n\"\n \"```godcode\\nANOINT the_chosen\\n```\"\n ),\n \"REFLECT\": (\n \"**REFLECT**\\n\\n\"\n \"Pause and contemplate. A still point in the works.\\n\\n\"\n \"```godcode\\nREFLECT\\n```\"\n ),\n \"AND\": (\n \"**AND**\\n\\n\"\n \"Join two truths; the whole holds only if both hold.\\n\\n\"\n \"```godcode\\nIF faith AND works THEN\\n```\"\n ),\n \"OR\": (\n \"**OR**\\n\\n\"\n \"Offer two truths; the whole holds if either holds.\\n\\n\"\n \"```godcode\\nIF mercy OR grace THEN\\n```\"\n ),\n \"NOT\": (\n \"**NOT**\\n\\n\"\n \"Turn a truth upon its head.\\n\\n```godcode\\nIF NOT fear THEN\\n```\"\n ),\n \"TRUE\": (\n \"**TRUE**\\n\\n\"\n \"The eternal yes.\\n\\n```godcode\\nDECLARE amen AS true\\n```\"\n ),\n \"FALSE\": (\n \"**FALSE**\\n\\n\"\n \"The eternal no.\\n\\n```godcode\\nDECLARE doubt AS false\\n```\"\n ),\n \"VOID\": (\n \"**VOID**\\n\\n\"\n \"The absence of all things. What a rite yields when it returns \"\n \"nothing.\\n\\n```godcode\\nDECLARE emptiness AS void\\n```\"\n ),\n \"IS\": (\n \"**IS**\\n\\n\"\n \"The weighing word. Reserved for divine comparisons.\\n\\n\"\n \"```godcode\\n# reserved\\n```\"\n ),\n \"END\": (\n \"**END**\\n\\n\"\n \"The closing word. Paired with `CREATION` or `RITE` to seal a \"\n \"block.\\n\\n```godcode\\nEND CREATION\\n```\"\n ),\n # -- built-ins -------------------------------------------------------\n \"LEN\": (\n \"**LEN**(value)\\n\\n\"\n \"Measure the length of a string or a list, and the number shall \"\n \"be revealed.\\n\\n```godcode\\nREVEAL(LEN(\\\"firmament\\\"))\\n```\"\n ),\n \"STR\": (\n \"**STR**(value)\\n\\n\"\n \"Turn anything into its spoken form. A string.\\n\\n\"\n \"```godcode\\nREVEAL(STR(40) + \\\" days\\\")\\n```\"\n ),\n \"NUM\": (\n \"**NUM**(value)\\n\\n\"\n \"Turn a string into a number, that it may be weighed and counted.\\n\\n\"\n \"```godcode\\nDECLARE years AS NUM(\\\"40\\\")\\n```\"\n ),\n \"TYPE\": (\n \"**TYPE**(value)\\n\\n\"\n \"Discern the kind of a thing. Its type, named aloud.\\n\\n\"\n \"```godcode\\nREVEAL(TYPE(manna))\\n```\"\n ),\n \"RANDOM\": (\n \"**RANDOM**(bound)\\n\\n\"\n \"Cast lots. Draw a whole number from 0 up to (but not including) \"\n \"`bound`.\\n\\n```godcode\\nDECLARE lot AS RANDOM(12)\\n```\"\n ),\n \"RANGE\": (\n \"**RANGE**(stop) / **RANGE**(start, stop)\\n\\n\"\n \"Number the days. Produce the sequence of whole numbers from \"\n \"0 (or `start`) up to `stop`.\\n\\n```godcode\\n\"\n \"FOR day IN RANGE(7)\\n REVEAL(day)\\nENDFOR\\n```\"\n ),\n \"PUSH\": (\n \"**PUSH**(list, value)\\n\\n\"\n \"Add to the multitude. Append `value` to the end of `list`.\\n\\n\"\n \"```godcode\\nPUSH(tribes, \\\"Benjamin\\\")\\n```\"\n ),\n \"UPPER\": (\n \"**UPPER**(text)\\n\\n\"\n \"Lift every letter to the heavens. Uppercase the string.\\n\\n\"\n \"```godcode\\nREVEAL(UPPER(\\\"hosanna\\\"))\\n```\"\n ),\n \"LOWER\": (\n \"**LOWER**(text)\\n\\n\"\n \"Humble every letter. Lowercase the string.\\n\\n\"\n \"```godcode\\nREVEAL(LOWER(\\\"HOSANNA\\\"))\\n```\"\n ),\n \"SPLIT\": (\n \"**SPLIT**(text, separator)\\n\\n\"\n \"Divide the word. Split `text` into a list at each `separator`.\\n\\n\"\n \"```godcode\\nDECLARE words AS SPLIT(\\\"loaves fishes\\\", \\\" \\\")\\n```\"\n ),\n \"JOIN\": (\n \"**JOIN**(list, separator)\\n\\n\"\n \"Gather the scattered. Join a list of strings with `separator`.\\n\\n\"\n \"```godcode\\nREVEAL(JOIN(words, \\\" \\\"))\\n```\"\n ),\n \"ASK\": (\n \"**ASK**([prompt])\\n\\n\"\n \"Seek counsel. Read a line from the one who runs the scroll.\\n\\n\"\n \"```godcode\\nDECLARE name AS ASK(\\\"What is your name? \\\")\\n```\"\n ),\n \"BEHOLD\": (\n \"**BEHOLD**()\\n\\n\"\n \"Mark the present hour. The current time, in the heavens' own \"\n \"notation.\\n\\n```godcode\\nREVEAL(BEHOLD())\\n```\"\n ),\n \"REVERSE\": (\n \"**REVERSE**(value)\\n\\n\"\n \"Turn it back upon itself. Reverse a string or a list.\\n\\n\"\n \"```godcode\\nREVEAL(REVERSE(\\\"stressed\\\"))\\n```\"\n ),\n \"SHA256\": (\n \"**SHA256**(value)\\n\\n\"\n \"Take a word's fingerprint. The SHA-256 digest as 64 hex \"\n \"characters. The same word always gives the same fingerprint.\\n\\n\"\n \"```godcode\\nREVEAL(SHA256(\\\"manna\\\"))\\n```\"\n ),\n \"HMAC\": (\n \"**HMAC**(key, message)\\n\\n\"\n \"Seal a message under a key. The HMAC-SHA-256 signature as 64 \"\n \"hex characters. Only a keeper of the key can make or verify \"\n \"the seal.\\n\\n\"\n \"```godcode\\nDECLARE sig AS HMAC(\\\"secret\\\", \\\"the covenant stands\\\")\\n```\"\n ),\n \"BASE64_ENCODE\": (\n \"**BASE64_ENCODE**(value)\\n\\n\"\n \"Veil a word in base64. The veiled text as a plain word.\\n\\n\"\n \"```godcode\\nREVEAL(BASE64_ENCODE(\\\"grace\\\"))\\n```\"\n ),\n \"BASE64_DECODE\": (\n \"**BASE64_DECODE**(text)\\n\\n\"\n \"Lift a base64 veil. The plain word behind it. A gentle error \"\n \"if the veil is ill-formed.\\n\\n\"\n \"```godcode\\nREVEAL(BASE64_DECODE(BASE64_ENCODE(\\\"grace\\\")))\\n```\"\n ),\n \"TRIM\": (\n \"**TRIM**(value)\\n\\n\"\n \"Lift away leading and trailing whitespace. The trimmed word.\\n\\n\"\n \"```godcode\\nREVEAL(TRIM(\\\" grace \\\"))\\n```\"\n ),\n \"REPLACE\": (\n \"**REPLACE**(word, old, new)\\n\\n\"\n \"Turn every occurrence of `old` into `new`. The renewed word.\\n\\n\"\n \"```godcode\\nREVEAL(REPLACE(\\\"manna, manna\\\", \\\"manna\\\", \\\"bread\\\"))\\n```\"\n ),\n \"STARTS_WITH\": (\n \"**STARTS_WITH**(word, part)\\n\\n\"\n \"Ask whether the word opens with the part. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(STARTS_WITH(\\\"dawn\\\", \\\"da\\\"))\\n```\"\n ),\n \"ENDS_WITH\": (\n \"**ENDS_WITH**(word, part)\\n\\n\"\n \"Ask whether the word closes with the part. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(ENDS_WITH(\\\"dawn\\\", \\\"wn\\\"))\\n```\"\n ),\n \"SUBSTRING\": (\n \"**SUBSTRING**(word, start [, end])\\n\\n\"\n \"Cut a slice from the word, counting from 0. Edges past the \"\n \"word are gathered in.\\n\\n\"\n \"```godcode\\nREVEAL(SUBSTRING(\\\"blessing\\\", 2, 6))\\n```\"\n ),\n \"CONTAINS\": (\n \"**CONTAINS**(word, part) / **CONTAINS**(list, value)\\n\\n\"\n \"Ask whether the word holds the part, or the list holds the \"\n \"value. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(CONTAINS(\\\"blessing\\\", \\\"sing\\\"))\\n```\"\n ),\n \"COUNT\": (\n \"**COUNT**(word, part)\\n\\n\"\n \"Count how many times the part appears in the word.\\n\\n\"\n \"```godcode\\nREVEAL(COUNT(\\\"banana\\\", \\\"an\\\"))\\n```\"\n ),\n \"REPEAT\": (\n \"**REPEAT**(word, times)\\n\\n\"\n \"Sing the word `times` times over. Zero gives an empty word.\\n\\n\"\n \"```godcode\\nREVEAL(REPEAT(\\\"Pula! \\\", 3))\\n```\"\n ),\n \"SORT\": (\n \"**SORT**(list)\\n\\n\"\n \"Order the gathering: numbers, words, or truths, least first. \"\n \"Returns a new list; the old one is untouched. Mixed kinds are \"\n \"gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(SORT([3, 1, 2]))\\n```\"\n ),\n \"MIN_OF\": (\n \"**MIN_OF**(list)\\n\\n\"\n \"The least member of the gathering. An empty gathering is \"\n \"gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(MIN_OF([3, 1, 2]))\\n```\"\n ),\n \"MAX_OF\": (\n \"**MAX_OF**(list)\\n\\n\"\n \"The greatest member of the gathering. An empty gathering is \"\n \"gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(MAX_OF([3, 1, 2]))\\n```\"\n ),\n \"SUM_OF\": (\n \"**SUM_OF**(list)\\n\\n\"\n \"Add the numbers together. An empty list sums to 0.\\n\\n\"\n \"```godcode\\nREVEAL(SUM_OF([1, 2, 3]))\\n```\"\n ),\n \"FIRST\": (\n \"**FIRST**(list)\\n\\n\"\n \"The member at the head of the gathering. An empty gathering \"\n \"is gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(FIRST([\\\"a\\\", \\\"b\\\"]))\\n```\"\n ),\n \"LAST\": (\n \"**LAST**(list)\\n\\n\"\n \"The member at the end of the gathering. An empty gathering \"\n \"is gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(LAST([\\\"a\\\", \\\"b\\\"]))\\n```\"\n ),\n \"UNIQUE\": (\n \"**UNIQUE**(list)\\n\\n\"\n \"The gathering with repeats removed, order kept.\\n\\n\"\n \"```godcode\\nREVEAL(UNIQUE([1, 2, 2, 3]))\\n```\"\n ),\n \"INDEX_OF\": (\n \"**INDEX_OF**(list, value)\\n\\n\"\n \"The position of the value, counting from 0, or -1 when it is \"\n \"absent.\\n\\n\"\n \"```godcode\\nREVEAL(INDEX_OF([\\\"a\\\", \\\"b\\\"], \\\"b\\\"))\\n```\"\n ),\n \"KEYS\": (\n \"**KEYS**(map)\\n\\n\"\n \"The map's keys, as a list.\\n\\n\"\n \"```godcode\\nREVEAL(KEYS(JSON_PARSE(\\\"{{\\\\\\\"a\\\\\\\": 1}}\\\")))\\n```\"\n ),\n \"VALUES\": (\n \"**VALUES**(map)\\n\\n\"\n \"The map's values, as a list.\\n\\n\"\n \"```godcode\\nREVEAL(VALUES(JSON_PARSE(\\\"{{\\\\\\\"a\\\\\\\": 1}}\\\")))\\n```\"\n ),\n \"HAS_KEY\": (\n \"**HAS_KEY**(map, key)\\n\\n\"\n \"Ask whether the map holds the key. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(HAS_KEY(m, \\\"tribes\\\"))\\n```\"\n ),\n \"MERGE\": (\n \"**MERGE**(map1, map2)\\n\\n\"\n \"Weave two maps into a new one. Where both hold a key, the \"\n \"second map's value wins.\\n\\n\"\n \"```godcode\\nREVEAL(MERGE(m1, m2))\\n```\"\n ),\n \"ABS\": (\n \"**ABS**(number)\\n\\n\"\n \"The number's distance from zero, always positive.\\n\\n\"\n \"```godcode\\nREVEAL(ABS(-4))\\n```\"\n ),\n \"ROUND\": (\n \"**ROUND**(number [, places])\\n\\n\"\n \"Round half away from zero. `ROUND(2.5)` gives 3; give places \"\n \"to keep decimals.\\n\\n\"\n \"```godcode\\nREVEAL(ROUND(3.14159, 2))\\n```\"\n ),\n \"FLOOR\": (\n \"**FLOOR**(number)\\n\\n\"\n \"The whole number below.\\n\\n\"\n \"```godcode\\nREVEAL(FLOOR(3.9))\\n```\"\n ),\n \"CEIL\": (\n \"**CEIL**(number)\\n\\n\"\n \"The whole number above.\\n\\n\"\n \"```godcode\\nREVEAL(CEIL(3.1))\\n```\"\n ),\n \"SQRT\": (\n \"**SQRT**(number)\\n\\n\"\n \"The square root. A negative number is gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(SQRT(144))\\n```\"\n ),\n \"POW\": (\n \"**POW**(base, exponent)\\n\\n\"\n \"Raise the base to the exponent.\\n\\n\"\n \"```godcode\\nREVEAL(POW(2, 10))\\n```\"\n ),\n}\n\n# Phrases matched as whole units on hover (case-insensitive).\n_PHRASES = (\"BEGIN CREATION\", \"END CREATION\", \"DEFINE RITE\", \"END RITE\",\n \"BREATHE LIFE INTO\")\n\n# Snippet-style completions: (label, insertText, detail).\n_SNIPPETS: tuple[tuple[str, str, str], ...] = (\n (\"BEGIN CREATION … END CREATION\",\n \"BEGIN CREATION\\n\\t$0\\nEND CREATION\",\n \"Open a new scroll\"),\n (\"DECLARE … AS …\", \"DECLARE ${1:name} AS ${2:value}$0\",\n \"Declare a vessel\"),\n (\"IF … THEN … ENDIF\",\n \"IF ${1:condition} THEN\\n\\t$0\\nENDIF\",\n \"Weigh a condition\"),\n (\"FOR … IN … ENDFOR\",\n \"FOR ${1:item} IN ${2:list}\\n\\t$0\\nENDFOR\",\n \"Walk a multitude\"),\n (\"WHILE … DO … ENDWHILE\",\n \"WHILE ${1:condition} DO\\n\\t$0\\nENDWHILE\",\n \"Keep a vigil\"),\n (\"TRY … CATCH … ENDTRY\",\n \"TRY\\n\\t${1:works}\\nCATCH\\n\\t${2:refuge}$0\\nENDTRY\",\n \"Shelter a fragile work\"),\n (\"DEFINE RITE … END RITE\",\n \"DEFINE RITE ${1:name}(${2:params})\\n\\t$0\\nEND RITE\",\n \"Establish a rite\"),\n (\"INVOKE …\", \"INVOKE ${1:name}(${2:args})$0\", \"Call a rite\"),\n)\n\n_WORD_RE = re.compile(r\"[^\\W\\d]\\w*\") # Unicode letters: dotted Igbo words hover too\n\n\n# ---------------------------------------------------------------------------\n# Diagnostics — the real parser, same as `godcode check`\n# ---------------------------------------------------------------------------\n\ndef check_source(text: str) -> list[dict]:\n \"\"\"Parse *text* and return LSP diagnostics (empty when pure).\"\"\"\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n try:\n parse_source(text)\n except GodCodeError as err:\n line = max((err.line or 1) - 1, 0) # LSP lines are 0-based\n lines = text.splitlines()\n line_len = len(lines[line]) if line < len(lines) else 0\n start_char = max((err.col or 1) - 1, 0)\n start_char = min(start_char, max(line_len - 1, 0))\n end_char = min(start_char + 1, line_len)\n return [{\n \"range\": {\n \"start\": {\"line\": line, \"character\": start_char},\n \"end\": {\"line\": line, \"character\": end_char},\n },\n \"severity\": 1, # Error\n \"source\": \"godcode\",\n \"message\": str(err),\n }]\n return []\n\n\n# ---------------------------------------------------------------------------\n# Hover\n# ---------------------------------------------------------------------------\n\ndef _phrase_at(line_text: str, char: int) -> str | None:\n upper = line_text.upper()\n for phrase in _PHRASES:\n start = 0\n while True:\n idx = upper.find(phrase, start)\n if idx < 0:\n break\n if idx <= char <= idx + len(phrase):\n return phrase\n start = idx + 1\n return None\n\n\ndef hover_word(line_text: str, char: int) -> str | None:\n \"\"\"Return the doc-table key under the cursor, or None.\"\"\"\n phrase = _phrase_at(line_text, char)\n if phrase is not None:\n return phrase\n for match in _WORD_RE.finditer(line_text):\n if match.start() <= char <= match.end():\n return match.group(0).upper()\n return None\n\n\ndef hover_markdown(word: str | None) -> str | None:\n if word is None:\n return None\n return LSP_DOCS.get(word)\n\n\n# ---------------------------------------------------------------------------\n# Tongues — the editor speaks the scroll's language\n# ---------------------------------------------------------------------------\n\ndef tongue_of(text: str) -> str | None:\n \"\"\"The tongue a document is written in, from its ``# tongue:`` pragma.\"\"\"\n from godcode.tongues import detect_tongue\n return detect_tongue(text)\n\n\ndef tongue_table(code: str | None) -> dict:\n \"\"\"The tongue table for *code*, or an empty table for English/unknown.\"\"\"\n if code in (None, \"en\"):\n return {}\n try:\n from godcode.tongues import resolve\n table = resolve(code)\n except Exception: # unknown tongue: English completions carry on\n return {}\n return table\n\n\ndef tongue_keyword_items(code: str) -> list[dict]:\n \"\"\"Completion items for a tongue's keywords, e.g. ``SENOLA (REVEAL)``.\"\"\"\n table = tongue_table(code)\n aliases = table.get(\"aliases\", {})\n name = table.get(\"name\", code)\n items = []\n for word in sorted(aliases):\n canonical = aliases[word]\n items.append({\n \"label\": f\"{word} ({canonical})\",\n \"kind\": 14, # Keyword\n \"detail\": f\"God Code keyword in {name}\",\n \"insertText\": word,\n })\n compounds = table.get(\"compounds\", {})\n for (first, second), canonical in sorted(compounds.items()):\n items.append({\n \"label\": f\"{first} {second} ({canonical})\",\n \"kind\": 14, # Keyword\n \"detail\": f\"God Code keyword in {name}\",\n \"insertText\": f\"{first} {second}\",\n })\n return items\n\n\ndef tongue_snippet_items(table: dict) -> list[dict]:\n \"\"\"Block snippets in the tongue, offered when the tongue is active.\n\n The snippet set travels with the tongue's own table in\n ``godcode.tongues``, so a new tongue brings its snippets with it.\n \"\"\"\n name = table.get(\"name\", \"\")\n return [{\n \"label\": label,\n \"kind\": 15, # Snippet\n \"detail\": f\"{detail} ({name})\",\n \"insertText\": insert,\n \"insertTextFormat\": 2, # Snippet\n } for label, insert, detail in table.get(\"snippets\", ())]\n\n\n_TONGUE_PHRASES = {\n (\"BEGIN\", \"CREATION\"): \"BEGIN CREATION\",\n (\"END\", \"CREATION\"): \"END CREATION\",\n (\"END\", \"RITE\"): \"END RITE\",\n (\"DEFINE\", \"RITE\"): \"DEFINE RITE\",\n}\n\n\ndef tongue_hover_key(line_text: str, char: int, code: str) -> str | None:\n \"\"\"The canonical English doc key under the cursor for a tongue word.\n\n Two-word closers (``FEDISA FA``) map to their doc key, openers like\n ``SIMOLOLA TLHOLEGO`` (Setswana) or ``QALA INDALO`` (isiZulu) map to\n ``BEGIN CREATION``, and single words map\n through the tongue's alias table. Returns None when the cursor is not\n on a tongue word.\n \"\"\"\n table = tongue_table(code)\n aliases = table.get(\"aliases\", {})\n compounds = table.get(\"compounds\", {})\n for match in _WORD_RE.finditer(line_text):\n if not (match.start() <= char <= match.end()):\n continue\n word = match.group(0).upper()\n if word not in aliases:\n return None\n canonical = aliases[word]\n rest = line_text[match.end():].lstrip()\n second = _WORD_RE.match(rest)\n if second is not None:\n upper2 = second.group(0).upper()\n key = (word, upper2)\n if key in compounds:\n return compounds[key]\n canonical2 = aliases.get(upper2)\n phrase = _TONGUE_PHRASES.get((canonical, canonical2))\n if phrase is not None:\n return phrase\n return canonical\n return None\n\n\n# ---------------------------------------------------------------------------\n# Completion\n# ---------------------------------------------------------------------------\n\n_COMPLETION_KEYWORDS = sorted(LSP_DOCS)\n_BUILTINS = (\"LEN\", \"STR\", \"NUM\", \"TYPE\", \"RANDOM\", \"RANGE\", \"PUSH\",\n \"UPPER\", \"LOWER\", \"SPLIT\", \"JOIN\", \"ASK\", \"BEHOLD\", \"REVERSE\",\n \"ANCHOR\", \"CONSULT\", \"SHA256\", \"HMAC\", \"BASE64_ENCODE\",\n \"BASE64_DECODE\", \"TRIM\", \"REPLACE\", \"STARTS_WITH\", \"ENDS_WITH\",\n \"SUBSTRING\", \"CONTAINS\", \"COUNT\", \"REPEAT\", \"SORT\", \"MIN_OF\",\n \"MAX_OF\",\n \"SUM_OF\", \"FIRST\", \"LAST\", \"UNIQUE\", \"INDEX_OF\", \"KEYS\",\n \"VALUES\", \"HAS_KEY\", \"MERGE\", \"ABS\", \"ROUND\", \"FLOOR\", \"CEIL\",\n \"SQRT\", \"POW\")\n\n\ndef completion_items(text: str = \"\") -> list[dict]:\n \"\"\"Keyword, built-in, and snippet completions.\n\n When *text* carries a ``# tongue:`` pragma, the tongue's keywords\n (e.g. ``SENOLA (REVEAL)``) and the tongue's snippets join the English\n ones, so a writer crossing over has both hands full.\n \"\"\"\n items: list[dict] = []\n for kw in _COMPLETION_KEYWORDS:\n items.append({\n \"label\": kw,\n \"kind\": 14, # Keyword\n \"detail\": \"God Code \" + (\"built-in\" if kw in _BUILTINS\n else \"keyword\"),\n \"insertText\": kw,\n })\n for label, insert, detail in _SNIPPETS:\n items.append({\n \"label\": label,\n \"kind\": 15, # Snippet\n \"detail\": detail,\n \"insertText\": insert,\n \"insertTextFormat\": 2, # Snippet\n })\n code = tongue_of(text)\n table = tongue_table(code)\n if table:\n items.extend(tongue_keyword_items(code))\n items.extend(tongue_snippet_items(table))\n return items\n\n\n# ---------------------------------------------------------------------------\n# The server\n# ---------------------------------------------------------------------------\n\ndef _log(message: str) -> None:\n sys.stderr.write(f\"[godcode-lsp] {message}\\n\")\n sys.stderr.flush()\n\n\nclass LanguageServer:\n \"\"\"Hand-rolled LSP server over stdio.\"\"\"\n\n def __init__(self,\n stdin: \"io.BufferedReader | None\" = None,\n stdout: \"io.BufferedWriter | None\" = None) -> None:\n import io\n self.stdin = stdin or sys.stdin.buffer\n self.stdout = stdout or sys.stdout.buffer\n self.documents: dict[str, str] = {}\n self._shutdown = False\n self._handlers = {\n \"initialize\": self._on_initialize,\n \"initialized\": self._on_initialized,\n \"shutdown\": self._on_shutdown,\n \"exit\": self._on_exit,\n \"textDocument/didOpen\": self._on_did_open,\n \"textDocument/didChange\": self._on_did_change,\n \"textDocument/hover\": self._on_hover,\n \"textDocument/completion\": self._on_completion,\n }\n\n # -- transport --------------------------------------------------------\n def _read_message(self) -> dict | None:\n \"\"\"Read one Content-Length framed message. None on clean EOF.\"\"\"\n headers: dict[str, str] = {}\n while True:\n line = self.stdin.readline()\n if not line:\n return None # EOF\n line = line.decode(\"latin-1\").strip()\n if not line:\n break\n if \":\" in line:\n name, _, value = line.partition(\":\")\n headers[name.strip().lower()] = value.strip()\n try:\n length = int(headers.get(\"content-length\", \"\"))\n except (TypeError, ValueError):\n _log(\"malformed frame: bad Content-Length; skipping\")\n return {}\n try:\n body = self._read_exact(length)\n except EOFError:\n _log(\"malformed frame: truncated body; skipping\")\n return {}\n try:\n return json.loads(body.decode(\"utf-8\"))\n except (UnicodeDecodeError, json.JSONDecodeError) as exc:\n _log(f\"malformed frame: {exc}; skipping\")\n return {}\n\n def _read_exact(self, length: int) -> bytes:\n body = b\"\"\n while len(body) < length:\n chunk = self.stdin.read(length - len(body))\n if not chunk:\n raise EOFError(\"truncated frame\")\n body += chunk\n return body\n\n def _write(self, payload: dict) -> None:\n body = json.dumps(payload, separators=(\",\", \":\")).encode(\"utf-8\")\n self.stdout.write(\n f\"Content-Length: {len(body)}\\r\\n\\r\\n\".encode(\"ascii\") + body)\n self.stdout.flush()\n\n def _notify(self, method: str, params: dict) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"method\": method, \"params\": params})\n\n def _respond(self, msg_id, result) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"id\": msg_id, \"result\": result})\n\n def _error(self, msg_id, code: int, message: str) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"id\": msg_id,\n \"error\": {\"code\": code, \"message\": message}})\n\n # -- main loop ----------------------------------------------------------\n def serve(self) -> int:\n _log(\"the sanctuary opens (stdio)\")\n while True:\n message = self._read_message()\n if message is None:\n _log(\"stdin closed; ascending\")\n return 1 if not self._shutdown else 0\n if not message:\n continue # malformed frame: already logged, keep serving\n method = message.get(\"method\")\n handler = self._handlers.get(method) if method else None\n msg_id = message.get(\"id\")\n if handler is None:\n _log(f\"unknown method: {method!r}\")\n if msg_id is not None:\n self._error(msg_id, -32601,\n f\"Method not found: {method}\")\n continue\n try:\n stop = handler(msg_id, message.get(\"params\") or {})\n except Exception as exc: # never let a handler kill the server\n _log(f\"handler for {method} failed: {exc}\")\n if msg_id is not None:\n self._error(msg_id, -32603,\n f\"Internal error: {exc}\")\n continue\n if stop:\n return 0\n # pragma: no cover - unreachable\n\n # -- handlers -------------------------------------------------------------\n def _on_initialize(self, msg_id, params: dict) -> None: # noqa: ARG002\n _log(\"initialize received\")\n self._respond(msg_id, {\n \"capabilities\": {\n \"textDocumentSync\": 1, # Full\n \"hoverProvider\": True,\n \"completionProvider\": {\"triggerCharacters\": []},\n },\n \"serverInfo\": {\"name\": \"godcode-lsp\", \"version\": ENGINE_VERSION},\n })\n\n def _on_initialized(self, msg_id, params: dict) -> None: # noqa: ARG002\n _log(\"initialized; no-op\")\n\n def _on_shutdown(self, msg_id, params: dict) -> None: # noqa: ARG002\n _log(\"shutdown requested\")\n self._shutdown = True\n if msg_id is not None:\n self._respond(msg_id, None)\n\n def _on_exit(self, msg_id, params: dict) -> bool: # noqa: ARG002\n _log(\"exit; the sanctuary rests\")\n return True\n\n def _on_did_open(self, msg_id, params: dict) -> None: # noqa: ARG002\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n text = doc.get(\"text\", \"\")\n self.documents[uri] = text\n self._publish_diagnostics(uri, text)\n\n def _on_did_change(self, msg_id, params: dict) -> None: # noqa: ARG002\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n text = self.documents.get(uri, \"\")\n for change in params.get(\"contentChanges\", []):\n if \"range\" not in change: # full-document sync\n text = change.get(\"text\", \"\")\n self.documents[uri] = text\n self._publish_diagnostics(uri, text)\n\n def _publish_diagnostics(self, uri: str, text: str) -> None:\n diagnostics = check_source(text)\n _log(f\"diagnostics for {uri}: {len(diagnostics)} error(s)\")\n self._notify(\"textDocument/publishDiagnostics\",\n {\"uri\": uri, \"diagnostics\": diagnostics})\n\n def _on_hover(self, msg_id, params: dict) -> None:\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n pos = params.get(\"position\", {})\n line_no = pos.get(\"line\", 0)\n char = pos.get(\"character\", 0)\n text = self.documents.get(uri, \"\")\n lines = text.splitlines()\n line_text = lines[line_no] if 0 <= line_no < len(lines) else \"\"\n word = hover_word(line_text, char)\n canonical = word\n code = tongue_of(text)\n if code not in (None, \"en\"):\n tongue_key = tongue_hover_key(line_text, char, code)\n if tongue_key is not None:\n canonical = tongue_key\n markdown = hover_markdown(canonical)\n _log(f\"hover at {uri}:{line_no}:{char} -> {word!r}\"\n + (f\" (tongue {code}: {canonical!r})\" if canonical != word\n else \"\"))\n self._respond(msg_id, {\"contents\": {\"kind\": \"markdown\",\n \"value\": markdown}}\n if markdown else None)\n\n def _on_completion(self, msg_id, params: dict) -> None:\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n self._respond(msg_id, completion_items(self.documents.get(uri, \"\")))\n\n\ndef serve() -> int:\n \"\"\"Entry point for ``godcode lsp``.\"\"\"\n return LanguageServer().serve()\n","godcode/mcp.py":"\"\"\"The God Code MCP server -- ``godcode mcp``.\n\nSpeaks the Model Context Protocol over stdio (one JSON-RPC 2.0 message\nper line, the standard stdio transport) so any MCP client -- Claude Code,\nCursor, Codex, or any other agent host -- can check, run, explain,\nformat, and list God Code scrolls, and verify ledgers, without learning\na bespoke protocol.\n\nThe tools are the same eleven the agent bridge offers, plus one rule\nthat only holds here: **runs are always sandboxed**. An MCP client\ntalks to scrolls it did not write, so the server ignores any request\nto run outside the sandbox and says so in the result. The plain\n``godcode bridge`` keeps its own convention for hosts that already\ntrust their scrolls; this server never trusts them.\n\nNo third-party dependencies. Protocol versions are negotiated the way\nMCP asks: the client names the version it speaks, and the server\nanswers with that version when it knows it, or with the newest version\nit speaks when it does not.\n\"\"\"\nfrom __future__ import annotations\n\nimport json\n\nfrom godcode import tools as _tools\n\n#: Newest first. A client version outside this list gets the newest.\nSUPPORTED_PROTOCOL_VERSIONS = (\"2025-06-18\", \"2025-03-26\", \"2024-11-05\")\n\n_PARSE_ERROR = -32700\n_INVALID_REQUEST = -32600\n_METHOD_NOT_FOUND = -32601\n_INVALID_PARAMS = -32602\n_INTERNAL_ERROR = -32603\n\n\nclass _McpError(Exception):\n def __init__(self, code: int, message: str) -> None:\n super().__init__(message)\n self.code = code\n self.message = message\n\n\ndef _response_ok(req_id, result: dict) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id, \"result\": result}\n\n\ndef _response_err(req_id, code: int, message: str) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id,\n \"error\": {\"code\": code, \"message\": message}}\n\n\ndef negotiate_protocol_version(client_version) -> str:\n \"\"\"Answer an MCP initialize with a version both sides speak.\"\"\"\n if isinstance(client_version, str) \\\n and client_version in SUPPORTED_PROTOCOL_VERSIONS:\n return client_version\n return SUPPORTED_PROTOCOL_VERSIONS[0]\n\n\ndef _handle_initialize(params: dict) -> dict:\n from godcode import __version__\n\n return {\n \"protocolVersion\": negotiate_protocol_version(\n params.get(\"protocolVersion\")),\n \"capabilities\": {\"tools\": {}},\n \"serverInfo\": {\"name\": \"godcode\", \"version\": __version__},\n }\n\n\ndef call_mcp_tool(name: str, arguments: dict) -> dict:\n \"\"\"Run one tool the MCP way: runs are always sandboxed.\n\n Any ``sandbox: false`` on a run request is overruled, and the\n result says the run was sandboxed, so a client can never mistake\n an MCP run for an unsandboxed one.\n \"\"\"\n if name == \"run\":\n arguments = dict(arguments)\n arguments[\"sandbox\"] = True\n result = _tools.call_tool(name, arguments)\n result[\"sandbox\"] = True\n return result\n return _tools.call_tool(name, arguments)\n\n\ndef _handle_tools_call(params: dict) -> dict:\n name = params.get(\"name\")\n arguments = params.get(\"arguments\", {})\n if not isinstance(name, str):\n raise _McpError(_INVALID_PARAMS, \"tools/call needs 'name' as a string\")\n if not isinstance(arguments, dict):\n raise _McpError(_INVALID_PARAMS, \"'arguments' must be an object\")\n result = call_mcp_tool(name, arguments)\n payload = {\"content\": [{\"type\": \"text\",\n \"text\": json.dumps(result, ensure_ascii=False)}]}\n if not result.get(\"ok\", True):\n payload[\"isError\"] = True\n return payload\n\n\ndef _dispatch(method: str, params: dict):\n if method == \"initialize\":\n return _handle_initialize(params)\n if method == \"ping\":\n return {}\n if method == \"tools/list\":\n return {\"tools\": _tools.TOOL_SCHEMAS}\n if method == \"tools/call\":\n return _handle_tools_call(params)\n if method == \"resources/list\":\n return {\"resources\": []}\n if method == \"prompts/list\":\n return {\"prompts\": []}\n raise _McpError(_METHOD_NOT_FOUND, f\"no such method '{method}'\")\n\n\ndef handle_message(message: dict):\n \"\"\"Answer one parsed MCP message, or None when no answer is owed.\n\n Notifications (no ``id``) never get an answer, whatever method\n they carry. Anything malformed raises _McpError.\n \"\"\"\n if not isinstance(message, dict) or \"method\" not in message:\n raise _McpError(_INVALID_REQUEST, \"a request needs a 'method'\")\n if \"id\" not in message:\n return None\n params = message.get(\"params\", {})\n if not isinstance(params, dict):\n raise _McpError(_INVALID_PARAMS, \"'params' must be an object\")\n return _dispatch(message[\"method\"], params)\n\n\ndef cmd_mcp(args) -> int: # noqa: ARG001\n \"\"\"Serve the MCP server: JSON-RPC 2.0 over stdio, one message per line.\n\n Stdout carries exactly one protocol message per line. Tool work\n runs muted, so an engine print can never land in the stream: the\n response is written only after handling returns.\n \"\"\"\n import contextlib\n import io\n import sys\n\n stdin, stdout = sys.stdin, sys.stdout\n for line in stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n stdout.write(json.dumps(_response_err(None, _PARSE_ERROR,\n \"the request was not JSON\"))\n + \"\\n\")\n stdout.flush()\n continue\n req_id = request.get(\"id\") if isinstance(request, dict) else None\n try:\n with contextlib.redirect_stdout(io.StringIO()):\n result = handle_message(request)\n except _McpError as err:\n response = _response_err(req_id, err.code, err.message)\n except Exception as exc: # pragma: no cover - defensive\n response = _response_err(req_id, _INTERNAL_ERROR,\n f\"the server faltered: {exc!r}\")\n else:\n if result is None:\n continue\n response = _response_ok(req_id, result)\n stdout.write(json.dumps(response, ensure_ascii=False) + \"\\n\")\n stdout.flush()\n return 0\n","godcode/parser.py":"\"\"\"Recursive-descent parser for God Code v2.0.\n\n``Parser(tokens).parse()`` returns a ``Program``. A program is either a\n``BEGIN CREATION ... END CREATION`` block (wrapped in a Program) or a\nbare sequence of statements (for scrolls / fragments).\n\nStatement forms (spec §4):\n- DECLARE name AS expr (, expr)* -> Declare (multi-expr -> ListLiteral)\n- BREATHE LIFE INTO name -> Breathe\n- REVEAL(expr) -> Reveal\n- PROPHESY -> Prophesy\n- ASCEND / REFLECT -> Ascend / Reflect\n- BLESS name / ANOINT name -> Bless / Anoint\n- SEAL expr / TESTIFY expr -> SealStmt / Testify\n- IF expr THEN ... (block: ENDIF / inline) -> IfStmt\n- FOR name IN expr ... (block: ENDFOR / legacy open / inline) -> ForLoop\n- WHILE expr DO ... (block: ENDWHILE / inline) -> WhileLoop\n- TRY ... CATCH [name] ... ENDTRY (block) -> TryStmt\n- DEFINE RITE name(params) ... END RITE (block or inline) -> DefineRite\n- RETURN expr? -> Return\n- IMPORT \"path\" -> Import\n- INVOKE name(args) | any expression -> CallExpr / ExprStmt\n\nExpression precedence (low -> high):\n or -> and -> not -> comparison (IS [NOT], =, ==, !=, <, >, <=, >=)\n -> additive (+ -) -> multiplicative (* / %) -> unary (-, NOT) -> primary\n``IS``/``IS NOT`` become ``==``/``!=`` BinaryOps.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom . import ast as A\nfrom .errors import ParseError\nfrom .lexer import Lexer\nfrom .tokens import Token, TokenType\n\nTT = TokenType\n\n_EXPR_STARTS = {\n TT.NUMBER, TT.STRING, TT.IDENT, TT.LPAREN, TT.LBRACKET,\n TT.MINUS, TT.NOT, TT.TRUE, TT.FALSE, TT.VOID, TT.INVOKE,\n}\n\n# Tokens after which RETURN takes no expression.\n_RETURN_TERMINATORS = {\n TT.NEWLINE, TT.EOF, TT.END, TT.ENDIF, TT.ELSE, TT.ENDFOR, TT.ENDWHILE,\n TT.CATCH, TT.ENDTRY,\n}\n\n\nclass Parser:\n def __init__(self, tokens: list[Token], tongue: str | None = None):\n if not tokens:\n raise ParseError(\"The scroll is empty; there is nothing to reveal\")\n self.tokens = tokens\n self.pos = 0\n # The tongue the source was lexed in (\"en\" when none); carried into\n # interpolated {expressions} so their keywords speak it too.\n self._tongue = tongue or \"en\"\n # Tracks lexically enclosing FOR/WHILE loops so BREAK and CONTINUE\n # can be rejected at parse time when no loop holds them. A rite\n # body resets this to 0: loop signals never cross a rite boundary.\n self._loop_depth = 0\n\n # -- public ------------------------------------------------------------\n\n def parse(self) -> A.Program:\n self._skip_newlines()\n first = self._peek()\n if self._check(TT.BEGIN):\n block = self._parse_creation_block()\n self._skip_newlines()\n t = self._peek()\n if t.type is not TT.EOF:\n raise ParseError(\n f\"The creation is sealed, yet {self._describe(t)} remains; \"\n \"a scroll holds only one creation\",\n line=t.line, col=t.col,\n )\n return A.Program(statements=[block], line=block.line, col=block.col)\n stmts = self._parse_body(\n end={TT.EOF},\n missing=\"the end of the scroll\",\n opening=None,\n )\n return A.Program(statements=stmts, line=first.line, col=first.col)\n\n # -- cursor helpers ----------------------------------------------------\n\n def _peek(self) -> Token:\n return self.tokens[self.pos]\n\n def _peek_next(self) -> Token:\n if self.pos + 1 < len(self.tokens):\n return self.tokens[self.pos + 1]\n return self.tokens[-1]\n\n def _advance(self) -> Token:\n t = self.tokens[self.pos]\n if self.pos < len(self.tokens) - 1:\n self.pos += 1\n return t\n\n def _check(self, tt: TokenType) -> bool:\n return self._peek().type is tt\n\n def _expect(self, tt: TokenType, what: str | None = None) -> Token:\n t = self._peek()\n if t.type is not tt:\n raise ParseError(\n f\"Expected {what or tt.name} but found {self._describe(t)}\",\n line=t.line, col=t.col,\n )\n return self._advance()\n\n def _skip_newlines(self) -> None:\n while self._check(TT.NEWLINE):\n self._advance()\n\n @staticmethod\n def _describe(t: Token) -> str:\n if t.type is TT.EOF:\n return \"the end of the scroll\"\n if t.type is TT.NEWLINE:\n return \"the end of the line\"\n if t.type is TT.IDENT:\n return f\"the name '{t.value}'\"\n if t.type is TT.NUMBER:\n return f\"the number {t.value!r}\"\n if t.type is TT.STRING:\n return f\"the text {t.value!r}\"\n return f\"'{t.value}'\"\n\n # -- statement lists ---------------------------------------------------\n\n def _parse_body(self, *, end: set[TokenType], missing: str,\n opening: Token | None, legacy_for: bool = False) -> list:\n \"\"\"Parse statements until a token in ``end`` (left unconsumed).\n\n With ``legacy_for``, END CREATION / END RITE / EOF also end the body\n without being consumed (the original sample.godcode's open FOR).\n Otherwise hitting them raises ParseError naming what was missing.\n \"\"\"\n stmts: list = []\n while True:\n self._skip_newlines()\n t = self._peek()\n if t.type in end:\n return stmts\n if t.type is TT.EOF:\n if legacy_for:\n return stmts\n raise ParseError(\n f\"The scroll ends before {missing}; \"\n + (f\"the {opening.value} opened on line {opening.line} \"\n \"was never closed\" if opening else\n \"every opened block must be closed\"),\n line=t.line, col=t.col,\n )\n if t.type is TT.END and self._peek_next().type in (TT.CREATION, TT.RITE):\n if legacy_for:\n return stmts\n raise ParseError(\n f\"Found {t.value} {self._peek_next().value} before {missing}; \"\n \"every opened block must be closed in its own time\",\n line=t.line, col=t.col,\n )\n stmts.append(self._parse_statement())\n\n # -- top level ---------------------------------------------------------\n\n def _parse_creation_block(self) -> A.CreationBlock:\n b = self._expect(TT.BEGIN)\n self._expect(TT.CREATION)\n self._skip_newlines()\n stmts = self._parse_body(end={TT.END}, missing=\"END CREATION\", opening=b)\n self._expect(TT.END)\n self._expect(TT.CREATION)\n return A.CreationBlock(statements=stmts, line=b.line, col=b.col)\n\n # -- statements --------------------------------------------------------\n\n def _parse_statement(self):\n t = self._peek()\n tt = t.type\n if tt is TT.DECLARE:\n return self._parse_declare()\n if tt is TT.BREATHE:\n return self._parse_breathe()\n if tt is TT.REVEAL:\n return self._parse_reveal()\n if tt is TT.PROPHESY:\n return self._parse_prophesy()\n if tt is TT.ASCEND:\n self._advance()\n return A.Ascend(line=t.line, col=t.col)\n if tt is TT.REFLECT:\n self._advance()\n return A.Reflect(line=t.line, col=t.col)\n if tt is TT.BLESS:\n return self._parse_named_single(TT.BLESS, A.Bless)\n if tt is TT.ANOINT:\n return self._parse_named_single(TT.ANOINT, A.Anoint)\n if tt is TT.SEAL:\n self._advance()\n return A.SealStmt(expr=self._parse_expr(), line=t.line, col=t.col)\n if tt is TT.TESTIFY:\n self._advance()\n return A.Testify(expr=self._parse_expr(), line=t.line, col=t.col)\n if tt is TT.IF:\n return self._parse_if()\n if tt is TT.FOR:\n return self._parse_for()\n if tt is TT.WHILE:\n return self._parse_while()\n if tt is TT.BREAK:\n return self._parse_break()\n if tt is TT.CONTINUE:\n return self._parse_continue()\n if tt is TT.TRY:\n return self._parse_try()\n if tt is TT.DEFINE:\n return self._parse_define_rite()\n if tt is TT.RETURN:\n return self._parse_return()\n if tt is TT.IMPORT:\n return self._parse_import()\n if tt in _EXPR_STARTS:\n expr = self._parse_expr()\n return A.ExprStmt(expr=expr, line=t.line, col=t.col)\n raise ParseError(\n f\"Unexpected {self._describe(t)}; a decree must begin with \"\n \"a holy word (DECLARE, IF, FOR, REVEAL, ...)\",\n line=t.line, col=t.col,\n )\n\n def _parse_named_single(self, tt: TokenType, node_cls):\n kw = self._expect(tt)\n name = self._expect(TT.IDENT, \"a name\").value\n return node_cls(name=name, line=kw.line, col=kw.col)\n\n def _parse_declare(self) -> A.Declare:\n d = self._expect(TT.DECLARE)\n # --- v4.0: DECLARE INTENT \"words...\" ON rite_name ---\n # INTENT and ON are soft keywords (plain identifiers by text), so\n # `DECLARE intent AS x` keeps working: only DECLARE followed by the\n # word INTENT and then a quoted string takes the intent path.\n nxt, nxt2 = self._peek(), self._peek_next()\n if (nxt.type is TT.IDENT and nxt.value.upper() == \"INTENT\"\n and nxt2.type is TT.STRING):\n self._advance() # the word INTENT\n text = self._expect(TT.STRING, \"the intent in quotes\").value\n on = self._peek()\n if not (on.type is TT.IDENT and on.value.upper() == \"ON\"):\n raise ParseError(\n 'DECLARE INTENT needs ON and a rite name, as in '\n 'DECLARE INTENT \"bring peace\" ON evening_blessing',\n line=on.line, col=on.col,\n )\n self._advance() # the word ON\n rite = self._expect(TT.IDENT, \"a rite name\").value\n return A.DeclareIntent(text=text, rite=rite, line=d.line, col=d.col)\n # --- permission manifests: DECLARE PERMISSION TO ---\n # PERMISSION and TO are soft keywords (plain identifiers by text), so\n # `DECLARE permission AS x` keeps working: only DECLARE followed by\n # the word PERMISSION takes the manifest path.\n if (nxt.type is TT.IDENT and nxt.value.upper() == \"PERMISSION\"\n and nxt2.type is TT.IDENT and nxt2.value.upper() == \"TO\"):\n return self._parse_declare_permission(d)\n # --- end permission manifests ---\n name = self._expect(TT.IDENT, \"a name to declare\").value\n self._expect(TT.AS)\n items = [self._parse_expr()]\n while self._check(TT.COMMA):\n self._advance()\n items.append(self._parse_expr())\n if len(items) == 1:\n value = items[0]\n else:\n value = A.ListLiteral(items=items, line=items[0].line, col=items[0].col)\n return A.Declare(name=name, value=value, line=d.line, col=d.col)\n\n def _parse_declare_permission(self, d) -> A.DeclarePermission:\n \"\"\"Parse DECLARE PERMISSION TO -- the permission manifest.\"\"\"\n self._advance() # the word PERMISSION\n self._advance() # the word TO\n line, col = d.line, d.col\n\n def word_is(text: str) -> bool:\n t = self._peek()\n return t.type is TT.IDENT and t.value.upper() == text\n\n def eat_word(text: str) -> None:\n t = self._peek()\n if not (t.type is TT.IDENT and t.value.upper() == text):\n raise ParseError(\n f\"DECLARE PERMISSION TO expects the word {text} here, \"\n f\"as in DECLARE PERMISSION TO {text} ...\",\n line=t.line, col=t.col,\n )\n self._advance()\n\n def eat_string(what: str) -> str:\n return self._expect(TT.STRING, what).value\n\n if word_is(\"READ\"):\n self._advance()\n return A.DeclarePermission(\n power=\"read\",\n target=eat_string('a path in quotes, as in DECLARE PERMISSION TO READ \"data/\"'),\n line=line, col=col,\n )\n if word_is(\"WRITE\"):\n self._advance()\n return A.DeclarePermission(\n power=\"write\",\n target=eat_string('a path in quotes, as in DECLARE PERMISSION TO WRITE \"out/\"'),\n line=line, col=col,\n )\n if word_is(\"SPEAK\"):\n self._advance()\n eat_word(\"WITH\")\n return A.DeclarePermission(\n power=\"network\",\n target=eat_string('a host in quotes, as in DECLARE PERMISSION TO SPEAK WITH \"api.example.com\"'),\n line=line, col=col,\n )\n if word_is(\"ASK\"):\n self._advance()\n eat_word(\"THE\")\n eat_word(\"WORLD\")\n return A.DeclarePermission(power=\"stdin\", target=None, line=line, col=col)\n if word_is(\"SUMMON\"):\n self._advance()\n return A.DeclarePermission(\n power=\"summon\",\n target=eat_string('a verb name in quotes, as in DECLARE PERMISSION TO SUMMON \"reports.weekly\"'),\n line=line, col=col,\n )\n t = self._peek()\n raise ParseError(\n \"DECLARE PERMISSION TO grants one power: READ a path, WRITE a \"\n \"path, SPEAK WITH a host, ASK THE WORLD, or SUMMON a verb. \"\n f\"I heard '{t.value}'.\",\n line=t.line, col=t.col,\n )\n\n def _parse_breathe(self) -> A.Breathe:\n b = self._expect(TT.BREATHE)\n self._expect(TT.LIFE)\n self._expect(TT.INTO)\n name = self._expect(TT.IDENT, \"a name to breathe into\").value\n return A.Breathe(name=name, line=b.line, col=b.col)\n\n def _parse_reveal(self) -> A.Reveal:\n r = self._expect(TT.REVEAL)\n self._expect(TT.LPAREN)\n expr = self._parse_expr()\n self._expect(TT.RPAREN)\n return A.Reveal(expr=expr, line=r.line, col=r.col)\n\n def _parse_prophesy(self) -> A.Prophesy:\n p = self._expect(TT.PROPHESY)\n line_no = p.line\n parts: list[str] = []\n while True:\n t = self._peek()\n if t.type in (TT.NEWLINE, TT.EOF) or t.line != line_no:\n break\n parts.append(str(t.value))\n self._advance()\n return A.Prophesy(text=\" \".join(parts), line=p.line, col=p.col)\n\n def _parse_if(self) -> A.IfStmt:\n i = self._expect(TT.IF)\n cond = self._parse_expr()\n self._expect(TT.THEN)\n if self._check(TT.NEWLINE):\n self._skip_newlines()\n then_body = self._parse_body(end={TT.ENDIF, TT.ELSE},\n missing=\"ENDIF\", opening=i)\n else_body: list = []\n has_else = False\n if self._check(TT.ELSE):\n self._advance()\n has_else = True\n self._skip_newlines()\n else_body = self._parse_body(end={TT.ENDIF},\n missing=\"ENDIF\", opening=i)\n self._expect(TT.ENDIF)\n else:\n then_body = [self._parse_statement()]\n else_body = []\n has_else = False\n if self._check(TT.ELSE):\n self._advance()\n has_else = True\n else_body = [self._parse_statement()]\n return A.IfStmt(cond=cond, then_body=then_body, else_body=else_body,\n has_else=has_else, line=i.line, col=i.col)\n\n def _parse_for(self) -> A.ForLoop:\n f = self._expect(TT.FOR)\n var = self._expect(TT.IDENT, \"a name for the traveler\").value\n self._expect(TT.IN)\n iterable = self._parse_expr()\n self._loop_depth += 1\n try:\n if self._check(TT.NEWLINE):\n body = self._parse_body(end={TT.ENDFOR}, missing=\"ENDFOR\",\n opening=f, legacy_for=True)\n if self._check(TT.ENDFOR):\n self._advance()\n else:\n body = [self._parse_statement()]\n finally:\n self._loop_depth -= 1\n return A.ForLoop(var=var, iterable=iterable, body=body,\n line=f.line, col=f.col)\n\n def _parse_while(self) -> A.WhileLoop:\n w = self._expect(TT.WHILE)\n cond = self._parse_expr()\n self._expect(TT.DO)\n self._loop_depth += 1\n try:\n if self._check(TT.NEWLINE):\n body = self._parse_body(end={TT.ENDWHILE}, missing=\"ENDWHILE\",\n opening=w)\n self._expect(TT.ENDWHILE)\n else:\n body = [self._parse_statement()]\n finally:\n self._loop_depth -= 1\n return A.WhileLoop(cond=cond, body=body, line=w.line, col=w.col)\n\n def _parse_break(self) -> A.Break:\n b = self._advance()\n if self._loop_depth == 0:\n raise ParseError(\n \"BREAK can only be used inside a loop. It was spoken with \"\n \"no cycle to release. Place it within a FOR or a WHILE.\",\n line=b.line, col=b.col,\n )\n return A.Break(line=b.line, col=b.col)\n\n def _parse_continue(self) -> A.Continue:\n c = self._advance()\n if self._loop_depth == 0:\n raise ParseError(\n \"CONTINUE can only be used inside a loop. It was spoken with \"\n \"no cycle to turn. Place it within a FOR or a WHILE.\",\n line=c.line, col=c.col,\n )\n return A.Continue(line=c.line, col=c.col)\n\n def _parse_try(self) -> A.TryStmt:\n t = self._expect(TT.TRY)\n if not self._check(TT.NEWLINE):\n raise ParseError(\n \"TRY opens a block: place its works on the following lines, \"\n \"then CATCH ... ENDTRY\",\n line=t.line, col=t.col,\n )\n self._skip_newlines()\n try_body = self._parse_body(end={TT.CATCH}, missing=\"CATCH\", opening=t)\n self._expect(TT.CATCH)\n if self._check(TT.IDENT):\n error_name = self._advance().value\n else:\n error_name = \"ERROR\"\n self._skip_newlines()\n catch_body = self._parse_body(end={TT.ENDTRY}, missing=\"ENDTRY\",\n opening=t)\n self._expect(TT.ENDTRY)\n return A.TryStmt(try_body=try_body, catch_body=catch_body,\n error_name=error_name, line=t.line, col=t.col)\n\n def _parse_define_rite(self) -> A.DefineRite:\n d = self._expect(TT.DEFINE)\n self._expect(TT.RITE)\n name = self._expect(TT.IDENT, \"a name for the rite\").value\n self._expect(TT.LPAREN)\n params: list[str] = []\n if not self._check(TT.RPAREN):\n params.append(self._expect(TT.IDENT, \"a parameter name\").value)\n while self._check(TT.COMMA):\n self._advance()\n params.append(self._expect(TT.IDENT, \"a parameter name\").value)\n self._expect(TT.RPAREN)\n # A rite body is a fresh boundary: BREAK/CONTINUE inside it may only\n # answer to loops within the rite, never to a caller's loop.\n saved_depth, self._loop_depth = self._loop_depth, 0\n try:\n if self._check(TT.NEWLINE):\n self._skip_newlines()\n body = self._parse_body(end={TT.END}, missing=\"END RITE\", opening=d)\n else:\n # inline single-statement body, e.g. DEFINE RITE f(x) SEAL x END RITE\n body = [self._parse_statement()]\n self._skip_newlines()\n finally:\n self._loop_depth = saved_depth\n self._expect(TT.END)\n self._expect(TT.RITE)\n return A.DefineRite(name=name, params=params, body=body,\n line=d.line, col=d.col)\n\n def _parse_return(self) -> A.Return:\n r = self._expect(TT.RETURN)\n if self._peek().type in _RETURN_TERMINATORS:\n return A.Return(expr=None, line=r.line, col=r.col)\n return A.Return(expr=self._parse_expr(), line=r.line, col=r.col)\n\n def _parse_import(self) -> A.Import:\n im = self._expect(TT.IMPORT)\n path = self._expect(TT.STRING, \"a scroll path in quotes\").value\n return A.Import(path=path, line=im.line, col=im.col)\n\n # -- expressions -------------------------------------------------------\n\n def _parse_expr(self):\n return self._parse_or()\n\n def _parse_or(self):\n left = self._parse_and()\n while self._check(TT.OR):\n op = self._advance()\n right = self._parse_and()\n left = A.BinaryOp(op=\"or\", left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_and(self):\n left = self._parse_not_low()\n while self._check(TT.AND):\n op = self._advance()\n right = self._parse_not_low()\n left = A.BinaryOp(op=\"and\", left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_not_low(self):\n if self._check(TT.NOT):\n op = self._advance()\n return A.UnaryOp(op=\"not\", operand=self._parse_not_low(),\n line=op.line, col=op.col)\n return self._parse_comparison()\n\n _COMPARISON_OPS = {\n TT.EQ: \"==\", TT.NEQ: \"!=\", TT.LT: \"<\",\n TT.GT: \">\", TT.LTE: \"<=\", TT.GTE: \">=\",\n }\n\n def _parse_comparison(self):\n left = self._parse_additive()\n while True:\n t = self._peek()\n if t.type is TT.IS:\n self._advance()\n if self._check(TT.NOT):\n self._advance()\n op = \"!=\"\n else:\n op = \"==\"\n elif t.type in self._COMPARISON_OPS:\n self._advance()\n op = self._COMPARISON_OPS[t.type]\n else:\n break\n right = self._parse_additive()\n left = A.BinaryOp(op=op, left=left, right=right,\n line=t.line, col=t.col)\n return left\n\n def _parse_additive(self):\n left = self._parse_multiplicative()\n while self._peek().type in (TT.PLUS, TT.MINUS):\n op = self._advance()\n right = self._parse_multiplicative()\n left = A.BinaryOp(op=op.value, left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_multiplicative(self):\n left = self._parse_unary()\n while self._peek().type in (TT.STAR, TT.SLASH, TT.PERCENT):\n op = self._advance()\n right = self._parse_unary()\n left = A.BinaryOp(op=op.value, left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_unary(self):\n t = self._peek()\n if t.type is TT.MINUS:\n self._advance()\n return A.UnaryOp(op=\"-\", operand=self._parse_unary(),\n line=t.line, col=t.col)\n if t.type is TT.NOT:\n self._advance()\n return A.UnaryOp(op=\"not\", operand=self._parse_unary(),\n line=t.line, col=t.col)\n return self._parse_postfix()\n\n def _parse_postfix(self):\n obj = self._parse_primary()\n while self._check(TT.LBRACKET):\n lb = self._advance()\n index = self._parse_expr()\n self._expect(TT.RBRACKET)\n obj = A.Index(obj=obj, index=index, line=lb.line, col=lb.col)\n return obj\n\n def _parse_primary(self):\n t = self._peek()\n tt = t.type\n if tt is TT.NUMBER:\n self._advance()\n return A.Literal(value=t.value, line=t.line, col=t.col)\n if tt is TT.STRING:\n self._advance()\n if \"{\" in t.value or \"}}\" in t.value:\n return self._parse_interpolated(t)\n return A.Literal(value=t.value, line=t.line, col=t.col)\n if tt is TT.TRUE:\n self._advance()\n return A.Literal(value=True, line=t.line, col=t.col)\n if tt is TT.FALSE:\n self._advance()\n return A.Literal(value=False, line=t.line, col=t.col)\n if tt is TT.VOID:\n self._advance()\n return A.Literal(value=None, line=t.line, col=t.col)\n if tt is TT.IDENT:\n self._advance()\n if self._check(TT.LPAREN):\n self._advance()\n args = self._parse_args()\n self._expect(TT.RPAREN)\n return A.CallExpr(callee=t.value, args=args,\n line=t.line, col=t.col)\n return A.Identifier(name=t.value, line=t.line, col=t.col)\n if tt is TT.INVOKE:\n self._advance()\n name = self._expect(TT.IDENT, \"a rite name\").value\n self._expect(TT.LPAREN)\n args = self._parse_args()\n self._expect(TT.RPAREN)\n return A.CallExpr(callee=name, args=args, line=t.line, col=t.col)\n if tt is TT.LPAREN:\n self._advance()\n expr = self._parse_expr()\n self._expect(TT.RPAREN)\n return expr\n if tt is TT.LBRACKET:\n self._advance()\n items = []\n if not self._check(TT.RBRACKET):\n items.append(self._parse_expr())\n while self._check(TT.COMMA):\n self._advance()\n items.append(self._parse_expr())\n self._expect(TT.RBRACKET)\n return A.ListLiteral(items=items, line=t.line, col=t.col)\n raise ParseError(\n f\"Expected a value or name but found {self._describe(t)}\",\n line=t.line, col=t.col,\n )\n\n # -- string interpolation: \"grace upon {name}\" ----------------------------\n\n def _parse_interpolated(self, tok):\n \"\"\"Build an InterpolatedString from a STRING token's value.\n\n ``{expr}`` breathes the expression's revealed value into the string;\n ``{{`` and ``}}`` write a plain brace; a lone ``}`` stays a plain brace.\n \"\"\"\n src = tok.value\n parts: list = []\n buf: list[str] = []\n i, n = 0, len(src)\n while i < n:\n ch = src[i]\n if ch == \"{\" and src[i + 1 : i + 2] == \"{\":\n buf.append(\"{\")\n i += 2\n continue\n if ch == \"}\" and src[i + 1 : i + 2] == \"}\":\n buf.append(\"}\")\n i += 2\n continue\n if ch == \"{\":\n end = self._find_interpolation_end(src, i, tok)\n inner = src[i + 1 : end]\n if not inner.strip():\n raise ParseError(\n \"empty braces breathe nothing into the string; \"\n \"place a name or an expression between '{' and '}', \"\n \"or write '{{}}' for plain braces\",\n line=tok.line, col=tok.col + i,\n )\n if buf:\n parts.append(\"\".join(buf))\n buf = []\n parts.append(self._parse_braced_expr(inner, tok, i))\n i = end + 1\n continue\n buf.append(ch)\n i += 1\n if buf:\n parts.append(\"\".join(buf))\n return A.InterpolatedString(parts=parts, source=src,\n line=tok.line, col=tok.col)\n\n @staticmethod\n def _find_interpolation_end(src: str, start: int, tok) -> int:\n \"\"\"Index of the ``}`` closing the ``{`` at ``start``.\n\n Nested braces count toward the depth, and braces inside a quoted\n string are skipped, so ``\"{greet(\"hi {name}\")}\"`` seals correctly.\n \"\"\"\n depth = 0\n in_string = False\n i, n = start, len(src)\n while i < n:\n c = src[i]\n if in_string:\n if c == \"\\\\\":\n i += 2\n continue\n if c == '\"':\n in_string = False\n elif c == '\"':\n in_string = True\n elif c == \"{\":\n depth += 1\n elif c == \"}\":\n depth -= 1\n if depth == 0:\n return i\n i += 1\n raise ParseError(\n \"an opening '{' breathes a blessing that was never sealed; \"\n \"close it with '}' or write '{{' for a plain brace\",\n line=tok.line, col=tok.col + start,\n )\n\n def _parse_braced_expr(self, inner: str, tok, offset: int):\n \"\"\"Parse the text between one pair of braces as a single expression.\"\"\"\n tokens = [t for t in Lexer(inner, tongue=self._tongue).lex()\n if t.type not in (TT.NEWLINE, TT.EOF)]\n tokens.append(Token(TT.EOF, \"\", tok.line, tok.col + offset))\n sub = Parser(tokens)\n expr = sub._parse_expr()\n if not sub._check(TT.EOF):\n raise ParseError(\n \"the blessing between '{' and '}' could not be understood; \"\n \"only one expression may dwell there\",\n line=tok.line, col=tok.col + offset,\n )\n return expr\n\n def _parse_args(self) -> list:\n args = []\n if not self._check(TT.RPAREN):\n args.append(self._parse_expr())\n while self._check(TT.COMMA):\n self._advance()\n args.append(self._parse_expr())\n return args\n","godcode/permissions.py":"\"\"\"Permission manifests for God Code.\n\nA scroll may declare what it is allowed to touch:\n\n DECLARE PERMISSION TO READ \"data/\"\n DECLARE PERMISSION TO WRITE \"out/\"\n DECLARE PERMISSION TO SPEAK WITH \"api.example.com\"\n DECLARE PERMISSION TO ASK THE WORLD\n DECLARE PERMISSION TO SUMMON \"reports.weekly\"\n\nThe manifest is collected from the scroll's top-level decrees before the\nrun begins. It never widens what the host allows: the effective grant is\nalways *host policy intersect manifest*. A scroll that reaches for a\npower it did not declare is counselled and stopped with a\n``SandboxViolation``.\n\nImported scrolls contribute their own manifests; grants compose by union\n(a run may use any power granted by any scroll it breathes in). Relative\npath patterns are resolved against the directory of the scroll that\ndeclares them.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any\nfrom urllib.parse import urlparse\n\n__all__ = [\n \"PermissionManifest\",\n \"collect_manifest\",\n \"POWERS\",\n]\n\n# The five declared powers, in the order they read in counsel.\nPOWERS = (\"read\", \"write\", \"network\", \"stdin\", \"summon\")\n\n# AST node class name we collect from, so this module never imports the\n# parser or interpreter (no import cycles).\n_DECLARE_PERMISSION_NODE = \"DeclarePermission\"\n\n\ndef _node_is_permission(stmt: Any) -> bool:\n return type(stmt).__name__ == _DECLARE_PERMISSION_NODE\n\n\n@dataclass\nclass PermissionManifest:\n \"\"\"The declared powers of one scroll or one whole run.\n\n Path patterns are stored as absolute directory prefixes. A pattern\n naming a file grants that exact file; a pattern naming a directory\n grants everything beneath it.\n \"\"\"\n\n read_paths: tuple[str, ...] = ()\n write_paths: tuple[str, ...] = ()\n hosts: tuple[str, ...] = ()\n stdin: bool = False\n summons: tuple[str, ...] = ()\n\n def __bool__(self) -> bool:\n return bool(\n self.read_paths\n or self.write_paths\n or self.hosts\n or self.stdin\n or self.summons\n )\n\n # -- composition ----------------------------------------------------\n\n def merge(self, other: \"PermissionManifest\") -> \"PermissionManifest\":\n \"\"\"Union two manifests: grants only ever grow by import.\"\"\"\n def _union(a: tuple[str, ...], b: tuple[str, ...]) -> tuple[str, ...]:\n seen: list[str] = []\n for item in (*a, *b):\n if item not in seen:\n seen.append(item)\n return tuple(seen)\n\n return PermissionManifest(\n read_paths=_union(self.read_paths, other.read_paths),\n write_paths=_union(self.write_paths, other.write_paths),\n hosts=_union(self.hosts, other.hosts),\n stdin=self.stdin or other.stdin,\n summons=_union(self.summons, other.summons),\n )\n\n # -- enforcement ----------------------------------------------------\n\n @staticmethod\n def _under(path: str, granted: tuple[str, ...]) -> bool:\n try:\n resolved = os.path.realpath(path)\n except OSError:\n return False\n for base in granted:\n if resolved == base or resolved.startswith(base + os.sep):\n return True\n return False\n\n def allows_read(self, path: str) -> bool:\n return self._under(path, self.read_paths)\n\n def allows_write(self, path: str) -> bool:\n return self._under(path, self.write_paths)\n\n def allows_host(self, url: str) -> bool:\n try:\n host = (urlparse(url).hostname or \"\").lower()\n except (ValueError, AttributeError):\n return False\n return any(host == granted or host.endswith(\".\" + granted)\n for granted in self.hosts)\n\n def allows_summon(self, verb: str) -> bool:\n return any(verb == name or verb.startswith(name + \".\")\n for name in self.summons)\n\n # -- machine interfaces ----------------------------------------------\n\n def to_json(self) -> dict:\n \"\"\"Stable shape for agents: `godcode permissions --json`.\"\"\"\n return {\n \"read\": list(self.read_paths),\n \"write\": list(self.write_paths),\n \"network\": list(self.hosts),\n \"stdin\": self.stdin,\n \"summon\": list(self.summons),\n }\n\n def describe(self) -> list[str]:\n \"\"\"One human line per granted power, for counsel and CLI output.\"\"\"\n lines: list[str] = []\n for path in self.read_paths:\n lines.append(f\"may read from {path}\")\n for path in self.write_paths:\n lines.append(f\"may write to {path}\")\n for host in self.hosts:\n lines.append(f\"may speak with {host}\")\n if self.stdin:\n lines.append(\"may ask the outer world\")\n for name in self.summons:\n lines.append(f\"may summon {name}\")\n return lines\n\n\ndef collect_manifest(statements: list, base_dir: str | Path | None) -> PermissionManifest:\n \"\"\"Gather DECLARE PERMISSION decrees from top-level statements.\n\n Looks at the scroll's top level and inside any top-level creation\n blocks. ``base_dir`` resolves relative path patterns to absolute\n prefixes; ``None`` resolves them against the current working\n directory.\n \"\"\"\n base = Path(base_dir) if base_dir else Path.cwd()\n reads: list[str] = []\n writes: list[str] = []\n hosts: list[str] = []\n stdin = False\n summons: list[str] = []\n\n def _resolve(pattern: str) -> str:\n candidate = Path(pattern)\n if not candidate.is_absolute():\n candidate = base / candidate\n try:\n return os.path.realpath(candidate)\n except OSError: # pragma: no cover - defensive\n return str(candidate)\n\n def _visit(stmts: list, inside_block: bool) -> None:\n nonlocal stdin\n for stmt in stmts:\n if _node_is_permission(stmt):\n power = getattr(stmt, \"power\", \"\")\n target = getattr(stmt, \"target\", None)\n if power == \"read\" and target:\n reads.append(_resolve(target))\n elif power == \"write\" and target:\n writes.append(_resolve(target))\n elif power == \"network\" and target:\n hosts.append(target.strip().lower())\n elif power == \"stdin\":\n stdin = True\n elif power == \"summon\" and target:\n summons.append(target.strip())\n elif (not inside_block\n and type(stmt).__name__ == \"CreationBlock\"):\n _visit(getattr(stmt, \"statements\", []), True)\n\n _visit(statements, False)\n\n def _dedupe(items: list[str]) -> tuple[str, ...]:\n seen: list[str] = []\n for item in items:\n if item not in seen:\n seen.append(item)\n return tuple(seen)\n\n return PermissionManifest(\n read_paths=_dedupe(reads),\n write_paths=_dedupe(writes),\n hosts=_dedupe(hosts),\n stdin=stdin,\n summons=_dedupe(summons),\n )\n","godcode/plugins.py":"\"\"\"Pillar 3 — plugins and the SUMMON foreign-function interface.\n\nA plugin is a plain Python module living in a plugins directory. On load it\nexposes::\n\n PLUGIN_API_VERSION = 1\n\n def register(interpreter):\n interpreter.register_plugin_verb(\"myns.myverb\", myverb, plugin=\"myns\")\n\nThe interpreter calls ``register(interpreter)`` at startup, so the plugin can\nadd new built-in verbs through the same ``_builtins`` mechanism the v2 core\nverbs use. God Code calls those verbs through the ``SUMMON`` FFI verb::\n\n SUMMON(\"myns.myverb\", arg1, arg2)\n\nPlugins are **trusted host code**: they run with the full power of Python,\nand SUMMON calls into them bypass any sandbox policy *by design*. Every\nplugin verb is recorded with ``trusted=True`` on the interpreter\n(``interpreter.plugin_verb_info``) so a future sandbox pillar can consult the\nmarker when deciding what a scroll may touch.\n\nSet ``GODCODE_NO_PLUGINS=1`` in the environment to skip plugin auto-loading\nentirely.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib.metadata\nimport importlib.util\nimport os\nimport re\nimport sys\nimport types\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nfrom godcode.values import Contract, RiteFunction, Symbol # noqa: F401 (re-exported for plugin authors)\n\nPLUGIN_API_VERSION = 1\n\"\"\"Version of the plugin contract this engine speaks.\"\"\"\n\nENTRY_POINT_GROUP = \"godcode_plugins\"\n\"\"\"importlib.metadata entry-point group for installed plugins (best-effort).\"\"\"\n\nDISABLE_ENV_VAR = \"GODCODE_NO_PLUGINS\"\n\"\"\"Set to \"1\" to skip plugin auto-loading entirely.\"\"\"\n\n\n# ---------------------------------------------------------------------------\n# discovery\n# ---------------------------------------------------------------------------\n\ndef default_plugin_dirs() -> list[Path]:\n \"\"\"Where plugins are looked for: ``./plugins`` then ``~/.godcode/plugins``.\"\"\"\n dirs = [Path.cwd() / \"plugins\"]\n try:\n dirs.append(Path.home() / \".godcode\" / \"plugins\")\n except Exception: # pragma: no cover - exotic platforms without a home\n pass\n return dirs\n\n\ndef _warn(message: str) -> None:\n print(f\"godcode: plugin warning: {message}\", file=sys.stderr)\n\n\ndef _iter_plugin_files(dirs: list[Path]):\n \"\"\"Yield ``(stem, path)`` for each candidate plugin file in *dirs*.\"\"\"\n for directory in dirs:\n try:\n if not directory.is_dir():\n continue\n entries = sorted(directory.iterdir())\n except OSError as exc:\n _warn(f\"cannot scan {directory}: {exc}\")\n continue\n for path in entries:\n if not path.is_file() or path.suffix != \".py\":\n continue\n stem = path.stem\n if stem == \"__init__\" or stem.startswith((\"_\", \".\")):\n continue\n yield stem, path\n\n\ndef _module_name_for(stem: str) -> str:\n safe = re.sub(r\"[^0-9a-zA-Z_]\", \"_\", stem)\n if not safe or safe[0].isdigit():\n safe = \"_\" + safe\n return f\"godcode_plugin_{safe}\"\n\n\ndef _import_from_path(stem: str, path: Path) -> types.ModuleType:\n \"\"\"Import the module at *path* without touching ``sys.path``.\"\"\"\n name = _module_name_for(stem)\n spec = importlib.util.spec_from_file_location(name, path)\n if spec is None or spec.loader is None: # pragma: no cover - defensive\n raise ImportError(f\"cannot build a module spec for {path}\")\n module = importlib.util.module_from_spec(spec)\n # NOTE: deliberately *not* cached in sys.modules — each interpreter gets a\n # freshly executed plugin module, so plugin state never leaks between runs.\n spec.loader.exec_module(module)\n return module\n\n\ndef _entry_point_plugins() -> dict[str, Any]:\n \"\"\"Best-effort load of the ``godcode_plugins`` entry-point group.\"\"\"\n found: dict[str, Any] = {}\n try:\n entry_points = importlib.metadata.entry_points()\n except Exception as exc: # pragma: no cover - metadata backend missing\n _warn(f\"could not read entry points: {exc}\")\n return found\n try:\n if hasattr(entry_points, \"select\"): # Python 3.10+ EntryPoints\n selected = entry_points.select(group=ENTRY_POINT_GROUP)\n else: # pragma: no cover - legacy dict-style interface\n selected = entry_points.get(ENTRY_POINT_GROUP, ())\n except Exception as exc:\n _warn(f\"could not select {ENTRY_POINT_GROUP!r} entry points: {exc}\")\n return found\n for ep in selected:\n try:\n found[ep.name] = ep.load()\n except Exception as exc:\n _warn(f\"entry-point plugin {ep.name!r} failed to load: {exc}\")\n return found\n\n\ndef discover_plugins(dirs: list[Path] | None = None) -> dict[str, Any]:\n \"\"\"Import every plugin module found and return ``{name: module}``.\n\n *dirs* defaults to :func:`default_plugin_dirs`, with the\n ``godcode_plugins`` entry-point group consulted afterwards (later sources\n shadow earlier ones on name clashes).\n\n A module that fails to import is skipped with a warning on stderr — a\n broken plugin never crashes the host run.\n \"\"\"\n if dirs is None:\n dirs = default_plugin_dirs()\n discovered: dict[str, Any] = {}\n for stem, path in _iter_plugin_files(dirs):\n try:\n discovered[stem] = _import_from_path(stem, path)\n except Exception as exc:\n _warn(f\"plugin {path} failed to import ({exc}). Skipped\")\n for name, module in _entry_point_plugins().items():\n discovered[name] = module\n return discovered\n\n\ndef load_plugins(interpreter, dirs: list[Path] | None = None) -> list[str]:\n \"\"\"Discover plugins and call ``register(interpreter)`` on each.\n\n Returns the names of the plugins whose ``register()`` ran cleanly. A\n missing ``register()``, a ``PLUGIN_API_VERSION`` mismatch, or an\n exception inside ``register()`` only produces a stderr warning — never\n an exception, so startup always survives a bad plugin.\n \"\"\"\n loaded: list[str] = []\n for name, module in discover_plugins(dirs).items():\n api = getattr(module, \"PLUGIN_API_VERSION\", 1)\n if api != PLUGIN_API_VERSION:\n _warn(\n f\"plugin {name!r} speaks API version {api}, \"\n f\"this engine speaks {PLUGIN_API_VERSION}. Skipped\"\n )\n continue\n register = getattr(module, \"register\", None)\n if not callable(register):\n _warn(f\"plugin {name!r} exposes no register(interpreter). Skipped\")\n continue\n try:\n register(interpreter)\n except Exception as exc:\n _warn(f\"plugin {name!r} register() failed ({exc}). Skipped\")\n continue\n loaded.append(name)\n return loaded\n\n\n# ---------------------------------------------------------------------------\n# value conversion: God Code <-> Python\n# ---------------------------------------------------------------------------\n#\n# God Code values already *are* Python objects inside the interpreter, so most\n# conversions are the identity. The table below is the contract plugin\n# authors can rely on:\n#\n# God Code number <-> Python int / float (identity)\n# God Code string <-> Python str (identity)\n# God Code boolean <-> Python bool (identity)\n# God Code void <-> Python None (identity)\n# God Code list <-> Python list (recursive)\n# God Code symbol <-> Symbol, a str subclass (identity)\n# God Code contract <-> Contract (opaque, identity)\n# God Code rite <-> RiteFunction (opaque, identity)\n#\n# Anything else a plugin returns (dict, set, tuple, custom objects, ...)\n# passes through opaquely, except tuples which become lists recursively.\n# REVEAL renders opaque values with str().\n\ndef to_python(value: Any) -> Any:\n \"\"\"Convert a God Code value to the Python value a plugin receives.\n\n Identity for every documented God Code value; see the table above.\n \"\"\"\n return value\n\n\ndef to_godcode(value: Any) -> Any:\n \"\"\"Convert a plugin's Python return value back into a God Code value.\n\n Tuples become lists (recursively); every other value passes through\n as-is. Values with no God Code counterpart (dicts, sets, custom\n objects) travel opaquely and are rendered with ``str()`` by REVEAL.\n \"\"\"\n if isinstance(value, tuple):\n return [to_godcode(item) for item in value]\n if isinstance(value, list):\n return [to_godcode(item) for item in value]\n return value\n\n\n# ---------------------------------------------------------------------------\n# interpreter mixin helpers (kept here so interpreter.py stays small)\n# ---------------------------------------------------------------------------\n\ndef make_verb_adapter(name: str, func: Callable[..., Any]):\n \"\"\"Wrap a plain ``func(*args)`` into the ``(args, line)`` builtin shape.\n\n Arguments are converted God Code -> Python, the return value Python ->\n God Code. A plugin exception becomes a line-numbered GodRuntimeError;\n divine errors pass through untouched.\n \"\"\"\n from godcode.errors import GodCodeError, GodRuntimeError\n\n def _adapter(args: list, line):\n py_args = [to_python(arg) for arg in args]\n try:\n result = func(*py_args)\n except GodCodeError:\n raise\n except Exception as exc:\n raise GodRuntimeError(\n f\"The '{name}' verb faltered in the outer world: {exc}\",\n line,\n ) from exc\n return to_godcode(result)\n\n _adapter.__name__ = f\"plugin:{name}\"\n _adapter.__doc__ = getattr(func, \"__doc__\", None)\n return _adapter\n","godcode/registry.py":"\"\"\"Pillar 2 — the Scroll Registry: installable, versioned God Code scrolls.\n\nA scroll is a directory holding a ``scroll.toml`` manifest beside its entry\n``.god`` file. The local registry (``registry/`` at the repo root) is the\nsource of truth: ``publish`` copies a scroll into\n``registry/scrolls///`` and records it in\n``registry/index.json``; ``install`` copies from there into\n``~/.godcode/scrolls///`` (user-global) or\n``.godcode/scrolls/`` (project-local, wins over user-global).\n\nrequires-python is >=3.10, so ``tomllib`` (3.11+) is off the table: the\nmanifest parser below is a hand-rolled TOML subset covering exactly the\nkeys this registry defines.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nimport os\nimport re\nimport shutil\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nfrom typing import Any, Optional\n\ntry: # the package version is the engine version; tolerate odd import orders\n from godcode import __version__ as ENGINE_VERSION\nexcept Exception: # pragma: no cover - defensive\n ENGINE_VERSION = \"2.0.0\"\n\n# ---------------------------------------------------------------------------\n# errors\n\n\nclass ScrollError(Exception):\n \"\"\"Raised when a manifest, publish, install, or lookup fails.\"\"\"\n\n\nclass ScrollNotFoundError(ScrollError):\n \"\"\"Raised when a scroll cannot be found in a registry.\n\n Kept distinct from ScrollError so the CLI can fall back from the local\n registry to the remote one on exactly this failure.\n \"\"\"\n\n\n# ---------------------------------------------------------------------------\n# manifest parsing (TOML subset: key = \"value\" pairs, # comments)\n\n\nMANIFEST_KEYS = frozenset(\n {\"name\", \"version\", \"author\", \"description\", \"entry\", \"godcode\",\n \"dependencies\"}\n)\nREQUIRED_KEYS = frozenset(\n {\"name\", \"version\", \"author\", \"description\", \"entry\", \"godcode\"}\n) # dependencies is optional\n_NAME_RE = re.compile(r\"^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$\")\n_SEMVER_RE = re.compile(r\"^(\\d+)\\.(\\d+)\\.(\\d+)$\")\n_REQ_CLAUSE_RE = re.compile(r\"^(>=|<=|==|!=|>|<)\\s*(\\d+(?:\\.\\d+){0,2})$\")\n\n# Human-readable blurbs shown in errors; keep them short.\n_KEY_HINTS = {\n \"name\": 'e.g. name = \"json-tools\"',\n \"version\": 'e.g. version = \"1.0.0\"',\n \"author\": 'e.g. author = \"Ama Seretse\"',\n \"description\": 'e.g. description = \"JSON helpers written in God Code\"',\n \"entry\": 'e.g. entry = \"json-tools.god\"',\n \"godcode\": 'e.g. godcode = \">=2.0\"',\n \"dependencies\": 'e.g. dependencies = \"json-tools >= 1.0.0, dates\"',\n}\n\n\ndef _strip_comment(line: str) -> str:\n \"\"\"Cut a trailing ``#`` comment, ignoring ``#`` inside quoted strings.\"\"\"\n in_quote: str | None = None\n i = 0\n while i < len(line):\n ch = line[i]\n if in_quote:\n if ch == \"\\\\\" and in_quote == '\"':\n i += 2\n continue\n if ch == in_quote:\n in_quote = None\n elif ch in ('\"', \"'\"):\n in_quote = ch\n elif ch == \"#\":\n return line[:i]\n i += 1\n return line\n\n\ndef _parse_toml_value(raw: str, source: str, lineno: int) -> str:\n \"\"\"Parse a quoted TOML string value (double- or single-quoted).\"\"\"\n if len(raw) >= 2 and raw[0] == '\"' and raw[-1] == '\"':\n out: list[str] = []\n i = 1\n while i < len(raw) - 1:\n ch = raw[i]\n if ch == \"\\\\\":\n i += 1\n if i >= len(raw) - 1:\n raise ScrollError(\n f\"{source}:{lineno}: dangling backslash in manifest value\"\n )\n esc = raw[i]\n out.append({\"n\": \"\\n\", \"t\": \"\\t\", \"r\": \"\\r\"}.get(esc, esc))\n else:\n out.append(ch)\n i += 1\n return \"\".join(out)\n if len(raw) >= 2 and raw[0] == \"'\" and raw[-1] == \"'\":\n return raw[1:-1] # literal string: no escapes\n raise ScrollError(\n f\"{source}:{lineno}: manifest values must be quoted strings \"\n f\"(got {raw!r})\"\n )\n\n\ndef parse_manifest(text: str, source: str = \"\") -> dict[str, str]:\n \"\"\"Parse and validate a ``scroll.toml`` manifest. Returns a plain dict.\"\"\"\n data: dict[str, str] = {}\n for lineno, raw_line in enumerate(text.splitlines(), 1):\n line = _strip_comment(raw_line).strip()\n if not line:\n continue\n if \"=\" not in line:\n raise ScrollError(\n f\"{source}:{lineno}: expected `key = \\\"value\\\"`, got {line!r}\"\n )\n key, _, value = line.partition(\"=\")\n key, value = key.strip(), value.strip()\n if not re.fullmatch(r\"[A-Za-z_][A-Za-z0-9_-]*\", key):\n raise ScrollError(f\"{source}:{lineno}: bad manifest key {key!r}\")\n if key in data:\n raise ScrollError(\n f\"{source}:{lineno}: duplicate manifest key {key!r}\"\n )\n data[key] = _parse_toml_value(value, source, lineno)\n\n unknown = sorted(set(data) - MANIFEST_KEYS)\n if unknown:\n raise ScrollError(\n f\"{source}: unknown manifest key(s) {', '.join(unknown)}; \"\n \"known keys: \" + \", \".join(sorted(MANIFEST_KEYS))\n )\n missing = sorted(REQUIRED_KEYS - set(data))\n if missing:\n hints = \"; \".join(_KEY_HINTS[k] for k in missing)\n raise ScrollError(\n f\"{source}: missing required manifest key(s) \"\n f\"{', '.join(missing)} ({hints})\"\n )\n\n name = data[\"name\"]\n if not _NAME_RE.match(name):\n raise ScrollError(\n f\"{source}: name {name!r} must be lowercase letters, digits and \"\n \"hyphens, starting with a letter\"\n )\n parse_semver(data[\"version\"], source=source) # validates\n entry = data[\"entry\"]\n if not entry or \"/\" in entry or \"\\\\\" in entry or entry.startswith(\".\"):\n raise ScrollError(\n f\"{source}: entry must be a plain filename, got {entry!r}\"\n )\n req = data[\"godcode\"]\n if not requirement_satisfied(req):\n raise ScrollError(\n f\"{source}: this scroll needs God Code {req}, \"\n f\"but the engine is {ENGINE_VERSION}\"\n )\n if \"dependencies\" in data:\n parse_dependencies(data[\"dependencies\"], source=source)\n return data\n\n\ndef read_manifest(path: str | os.PathLike) -> dict[str, str]:\n \"\"\"Read, parse, and validate the manifest at ``path``.\"\"\"\n path = Path(path)\n try:\n text = path.read_text(encoding=\"utf-8\")\n except OSError as exc:\n raise ScrollError(f\"cannot read manifest {path}: {exc}\") from exc\n return parse_manifest(text, source=str(path))\n\n\n# ---------------------------------------------------------------------------\n# semver-ish versions (X.Y.Z only)\n\n\ndef parse_semver(text: str, source: str = \"\") -> tuple[int, int, int]:\n \"\"\"Parse ``X.Y.Z``; raise ScrollError on anything else.\"\"\"\n match = _SEMVER_RE.match(text.strip())\n if not match:\n raise ScrollError(\n f\"{source}: version must look like X.Y.Z, got {text!r}\"\n )\n return int(match.group(1)), int(match.group(2)), int(match.group(3))\n\n\ndef compare_versions(a: str, b: str) -> int:\n \"\"\"-1 if a < b, 0 if equal, 1 if a > b (numeric per component).\"\"\"\n ta, tb = parse_semver(a), parse_semver(b)\n return (ta > tb) - (ta < tb)\n\n\ndef latest_version(versions: list[str]) -> str:\n \"\"\"The highest version; ties are impossible (versions are unique).\"\"\"\n if not versions:\n raise ScrollError(\"no versions to choose from\")\n best = versions[0]\n for v in versions[1:]:\n if compare_versions(v, best) > 0:\n best = v\n return best\n\n\n# ---------------------------------------------------------------------------\n# godcode version requirements, e.g. \">=2.0, <4\"\n\n\ndef _parse_requirement(req: str) -> list[tuple[str, tuple[int, ...]]]:\n clauses: list[tuple[str, tuple[int, ...]]] = []\n for part in req.split(\",\"):\n part = part.strip()\n if not part:\n raise ScrollError(f\"bad godcode requirement {req!r}: empty clause\")\n match = _REQ_CLAUSE_RE.match(part)\n if not match:\n raise ScrollError(\n f\"bad godcode requirement {req!r}: expected e.g. \"\n f\"'>=2.0', got {part!r}\"\n )\n op, ver = match.group(1), match.group(2)\n clauses.append((op, tuple(int(x) for x in ver.split(\".\"))))\n return clauses\n\n\ndef _pad(parts: tuple[int, ...], length: int) -> tuple[int, ...]:\n return parts + (0,) * (length - len(parts))\n\n\ndef _clauses_satisfied(\n req: str, engine: str, clauses: list[tuple[str, tuple[int, ...]]]\n) -> bool:\n engine_parts = _pad(tuple(int(x) for x in engine.split(\".\")), 3)\n for op, want in clauses:\n want = _pad(want, 3)\n if op == \">=\" and not (engine_parts >= want):\n return False\n if op == \"<=\" and not (engine_parts <= want):\n return False\n if op == \"==\" and not (engine_parts == want):\n return False\n if op == \"!=\" and not (engine_parts != want):\n return False\n if op == \">\" and not (engine_parts > want):\n return False\n if op == \"<\" and not (engine_parts < want):\n return False\n return True\n\n\ndef requirement_satisfied(req: str, engine: str = ENGINE_VERSION) -> bool:\n \"\"\"True when ``engine`` satisfies a requirement like ``>=2.0``.\"\"\"\n return _clauses_satisfied(req, engine, _parse_requirement(req))\n\n\n# ---------------------------------------------------------------------------\n# scroll dependencies, e.g. dependencies = \"json-tools >= 1.0.0, dates\"\n\n\ndef parse_dependencies(\n spec: str, source: str = \"\"\n) -> list[tuple[str, str | None]]:\n \"\"\"Parse a manifest ``dependencies`` value.\n\n Returns ``[(name, requirement)]``; requirement is None when the clause\n names the scroll with no version constraint. A clause carries at most\n one requirement clause (``>= 1.0.0``); commas separate dependencies.\n \"\"\"\n if not spec.strip():\n return []\n deps: list[tuple[str, str | None]] = []\n for part in spec.split(\",\"):\n part = part.strip()\n if not part:\n raise ScrollError(\n f\"{source}: bad dependencies {spec!r}: empty clause\"\n )\n tokens = part.split()\n name = tokens[0]\n if not _NAME_RE.match(name):\n raise ScrollError(\n f\"{source}: bad dependency name {name!r} in \"\n f\"dependencies {spec!r}\"\n )\n requirement = \" \".join(tokens[1:]) or None\n if requirement is not None:\n _parse_requirement(requirement) # validates the clause shape\n if name in {n for n, _ in deps}:\n raise ScrollError(\n f\"{source}: duplicate dependency {name!r} in \"\n f\"dependencies {spec!r}\"\n )\n deps.append((name, requirement))\n return deps\n\n\ndef render_manifest(manifest: dict[str, str]) -> str:\n \"\"\"Render a manifest dict as ``scroll.toml`` text.\"\"\"\n lines: list[str] = []\n for key in (\"name\", \"version\", \"author\", \"description\", \"entry\",\n \"godcode\", \"dependencies\"):\n if key in manifest:\n value = manifest[key].replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"')\n lines.append(f'{key} = \"{value}\"')\n return \"\\n\".join(lines) + \"\\n\"\n\n\n# ---------------------------------------------------------------------------\n# the registry\n\n\ndef _default_registry_root() -> Path:\n return Path(__file__).resolve().parent.parent / \"registry\"\n\n\ndef _sha256_file(path: Path) -> str:\n \"\"\"Hex sha256 of a file's bytes.\"\"\"\n digest = hashlib.sha256()\n with open(path, \"rb\") as handle:\n for chunk in iter(lambda: handle.read(65536), b\"\"):\n digest.update(chunk)\n return digest.hexdigest()\n\n\ndef _checksum_tree(root: Path) -> dict[str, str]:\n \"\"\"sha256 for every file under ``root``, keyed by relative path.\"\"\"\n checksums: dict[str, str] = {}\n for path in sorted(root.rglob(\"*\")):\n if path.is_file():\n checksums[path.relative_to(root).as_posix()] = _sha256_file(path)\n return checksums\n\n\nclass ScrollRegistry:\n \"\"\"Local scroll registry: publish into ``registry/``, install from it.\"\"\"\n\n def __init__(\n self,\n registry_root: str | os.PathLike | None = None,\n home: str | os.PathLike | None = None,\n project_dir: str | os.PathLike | None = None,\n ) -> None:\n self.registry_root = Path(registry_root or _default_registry_root())\n self.scrolls_root = self.registry_root / \"scrolls\"\n self.index_path = self.registry_root / \"index.json\"\n self.home = Path(home or Path.home()) # honors $HOME, monkeypatchable\n self.user_dir = self.home / \".godcode\" / \"scrolls\"\n self.project_dir = Path(project_dir or Path.cwd())\n self.project_scrolls_dir = self.project_dir / \".godcode\" / \"scrolls\"\n\n # ------------------------------------------------------------- index ---\n\n def load_index(self) -> dict[str, Any]:\n \"\"\"The published index; {} when nothing has been published yet.\"\"\"\n if not self.index_path.is_file():\n return {}\n try:\n return json.loads(self.index_path.read_text(encoding=\"utf-8\"))\n except (OSError, json.JSONDecodeError) as exc:\n raise ScrollError(\n f\"cannot read registry index {self.index_path}: {exc}\"\n ) from exc\n\n def _save_index(self, index: dict[str, Any]) -> None:\n self.index_path.parent.mkdir(parents=True, exist_ok=True)\n self.index_path.write_text(\n json.dumps(index, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\"\n )\n\n # ----------------------------------------------------------- publish ---\n\n def publish(self, scroll_dir: str | os.PathLike) -> dict[str, str]:\n \"\"\"Validate a scroll directory and publish it into the registry.\n\n Copies ``scroll_dir`` to ``registry/scrolls///`` and\n updates ``index.json``. Refuses when that exact version is already\n published. Returns the validated manifest.\n \"\"\"\n src = Path(scroll_dir)\n if not src.is_dir():\n raise ScrollError(f\"publish: {src} is not a directory\")\n manifest_path = src / \"scroll.toml\"\n if not manifest_path.is_file():\n raise ScrollError(f\"publish: {src} holds no scroll.toml manifest\")\n manifest = read_manifest(manifest_path)\n\n name, version = manifest[\"name\"], manifest[\"version\"]\n if src.name != name:\n raise ScrollError(\n f\"publish: manifest name {name!r} does not match directory \"\n f\"name {src.name!r}\"\n )\n entry_path = src / manifest[\"entry\"]\n if not entry_path.is_file():\n raise ScrollError(\n f\"publish: entry file {manifest['entry']!r} not found in {src}\"\n )\n\n index = self.load_index()\n published = index.get(name, {}).get(\"versions\", [])\n if version in published:\n raise ScrollError(\n f\"publish: {name} {version} is already in the registry. \"\n \"Bump the version to publish again\"\n )\n\n dest = self.scrolls_root / name / version\n if dest.exists():\n raise ScrollError(\n f\"publish: {dest} already exists on disk but is not indexed; \"\n \"remove it or repair the index first\"\n )\n shutil.copytree(src, dest)\n\n versions = sorted(set(published) | {version},\n key=lambda v: parse_semver(v))\n index[name] = {\n \"name\": name,\n \"versions\": versions,\n \"latest\": latest_version(versions),\n \"manifest\": manifest,\n \"checksums\": {\n **index.get(name, {}).get(\"checksums\", {}),\n version: _checksum_tree(dest),\n },\n }\n self._save_index(index)\n return manifest\n\n # ----------------------------------------------------------- install ---\n\n def _remote_client(self, remote: bool | Any) -> Any | None:\n \"\"\"A RemoteRegistry when ``remote`` asks for one, else None.\n\n ``remote`` may be True (build a default client), a RemoteRegistry\n instance (use it), or False/None (local only).\n \"\"\"\n if remote is True:\n from godcode.remote_registry import RemoteRegistry\n\n return RemoteRegistry()\n return remote or None\n\n def resolve_version(self, name: str, version: str | None = None) -> str:\n \"\"\"The version to install: ``version`` if given, else the latest.\"\"\"\n index = self.load_index()\n entry = index.get(name)\n if entry is None:\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the registry \"\n f\"({self.registry_root})\"\n )\n versions: list[str] = entry[\"versions\"]\n if version is None:\n return entry[\"latest\"]\n if version not in versions:\n raise ScrollError(\n f\"install: {name} has no version {version!r}; \"\n f\"published: {', '.join(versions)}\"\n )\n return version\n\n def _choose_source(\n self,\n name: str,\n requirement: str | None,\n remote_client: Any | None,\n stack: tuple[str, ...],\n ) -> tuple[str, str, dict[str, Any] | None]:\n \"\"\"Pick (version, source, info) for ``name`` under ``requirement``.\n\n ``requirement`` is None (any version), ``==X.Y.Z`` (exact, from\n ``--version`` or a pinned dependency), or a dep clause like\n ``>= 1.0.0``. The local index always wins; the remote registry is\n consulted only when a client was passed and the local index cannot\n serve the requirement.\n \"\"\"\n context = f\" (needed by {' -> '.join(stack)})\" if stack else \"\"\n index = self.load_index()\n entry = index.get(name)\n\n if requirement is not None and requirement.startswith(\"==\"):\n exact = requirement[2:].strip()\n if entry is not None:\n if exact in entry[\"versions\"]:\n return exact, \"local\", None\n if remote_client is None:\n raise ScrollError(\n f\"install: {name} has no version {exact!r}; \"\n f\"published: {', '.join(entry['versions'])}\"\n )\n # else: fall through to the remote lookup below\n elif entry is not None:\n matching = [\n v\n for v in entry[\"versions\"]\n if requirement is None\n or requirement_satisfied(requirement, v)\n ]\n if matching:\n return latest_version(matching), \"local\", None\n\n if remote_client is not None:\n try:\n info, matching = remote_client.versions_satisfying(\n name, requirement\n )\n except ScrollError as exc:\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the local registry and the \"\n f\"remote registry cannot serve it: {exc}{context}\"\n ) from exc\n if matching:\n return matching[0], \"remote\", info\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the local registry and the \"\n f\"remote registry has no version matching \"\n f\"{requirement or 'any'!r}{context}\"\n )\n if entry is None:\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the registry \"\n f\"({self.registry_root}){context}\"\n )\n raise ScrollNotFoundError(\n f\"install: {name!r} has no published version matching \"\n f\"{requirement!r}{context}\"\n )\n\n def _manifest_for(\n self,\n name: str,\n version: str,\n source: str,\n info: dict[str, Any] | None,\n ) -> dict[str, str]:\n \"\"\"The validated manifest for a chosen (name, version).\"\"\"\n if source == \"local\":\n return read_manifest(self.scrolls_root / name / version / \"scroll.toml\")\n from godcode.remote_registry import synthesized_manifest\n\n manifest = synthesized_manifest(name, info or {}, version)\n return parse_manifest(\n render_manifest(manifest), source=f\"\"\n )\n\n def _plan_install(\n self,\n name: str,\n requirement: str | None,\n stack: tuple[str, ...],\n remote_client: Any | None,\n plan: dict[str, dict[str, Any]],\n ) -> None:\n \"\"\"Fill ``plan`` (insertion-ordered, dependencies first) with the\n scrolls this install needs, resolving versions and detecting cycles.\n \"\"\"\n if name in stack:\n cycle = \" -> \".join([*stack, name])\n raise ScrollError(\n f\"dependency cycle detected: {cycle}. A scroll cannot depend \"\n \"on itself through a circle of dependencies; break the \"\n \"circle and publish again.\"\n )\n if name in plan:\n chosen = plan[name][\"version\"]\n if requirement is None or requirement_satisfied(requirement, chosen):\n return\n raise ScrollError(\n f\"install: version conflict for {name!r}: this install \"\n f\"already resolved {chosen}, which does not satisfy \"\n f\"{requirement!r}\"\n )\n version, source, info = self._choose_source(\n name, requirement, remote_client, stack\n )\n manifest = self._manifest_for(name, version, source, info)\n for dep_name, dep_req in parse_dependencies(\n manifest.get(\"dependencies\", \"\"), source=f\"<{name} {version}>\"\n ):\n self._plan_install(dep_name, dep_req, stack + (name,),\n remote_client, plan)\n plan[name] = {\n \"name\": name,\n \"version\": version,\n \"source\": source,\n \"info\": info,\n \"manifest\": manifest,\n }\n\n def _dependency_tree(\n self, manifest: dict[str, str], plan: dict[str, dict[str, Any]]\n ) -> dict[str, str]:\n \"\"\"Resolved {dependency name: version} for a receipt.\"\"\"\n tree: dict[str, str] = {}\n for dep_name, _ in parse_dependencies(manifest.get(\"dependencies\", \"\")):\n if dep_name in plan:\n tree[dep_name] = plan[dep_name][\"version\"]\n return tree\n\n def _verify_checksums(self, name: str, version: str, src: Path) -> dict[str, str]:\n \"\"\"Check published files against the checksums recorded on publish.\n\n Returns the recorded checksums (for the receipt). Index entries\n written before checksums existed carry none and are trusted as-is.\n \"\"\"\n index = self.load_index()\n recorded: dict[str, str] = (\n index.get(name, {}).get(\"checksums\", {}) or {}\n ).get(version, {})\n for rel, expected in recorded.items():\n path = src / rel\n if not path.is_file():\n raise ScrollError(\n f\"install: {name} {version} is missing published file \"\n f\"{rel!r} in the registry; republish the scroll\"\n )\n actual = _sha256_file(path)\n if actual != expected:\n raise ScrollError(\n f\"install: checksum mismatch for {name} {version} file \"\n f\"{rel!r}: the registry copy changed after publish \"\n f\"(expected {expected[:12]}..., got {actual[:12]}...). \"\n \"Republish the scroll to heal the registry.\"\n )\n return recorded\n\n def _write_install(\n self,\n name: str,\n version: str,\n project: bool,\n manifest: dict[str, str],\n *,\n source: str,\n checksums: dict[str, str],\n dependencies: dict[str, str],\n copy_from: Path | None = None,\n files: dict[str, str] | None = None,\n ) -> dict[str, Any]:\n \"\"\"Materialize one installed scroll directory and its receipt.\"\"\"\n base = self.project_scrolls_dir if project else self.user_dir\n dest = base / name / version\n if dest.exists():\n shutil.rmtree(dest)\n if copy_from is not None:\n shutil.copytree(copy_from, dest)\n else:\n dest.mkdir(parents=True)\n for rel, content in (files or {}).items():\n (dest / rel).write_text(content, encoding=\"utf-8\")\n\n receipt = {\n \"name\": name,\n \"version\": version,\n \"source\": source,\n \"location\": \"project\" if project else \"user\",\n \"installed_at\": datetime.now(timezone.utc).isoformat(),\n \"checksums\": checksums,\n \"dependencies\": dependencies,\n \"manifest\": manifest,\n }\n (dest / \"install.json\").write_text(\n json.dumps(receipt, indent=2, sort_keys=True) + \"\\n\",\n encoding=\"utf-8\",\n )\n return receipt\n\n def _install_local(\n self,\n name: str,\n version: str,\n manifest: dict[str, str],\n project: bool,\n dependency_tree: dict[str, str],\n ) -> dict[str, Any]:\n \"\"\"Install one planned scroll from the local registry directory.\"\"\"\n src = self.scrolls_root / name / version\n if not src.is_dir():\n raise ScrollError(\n f\"install: registry is missing files for {name} {version} \"\n f\"(expected {src})\"\n )\n checksums = self._verify_checksums(name, version, src)\n return self._write_install(\n name, version, project, manifest,\n source=\"local\", checksums=checksums,\n dependencies=dependency_tree, copy_from=src,\n )\n\n def _install_remote(\n self,\n name: str,\n version: str,\n manifest: dict[str, str],\n project: bool,\n remote_client: Any,\n dependency_tree: dict[str, str],\n ) -> dict[str, Any]:\n \"\"\"Install one planned scroll by downloading it from the remote.\"\"\"\n code, resolved = remote_client.fetch_code(name, version)\n entry_name = manifest[\"entry\"]\n manifest_text = render_manifest({**manifest, \"version\": resolved})\n checksums = {\n entry_name: hashlib.sha256(code.encode(\"utf-8\")).hexdigest(),\n \"scroll.toml\": hashlib.sha256(\n manifest_text.encode(\"utf-8\")).hexdigest(),\n }\n return self._write_install(\n name, resolved, project, {**manifest, \"version\": resolved},\n source=\"remote\", checksums=checksums,\n dependencies=dependency_tree,\n files={entry_name: code, \"scroll.toml\": manifest_text},\n )\n\n def install(\n self,\n name: str,\n version: str | None = None,\n project: bool = False,\n remote: bool | Any = False,\n ) -> dict[str, Any]:\n \"\"\"Install a scroll and its dependencies into an install directory.\n\n ``project=True`` installs under ``.godcode/scrolls/`` in the current\n (or given) project directory; otherwise under ``~/.godcode/scrolls/``.\n Dependencies declared in the manifest are resolved recursively, the\n local index first and then the remote registry when ``remote`` is a\n client (or True for a default client); cycles are refused with a\n clear error. Returns the top-level install receipt.\n \"\"\"\n remote_client = self._remote_client(remote)\n plan: dict[str, dict[str, Any]] = {}\n self._plan_install(\n name,\n f\"=={version}\" if version is not None else None,\n (),\n remote_client,\n plan,\n )\n receipts: list[dict[str, Any]] = []\n for item in plan.values():\n tree = self._dependency_tree(item[\"manifest\"], plan)\n if item[\"source\"] == \"local\":\n receipts.append(\n self._install_local(\n item[\"name\"], item[\"version\"], item[\"manifest\"],\n project, tree,\n )\n )\n else:\n assert remote_client is not None # chosen by _choose_source\n receipts.append(\n self._install_remote(\n item[\"name\"], item[\"version\"], item[\"manifest\"],\n project, remote_client, tree,\n )\n )\n return receipts[-1]\n\n # --------------------------------------------------------- uninstall ---\n\n def uninstall(\n self, name: str, version: str | None = None\n ) -> list[dict[str, str]]:\n \"\"\"Remove an installed scroll (one version, or every installed\n version when ``version`` is None) from both install scopes.\"\"\"\n removed: list[dict[str, str]] = []\n for base, location in (\n (self.project_scrolls_dir, \"project\"),\n (self.user_dir, \"user\"),\n ):\n name_dir = base / name\n if not name_dir.is_dir():\n continue\n if version is None:\n targets = sorted(d for d in name_dir.iterdir() if d.is_dir())\n else:\n single = name_dir / version\n targets = [single] if single.is_dir() else []\n for target in targets:\n shutil.rmtree(target)\n removed.append(\n {\"name\": name, \"version\": target.name,\n \"location\": location}\n )\n if version is None and name_dir.is_dir() and not any(\n name_dir.iterdir()\n ):\n name_dir.rmdir()\n if not removed:\n raise ScrollError(\n f\"uninstall: {name!r}\"\n + (f\" {version}\" if version else \"\")\n + \" is not installed\"\n )\n return removed\n\n # ------------------------------------------------------------ update ---\n\n def _newest_available(\n self, name: str, remote_client: Any | None\n ) -> tuple[str | None, str]:\n \"\"\"(newest version known anywhere, source) for ``name``.\"\"\"\n best: str | None = None\n source = \"local\"\n entry = self.load_index().get(name)\n if entry:\n best = entry[\"latest\"]\n if remote_client is not None:\n try:\n info, matching = remote_client.versions_satisfying(name, None)\n except ScrollError:\n matching = []\n info = {}\n if matching and (\n best is None or compare_versions(matching[0], best) > 0\n ):\n best, source = matching[0], \"remote\"\n return best, source\n\n def update(\n self,\n name: str | None = None,\n project: bool = False,\n remote: bool | Any = False,\n ) -> list[dict[str, Any]]:\n \"\"\"Update one installed scroll (or all, when ``name`` is None) to the\n newest version known to the local index or the remote registry.\"\"\"\n remote_client = self._remote_client(remote)\n rows = {r[\"name\"]: r for r in self.list_installed()}\n names = [name] if name is not None else sorted(rows)\n if name is not None and name not in rows:\n raise ScrollError(f\"update: {name!r} is not installed\")\n results: list[dict[str, Any]] = []\n for scroll_name in names:\n installed = rows[scroll_name][\"latest\"]\n available, _source = self._newest_available(scroll_name,\n remote_client)\n if available is not None and compare_versions(available,\n installed) > 0:\n receipt = self.install(\n scroll_name, version=available, project=project,\n remote=remote,\n )\n results.append(\n {\"name\": scroll_name, \"from\": installed,\n \"to\": available, \"source\": receipt[\"source\"]}\n )\n else:\n results.append(\n {\"name\": scroll_name, \"from\": installed,\n \"to\": installed, \"up_to_date\": True}\n )\n return results\n\n # -------------------------------------------------------------- read ---\n\n def _installed_versions(self, base: Path) -> dict[str, list[str]]:\n \"\"\"name -> sorted installed versions found under ``base``.\"\"\"\n found: dict[str, list[str]] = {}\n if not base.is_dir():\n return found\n for name_dir in sorted(base.iterdir()):\n if not name_dir.is_dir():\n continue\n for ver_dir in sorted(name_dir.iterdir()):\n if not ver_dir.is_dir():\n continue\n if not (ver_dir / \"scroll.toml\").is_file():\n continue\n try:\n parse_semver(ver_dir.name)\n except ScrollError:\n continue\n found.setdefault(name_dir.name, []).append(ver_dir.name)\n return found\n\n def list_installed(self) -> list[dict[str, Any]]:\n \"\"\"Every installed scroll; project-local entries win over user ones.\"\"\"\n user = self._installed_versions(self.user_dir)\n project = self._installed_versions(self.project_scrolls_dir)\n rows: list[dict[str, Any]] = []\n for name in sorted(set(user) | set(project)):\n versions = sorted(\n set(user.get(name, [])) | set(project.get(name, [])),\n key=lambda v: parse_semver(v),\n )\n rows.append(\n {\n \"name\": name,\n \"versions\": versions,\n \"latest\": latest_version(versions),\n \"locations\": sorted(\n {\n *((\"user\",) if name in user else ()),\n *((\"project\",) if name in project else ()),\n }\n ),\n }\n )\n return rows\n\n def info(self, name: str) -> dict[str, Any]:\n \"\"\"Manifest, published versions, and install state for ``name``.\"\"\"\n index = self.load_index()\n entry = index.get(name)\n user = self._installed_versions(self.user_dir).get(name, [])\n project = self._installed_versions(self.project_scrolls_dir).get(name, [])\n installed = sorted(set(user) | set(project),\n key=lambda v: parse_semver(v))\n return {\n \"name\": name,\n \"published\": entry[\"versions\"] if entry else [],\n \"latest\": entry[\"latest\"] if entry else None,\n \"manifest\": entry[\"manifest\"] if entry else None,\n \"installed\": installed,\n \"installed_project\": sorted(project, key=lambda v: parse_semver(v)),\n \"installed_user\": sorted(user, key=lambda v: parse_semver(v)),\n }\n\n # ------------------------------------------- interpreter resolution ----\n\n def resolve_entry(self, name: str) -> Optional[Path]:\n \"\"\"Path to the installed entry ``.god`` file for ``name``, if any.\n\n Project-local installs win; otherwise the latest user-global\n version wins. Returns None when the scroll is not installed.\n \"\"\"\n for base in (self.project_scrolls_dir, self.user_dir):\n name_dir = base / name\n if not name_dir.is_dir():\n continue\n versions: list[str] = []\n for ver_dir in name_dir.iterdir():\n if ver_dir.is_dir() and (ver_dir / \"scroll.toml\").is_file():\n try:\n parse_semver(ver_dir.name)\n except ScrollError:\n continue\n versions.append(ver_dir.name)\n if not versions:\n continue\n latest = latest_version(versions)\n scroll_dir = name_dir / latest\n try:\n manifest = read_manifest(scroll_dir / \"scroll.toml\")\n except ScrollError:\n continue\n entry = scroll_dir / manifest[\"entry\"]\n if entry.is_file():\n return entry.resolve()\n # project-local dir exists but is broken: fall through to user\n return None\n","godcode/remote_registry.py":"\"\"\"Pillar 2b. The remote Scroll Registry client.\n\nTalks to the live scroll registry over HTTPS (default\n``https://api.getgodcode.com``) using only the standard library, so no new\ndependencies are needed. The base URL comes from the\n``GODCODE_REGISTRY_URL`` environment variable, which lets tests point the\nclient at a local fake server instead of the live registry.\n\nEndpoints used (all read-only unless noted):\n\n- ``GET /v1/scrolls?q=&limit=&offset=``. Search.\n- ``GET /v1/scrolls/:name``. Scroll info (name, description, author,\n downloads, versions[], latest, updated_at).\n- ``GET /v1/scrolls/:name/download``. The latest entry ``.god`` code.\n- ``GET /v1/scrolls/:name/versions/:version``. JSON {name, version, code,\n created_at} for one version.\n- ``POST /v1/scrolls``. Publish (needs ``Authorization: Bearer ``).\n\nThe remote catalog does not carry engine requirements or dependency lists\nfor individual versions, so installs from remote synthesize a permissive\n``scroll.toml`` from the info endpoint and record their checksum in the\ninstall receipt instead of verifying one from the index.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom typing import Any\n\nfrom godcode.registry import ENGINE_VERSION, ScrollError, requirement_satisfied\n\nDEFAULT_BASE_URL = \"https://api.getgodcode.com\"\n_REQUEST_TIMEOUT = 20\n\n\nclass RegistryClientError(ScrollError):\n \"\"\"The remote registry could not be reached or refused the request.\"\"\"\n\n\ndef registry_base_url() -> str:\n \"\"\"Base URL for the remote registry (env-overridable, for tests).\"\"\"\n return (\n os.environ.get(\"GODCODE_REGISTRY_URL\") or DEFAULT_BASE_URL\n ).rstrip(\"/\")\n\n\ndef synthesized_manifest(name: str, info: dict[str, Any], version: str) -> dict[str, str]:\n \"\"\"Build a ``scroll.toml``-shaped manifest for a remote scroll.\n\n The info endpoint carries no engine requirement or dependency list, so\n the synthesis is permissive: it admits any modern engine and declares\n no dependencies. A future info field (``godcode`` / ``dependencies``)\n is passed straight through when present.\n \"\"\"\n manifest: dict[str, str] = {\n \"name\": name,\n \"version\": version,\n \"author\": str(info.get(\"author\", \"unknown\")),\n \"description\": str(info.get(\"description\", \"\") or \"\"),\n \"entry\": f\"{name}.god\",\n \"godcode\": \">=2.0\",\n }\n if info.get(\"godcode\"):\n manifest[\"godcode\"] = str(info[\"godcode\"])\n if info.get(\"dependencies\"):\n manifest[\"dependencies\"] = str(info[\"dependencies\"])\n # guard the synthesis itself against a broken requirement shape\n requirement_satisfied(manifest[\"godcode\"], ENGINE_VERSION)\n return manifest\n\n\nclass RemoteRegistry:\n \"\"\"Thin HTTPS client for the remote scroll registry.\"\"\"\n\n def __init__(self, base_url: str | None = None) -> None:\n self.base_url = (base_url or registry_base_url()).rstrip(\"/\")\n\n # ------------------------------------------------------------ http -----\n\n def _request(\n self,\n method: str,\n path: str,\n params: dict[str, str] | None = None,\n body: dict[str, Any] | None = None,\n token: str | None = None,\n ) -> tuple[int, Any]:\n \"\"\"Issue one request; return (status, parsed body).\"\"\"\n url = self.base_url + path\n if params:\n url += \"?\" + urllib.parse.urlencode(params)\n data = None\n headers = {\"Accept\": \"application/json\"}\n if body is not None:\n data = json.dumps(body).encode(\"utf-8\")\n headers[\"Content-Type\"] = \"application/json\"\n if token:\n headers[\"Authorization\"] = f\"Bearer {token}\"\n request = urllib.request.Request(\n url, data=data, headers=headers, method=method\n )\n try:\n with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT) as resp:\n raw = resp.read().decode(\"utf-8\")\n status = resp.status\n except urllib.error.HTTPError as exc:\n try:\n payload = json.loads(exc.read().decode(\"utf-8\"))\n except Exception:\n payload = {\"ok\": False, \"error\": exc.reason}\n raise RegistryClientError(\n f\"remote registry: {method} {path} failed with HTTP \"\n f\"{exc.code}: {payload.get('error', exc.reason)}\"\n ) from exc\n except (urllib.error.URLError, TimeoutError, OSError) as exc:\n raise RegistryClientError(\n f\"remote registry: cannot reach {self.base_url} \"\n f\"({exc}); is the network up and GODCODE_REGISTRY_URL set?\"\n ) from exc\n try:\n return status, json.loads(raw)\n except json.JSONDecodeError:\n # download endpoints return plain .god source, not JSON\n return status, raw\n\n # ------------------------------------------------------------ reads ----\n\n def search(\n self, query: str, limit: int = 20, offset: int = 0\n ) -> list[dict[str, Any]]:\n \"\"\"Search the remote catalog; rows carry name, description, author,\n latest version, downloads, and updated_at.\"\"\"\n _, payload = self._request(\n \"GET\",\n \"/v1/scrolls\",\n params={\"q\": query, \"limit\": str(limit), \"offset\": str(offset)},\n )\n if isinstance(payload, dict) and payload.get(\"ok\"):\n return list(payload.get(\"scrolls\", []))\n raise RegistryClientError(\n f\"remote registry: unexpected search response for {query!r}\"\n )\n\n def info(self, name: str) -> dict[str, Any]:\n \"\"\"Full catalog record for ``name`` (versions[], latest, ...).\"\"\"\n _, payload = self._request(\n \"GET\", f\"/v1/scrolls/{urllib.parse.quote(name, safe='')}\"\n )\n if isinstance(payload, dict) and payload.get(\"ok\"):\n record = dict(payload)\n record.setdefault(\"versions\", [])\n return record\n error = payload.get(\"error\") if isinstance(payload, dict) else None\n raise RegistryClientError(\n f\"remote registry: scroll {name!r} not found ({error or 'no record'})\"\n )\n\n def fetch_code(self, name: str, version: str | None = None) -> tuple[str, str]:\n \"\"\"The entry ``.god`` source for ``name``; returns (code, version).\n\n ``version`` selects an exact release; without it the latest entry\n is downloaded.\n \"\"\"\n quoted = urllib.parse.quote(name, safe=\"\")\n if version is None:\n _, payload = self._request(\"GET\", f\"/v1/scrolls/{quoted}/download\")\n if not isinstance(payload, str):\n raise RegistryClientError(\n f\"remote registry: download for {name!r} did not \"\n \"return scroll source\"\n )\n resolved = self.info(name)[\"latest\"]\n return payload, resolved\n _, payload = self._request(\n \"GET\",\n f\"/v1/scrolls/{quoted}/versions/{urllib.parse.quote(version, safe='')}\",\n )\n if isinstance(payload, dict) and payload.get(\"code\") is not None:\n return str(payload[\"code\"]), str(payload.get(\"version\", version))\n raise RegistryClientError(\n f\"remote registry: no code for {name!r} version {version!r}\"\n )\n\n def versions_satisfying(\n self, name: str, requirement: str | None\n ) -> tuple[dict[str, Any], list[str]]:\n \"\"\"The info record plus the versions matching ``requirement``\n (None means any version), highest first.\"\"\"\n from functools import cmp_to_key\n\n from godcode.registry import compare_versions, requirement_satisfied\n\n record = self.info(name)\n versions: list[str] = list(record.get(\"versions\") or [])\n matching = [\n v\n for v in versions\n if requirement is None\n or requirement_satisfied(requirement, v)\n ]\n matching.sort(key=cmp_to_key(compare_versions), reverse=True)\n return record, matching\n\n # ----------------------------------------------------------- publish ---\n\n def publish_scroll(\n self,\n *,\n name: str,\n version: str,\n code: str,\n description: str,\n author: str,\n token: str,\n ) -> dict[str, Any]:\n \"\"\"Publish one scroll version to the remote registry.\n\n The token travels as ``Authorization: Bearer ``. The body\n mirrors the version-fetch shape: {name, version, code, description,\n author}. Returns the registry's acknowledgement.\n \"\"\"\n if not token:\n raise RegistryClientError(\n \"remote publish needs a token; refusing to publish unsigned\"\n )\n _, payload = self._request(\n \"POST\",\n \"/v1/scrolls\",\n body={\n \"name\": name,\n \"version\": version,\n \"code\": code,\n \"description\": description,\n \"author\": author,\n },\n token=token,\n )\n if isinstance(payload, dict) and payload.get(\"ok\") is not False:\n return payload\n raise RegistryClientError(\n f\"remote registry refused the publish of {name} {version}: \"\n f\"{payload!r}\"\n )\n","godcode/sandbox.py":"\"\"\"In-process sandbox for God Code v3.0 — Pillar 1 (\"Strong Foundations\").\n\nRuns a God Code creation under a deny-by-default :class:`SandboxPolicy`:\nevery side-effecting power (scroll imports outside the consecrated paths,\nthe ASK rite that speaks with the outer world) is withheld unless the\npolicy explicitly grants it. File-writing rites keep their meaning but\nnot their reach: ANCHOR is answered with an ephemeral in-memory chain,\nso nothing is ever written to disk. A step budget and a wall-clock grant\nbound runaway creations.\n\nEntry points\n------------\n``run_sandboxed(source, policy, source_name)``\n Lex, parse, and run ``source`` under ``policy``; returns the list of\n REVEAL lines captured during the run.\n\n``apply_policy(interpreter, policy)``\n Install the sandbox hooks on an existing ``Interpreter``; returns the\n ``Sandbox`` guard.\n\n``SandboxPolicy.strict(...)``\n The policy the CLI uses: no writes, no network, no subprocesses, no\n stdin, scroll imports limited to the stdlib scrolls and (optionally)\n the creation's own directory, a 5-second time grant, and a 100,000\n step budget.\n\nHonest limits (see docs/sandbox.md): this is an *in-process* sandbox —\na cooperative audit of the tree-walker, not OS-level isolation. It\ncannot contain a hostile program that escapes the interpreter, and it\ncannot cap memory.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport os\nimport signal\nimport time\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodCodeError, SandboxViolation\n\n__all__ = [\n \"SandboxPolicy\",\n \"Sandbox\",\n \"SandboxViolation\",\n \"apply_policy\",\n \"run_sandboxed\",\n \"run_sandboxed_with_interpreter\",\n]\n\n\ndef _stdlib_scrolls_dir() -> str:\n return str(Path(__file__).parent / \"scrolls\")\n\n\n# ---------------------------------------------------------------------------\n# Policy\n# ---------------------------------------------------------------------------\n@dataclass\nclass SandboxPolicy:\n \"\"\"What a sandboxed creation is permitted to do. Deny-by-default.\n\n ``allow_read_paths``\n Approved directories for filesystem *reads*. ``None`` (the\n default) denies all reads; a tuple of directories grants reads\n under those trees. (No file-reading rites exist in v2.0; this is\n enforced should any be added.)\n ``allow_write`` / ``allow_network`` / ``allow_subprocess``\n Filesystem writes, network access, subprocess spawning. All deny\n by default. The ANCHOR rite is the one file-writing rite: under a\n policy that denies writes it is answered with an ephemeral\n in-memory chain instead of being refused, so creations keep\n their meaning without touching the disk.\n ``allow_stdin``\n Whether the ASK rite may speak with the outer world (``input()``).\n Denied by default.\n ``allowed_import_paths``\n Approved directories for IMPORT of scrolls. Empty (the default)\n denies every import. Each entry is a directory; a scroll is\n allowed if its real path lies under one of them.\n ``timeout_seconds``\n Wall-clock grant for the whole run. ``None`` or ``<= 0``\n disables the grant (not recommended).\n ``max_steps``\n Step budget: every statement dispatch and every expression\n evaluation counts one step, bounding both runaway loops and\n unbounded rite recursion.\n \"\"\"\n\n allow_read_paths: tuple[str, ...] | None = None\n allow_write: bool = False\n allow_network: bool = False\n allow_subprocess: bool = False\n allow_stdin: bool = False\n allowed_import_paths: tuple[str, ...] = ()\n timeout_seconds: float | None = 5.0\n max_steps: int = 100_000\n\n @classmethod\n def strict(\n cls,\n *,\n source_dir: str | None = None,\n timeout_seconds: float | None = 5.0,\n ) -> \"SandboxPolicy\":\n \"\"\"The CLI's strict policy: deny everything, bless the stdlib.\n\n Scroll imports are allowed from the bundled stdlib scrolls and,\n when given, the creation's own directory — nothing else.\n \"\"\"\n paths = [_stdlib_scrolls_dir()]\n if source_dir:\n paths.append(str(source_dir))\n return cls(\n allowed_import_paths=tuple(paths),\n timeout_seconds=timeout_seconds,\n )\n\n @classmethod\n def open(cls) -> \"SandboxPolicy\":\n \"\"\"The permissive host policy used under a permission manifest.\n\n A plain `godcode run` of a scroll without --sandbox has always run\n unbound; installing the guard with the open policy preserves that\n while letting the scroll's own permission manifest do the\n narrowing. No step budget, no time grant, every power allowed —\n the manifest alone withholds.\n \"\"\"\n return cls(\n allow_read_paths=(os.sep,),\n allow_write=True,\n allow_network=True,\n allow_subprocess=True,\n allow_stdin=True,\n allowed_import_paths=(os.sep,),\n timeout_seconds=None,\n max_steps=10**15,\n )\n\n\n# ---------------------------------------------------------------------------\n# The guard\n# ---------------------------------------------------------------------------\n# Builtin rite name -> SandboxPolicy attribute that must be truthy for the\n# rite to run. ANCHOR is deliberately absent: under a policy that denies\n# writes it is answered with an ephemeral in-memory chain (see\n# run_sandboxed_with_interpreter), so the rite itself never reaches the\n# filesystem and needs no grant. The vault builtins (godcode.stdlib_vault)\n# reach the host filesystem directly, so they are policed here too;\n# READ_FILE/LIST_DIR/FILE_EXISTS additionally enforce the granted\n# directories per path inside the builtins themselves.\n_SIDE_EFFECT_RITES: dict[str, str] = {\n \"ASK\": \"allow_stdin\",\n \"WRITE_FILE\": \"allow_write\",\n \"READ_FILE\": \"allow_read_paths\",\n \"LIST_DIR\": \"allow_read_paths\",\n \"FILE_EXISTS\": \"allow_read_paths\",\n \"HTTP_GET\": \"allow_network\",\n}\n\n_HOOKS = (\"_exec_stmt\", \"_eval_expr\", \"_call\", \"_exec_import\")\n\n\nclass Sandbox:\n \"\"\"Enforces a :class:`SandboxPolicy` on a live Interpreter.\n\n Installed hooks (see :meth:`install`):\n\n * ``_exec_stmt`` / ``_eval_expr`` — count one step per statement\n dispatch and expression evaluation; check the step budget and the\n wall-clock grant; record the current line for divine errors.\n * ``_call`` — refuse side-effecting rites the policy does not grant\n (ASK today; the registry above grows with the language).\n * ``_exec_import`` — resolve the scroll, then refuse any path\n outside ``allowed_import_paths``.\n \"\"\"\n\n def __init__(self, interpreter: Any, policy: SandboxPolicy):\n self.interpreter = interpreter\n self.policy = policy\n self.steps = 0\n self.started_at: float | None = None\n self.current_line: int | None = None\n self._originals: dict[str, Callable] = {}\n self._allowed_import_dirs = [\n os.path.realpath(p) for p in policy.allowed_import_paths\n ]\n # The open policy blesses the whole filesystem: every import path\n # is consecrated, as in a plain `godcode run` with no guard.\n self._import_open = any(\n d == os.path.realpath(os.sep) for d in self._allowed_import_dirs\n )\n\n # -- installation ---------------------------------------------------\n\n def install(self) -> \"Sandbox\":\n \"\"\"Wrap the interpreter's dispatch points. Idempotent.\n\n Also marks the interpreter with ``_sandbox_guard`` so builtins\n that reach the host world (the vault builtins in\n godcode.stdlib_vault) can see the policy and honor its grants.\n \"\"\"\n interp = self.interpreter\n if self._originals:\n return self\n interp._sandbox_guard = self\n for name in _HOOKS:\n original = getattr(interp, name)\n self._originals[name] = original\n setattr(interp, name, self._wrap(name, original))\n return self\n\n def uninstall(self) -> None:\n \"\"\"Restore the interpreter's original dispatch points.\"\"\"\n for name, original in self._originals.items():\n setattr(self.interpreter, name, original)\n self._originals.clear()\n self.interpreter.__dict__.pop(\"_sandbox_guard\", None)\n\n def _wrap(self, name: str, original: Callable) -> Callable:\n if name == \"_exec_stmt\":\n def exec_stmt(stmt, env):\n self.tick(stmt)\n return original(stmt, env)\n return exec_stmt\n if name == \"_eval_expr\":\n def eval_expr(expr, env):\n self.tick(expr)\n return original(expr, env)\n return eval_expr\n if name == \"_call\":\n def call(rite_name, args, env, line):\n self.check_rite(rite_name, line, tuple(args or ()))\n return original(rite_name, args, env, line)\n return call\n if name == \"_exec_import\":\n def exec_import(stmt, env):\n line = getattr(stmt, \"line\", None)\n path = self.interpreter._resolve_import(stmt.path, line)\n self.check_import_path(path, stmt.path, line)\n return original(stmt, env)\n return exec_import\n raise AssertionError(f\"unknown hook: {name}\") # pragma: no cover\n\n # -- enforcement -----------------------------------------------------\n\n def tick(self, node: Any) -> None:\n \"\"\"Count one interpreter step; enforce budget and time grant.\"\"\"\n self.steps += 1\n line = getattr(node, \"line\", None)\n if line is not None:\n self.current_line = line\n if self.steps > self.policy.max_steps:\n raise SandboxViolation(\n \"The sandbox withholds this power: the creation has taken \"\n f\"more than {self.policy.max_steps:,} steps. \"\n \"The step budget is spent, and the cycle is released.\",\n self.current_line,\n )\n if self.started_at is not None and self.policy.timeout_seconds:\n elapsed = time.monotonic() - self.started_at\n if elapsed > self.policy.timeout_seconds:\n raise SandboxViolation(\n \"The sandbox withholds this power: the appointed time \"\n f\"({self.policy.timeout_seconds:g}s) is spent. \"\n \"The creation is released in peace.\",\n self.current_line,\n )\n\n def check_rite(self, name: str, line: int | None, args: tuple = ()) -> None:\n \"\"\"Refuse side-effecting rites the policy does not grant.\n\n The host policy is consulted first; then the scroll's own\n permission manifest (when the scroll declared one) narrows the\n grant to the declared targets. The manifest never widens the host.\n \"\"\"\n need = _SIDE_EFFECT_RITES.get(str(name).upper())\n if need is not None and not getattr(self.policy, need, False):\n divine = {\n \"ASK\": \"the rite ASK would speak with the outer world\",\n \"WRITE_FILE\": \"the rite WRITE_FILE would write to the outer world\",\n \"READ_FILE\": \"the rite READ_FILE would read from the outer world\",\n \"LIST_DIR\": \"the rite LIST_DIR would read from the outer world\",\n \"FILE_EXISTS\": \"the rite FILE_EXISTS would read from the outer world\",\n \"HTTP_GET\": \"the rite HTTP_GET would reach out to the web\",\n }.get(str(name).upper(), f\"the rite {name}\")\n raise SandboxViolation(\n f\"The sandbox withholds this power: {divine}. \"\n \"It is not granted.\",\n line,\n )\n self._check_manifest(name, line, args)\n\n def _check_manifest(self, name: str, line: int | None, args: tuple) -> None:\n \"\"\"Enforce the scroll's declared permission manifest, if any.\n\n The guard reads the manifest live from the interpreter so that\n imported scrolls may widen the run's grants by declaring their\n own (grants compose by union; the host policy still narrows).\n \"\"\"\n manifest = getattr(self.interpreter, \"manifest\", None)\n if not manifest:\n return\n rite = str(name).upper()\n target = args[0] if args else None\n # Runtime file targets resolve exactly the way the builtins open\n # them: relative to the invocation directory. realpath() on the\n # raw target mirrors that, so the check can never be talked into\n # blessing a different file than the rite will touch.\n\n def withheld(counsel: str) -> SandboxViolation:\n return SandboxViolation(\n f\"The scroll reaches for a power it did not declare: {counsel} \"\n \"Declare it at the top of the scroll with DECLARE PERMISSION \"\n \"TO, or leave the power untouched.\",\n line,\n )\n\n if rite == \"ASK\" and not manifest.stdin:\n raise withheld(\"ASK would speak with the outer world\")\n if rite == \"WRITE_FILE\":\n if not (isinstance(target, str) and manifest.allows_write(target)):\n raise withheld(f\"WRITE_FILE would write '{target}'\")\n if rite in (\"READ_FILE\", \"LIST_DIR\", \"FILE_EXISTS\"):\n if not (isinstance(target, str) and manifest.allows_read(target)):\n raise withheld(f\"{rite} would read '{target}'\")\n if rite == \"HTTP_GET\":\n if not (isinstance(target, str) and manifest.allows_host(target)):\n raise withheld(f\"HTTP_GET would reach '{target}'\")\n if rite == \"SUMMON\":\n if not (isinstance(target, str) and manifest.allows_summon(target)):\n raise withheld(f\"SUMMON would call upon '{target}'\")\n\n def check_import_path(\n self, path: Path, requested: str, line: int | None\n ) -> None:\n \"\"\"Refuse scrolls outside the consecrated import paths.\"\"\"\n if self._import_open:\n return\n resolved = os.path.realpath(path)\n for allowed in self._allowed_import_dirs:\n if resolved == allowed or resolved.startswith(allowed + os.sep):\n return\n raise SandboxViolation(\n \"The sandbox withholds this power: the scroll \"\n f\"'{requested}' lies outside the consecrated paths. \"\n \"It may not be breathed in.\",\n line,\n )\n\n\ndef apply_policy(interpreter: Any, policy: SandboxPolicy) -> Sandbox:\n \"\"\"Install sandbox hooks on ``interpreter``; return the guard.\n\n One guard per interpreter; the hooks stay installed until\n ``guard.uninstall()`` is called.\n \"\"\"\n return Sandbox(interpreter, policy).install()\n\n\n# ---------------------------------------------------------------------------\n# Timeout: POSIX signal alarm with a wall-clock fallback\n# ---------------------------------------------------------------------------\n@contextlib.contextmanager\ndef _time_limit(seconds: float | None, guard: Sandbox):\n \"\"\"Raise SandboxViolation from a POSIX alarm when the grant expires.\n\n The wall-clock check in :meth:`Sandbox.tick` is the fallback (and the\n only enforcement on platforms without ``setitimer``, or outside the\n main thread, where signals cannot be armed).\n \"\"\"\n armed = False\n old_handler = None\n\n def _handler(signum, frame): # noqa: ARG001\n raise SandboxViolation(\n \"The sandbox withholds this power: the appointed time \"\n f\"({seconds:g}s) is spent. The creation is released in peace.\",\n guard.current_line,\n )\n\n try:\n if seconds and hasattr(signal, \"setitimer\"):\n old_handler = signal.signal(signal.SIGALRM, _handler)\n signal.setitimer(signal.ITIMER_REAL, seconds)\n armed = True\n except (ValueError, OSError, RuntimeError):\n armed = False # not the main thread, or signals unavailable\n try:\n yield\n finally:\n if armed:\n try:\n signal.setitimer(signal.ITIMER_REAL, 0)\n signal.signal(signal.SIGALRM, old_handler)\n except (ValueError, OSError, RuntimeError):\n pass\n\n\n# ---------------------------------------------------------------------------\n# High-level entry point\n# ---------------------------------------------------------------------------\ndef run_sandboxed_with_interpreter(\n source: str,\n policy: SandboxPolicy | None = None,\n source_name: str = \"\",\n) -> tuple[list[str], Any]:\n \"\"\"Run God Code ``source`` under ``policy``; return (REVEAL lines, interpreter).\n\n The interpreter is returned so callers can read machine state the run\n gathered (e.g. ``intent_checks`` for the v4.0 intent layer).\n \"\"\"\n from godcode import plugins\n from godcode.chain import MemoryChainAdapter\n from godcode.interpreter import Interpreter\n from godcode.spirit import SpiritEngine\n\n policy = policy or SandboxPolicy.strict()\n env_var = plugins.DISABLE_ENV_VAR\n previous = os.environ.get(env_var)\n os.environ[env_var] = \"1\"\n try:\n interpreter = Interpreter(log_path=None, interactive=False)\n finally:\n if previous is None:\n os.environ.pop(env_var, None)\n else:\n os.environ[env_var] = previous\n # v4.0: the covenant ledger and the audit log stay unbound (they write\n # to the host world, which the sandbox does not permit). The Spirit\n # only reads its dataset, so it is bound: CONSULT and the DECLARE\n # INTENT discernment need it. ANCHOR is answered with an ephemeral\n # in-memory chain, so no file is ever written.\n try:\n interpreter.spirit = SpiritEngine()\n except Exception:\n pass\n if not policy.allow_write:\n interpreter.chain_adapters = {\"simulated\": MemoryChainAdapter()}\n guard = apply_policy(interpreter, policy)\n guard.started_at = time.monotonic()\n try:\n with _time_limit(policy.timeout_seconds, guard):\n interpreter.run_source(source, source_name=source_name)\n except RecursionError:\n raise SandboxViolation(\n \"The sandbox withholds this power: the rites called upon \"\n \"themselves past the deep places. The recursion budget is \"\n \"spent, and the cycle is released.\",\n guard.current_line,\n ) from None\n finally:\n guard.started_at = None\n return list(interpreter.output), interpreter\n\n\ndef run_sandboxed(\n source: str,\n policy: SandboxPolicy | None = None,\n source_name: str = \"\",\n) -> list[str]:\n \"\"\"Run God Code ``source`` under ``policy``; return captured REVEAL lines.\n\n Uses the strict policy when none is given. The covenant ledger and\n the audit log stay unbound -- they write to the host world, which\n the sandbox does not permit. The Spirit is bound (it only reads its\n dataset), and ANCHOR answers with an ephemeral in-memory chain, so\n CONSULT and DECLARE INTENT work while no file is ever written. Host\n plugin auto-loading is disabled for the run (via the plugin system's\n own opt-out): plugins are trusted host code that runs outside any\n policy, so a deny-by-default sandbox must not breathe them in unasked.\n Raises :class:`SandboxViolation` (a GodCodeError, line-numbered)\n when the creation reaches beyond its grant.\n \"\"\"\n output, _ = run_sandboxed_with_interpreter(source, policy, source_name)\n return output\n","godcode/scaffold.py":"\"\"\"`godcode new` — raise a new God Code project from the dust.\n\nOne command lays out everything a first scroll needs: a manifest the\nscroll registry understands, a warm starter scroll that runs pure, a\ntest scroll the test runner discovers, and a small README that points\nat the next steps. The sanctuary welcomes the newcomer.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\n#: Scroll/project names: lowercase, digits, and hyphens, starting with a letter.\nNAME_RE = re.compile(r\"^[a-z][a-z0-9-]{0,63}$\")\n\n#: The engine release line this scaffold targets.\nENGINE_LINE = \">=4.1\"\n\n\nclass ScaffoldError(Exception):\n \"\"\"A gentle refusal to raise the project (bad name, occupied ground).\"\"\"\n\n\n@dataclass\nclass ScaffoldResult:\n \"\"\"What `create_project` laid down.\"\"\"\n\n name: str\n directory: Path\n files: list[str] = field(default_factory=list)\n\n\ndef validate_name(name: str) -> str:\n \"\"\"Return the cleaned name, or raise ScaffoldError with counsel.\"\"\"\n cleaned = (name or \"\").strip().lower()\n if not NAME_RE.match(cleaned):\n raise ScaffoldError(\n f\"'{name}' is not a fitting scroll name: use lowercase letters, \"\n \"digits, and hyphens, beginning with a letter \"\n \"(for example: my-scroll).\"\n )\n return cleaned\n\n\ndef _main_god(name: str) -> str:\n return f\"\"\"\\\n# {name}, a newborn scroll.\n# Run it with: godcode run main.god\n# Test it with: godcode test .\n# Declare the powers your scroll may touch (uncomment what it needs):\n# DECLARE PERMISSION TO READ \"data/\"\n# DECLARE PERMISSION TO WRITE \"out/\"\n\nBEGIN CREATION\n\n DECLARE INTENT \"speak a blessing of peace over the household\" ON evening_blessing\n\n DEFINE RITE evening_blessing()\n REVEAL(\"Peace be upon this house.\")\n REVEAL(\"May the morning bring grace and the evening bring rest.\")\n END RITE\n\n DECLARE day AS \"a new day\"\n evening_blessing()\n REVEAL(\"Walk into {{day}} with courage.\")\n\nEND CREATION\n\"\"\"\n\n\ndef _test_god(name: str) -> str:\n return f\"\"\"\\\n# Tests for the {name} scroll.\n# Run them with: godcode test .\n\nBEGIN CREATION\n\n DEFINE RITE TEST_day_declared()\n DECLARE day AS \"a new day\"\n TESTIFY day IS \"a new day\"\n END RITE\n\n DEFINE RITE TEST_blessing_holds()\n TESTIFY 2 + 3 IS 5\n END RITE\n\nEND CREATION\n\"\"\"\n\n\ndef _scroll_toml(name: str, author: str) -> str:\n return f\"\"\"\\\n# Scroll manifest — `godcode scroll publish .` reads this.\nname = \"{name}\"\nversion = \"0.1.0\"\nauthor = \"{author}\"\ndescription = \"A newborn God Code scroll.\"\nentry = \"main.god\"\ngodcode = \"{ENGINE_LINE}\"\n\"\"\"\n\n\ndef _readme(name: str) -> str:\n return f\"\"\"\\\n# {name}\n\nA God Code scroll, freshly created with `godcode new`.\n\n## Speak it\n\n godcode run main.god\n\n## Test it\n\n godcode test .\n\n## Polish it\n\n godcode check main.god # purity, without running\n godcode lint main.god # quiet troubles surfaced\n godcode fmt main.god # canonical form\n\n## Share it\n\n godcode scroll publish . # publish to the local scroll registry\n\nLearn the language: https://godcode-phi.vercel.app/learn/\n\"\"\"\n\n\ndef create_project(name: str, dest: Path | str = \".\",\n author: str = \"\") -> ScaffoldResult:\n \"\"\"Raise the project directory and write the four starter files.\n\n Raises ScaffoldError when the name is unfitting or the ground is\n already occupied.\n \"\"\"\n cleaned = validate_name(name)\n root = Path(dest).expanduser() / cleaned\n if root.exists():\n raise ScaffoldError(\n f\"'{root}' already stands: choose another name or an empty place.\"\n )\n root.mkdir(parents=True)\n\n files = {\n \"main.god\": _main_god(cleaned),\n \"test_main.god\": _test_god(cleaned),\n \"scroll.toml\": _scroll_toml(cleaned, author.replace('\"', \"\")),\n \"README.md\": _readme(cleaned),\n }\n for filename, text in files.items():\n (root / filename).write_text(text, encoding=\"utf-8\")\n return ScaffoldResult(name=cleaned, directory=root,\n files=sorted(files))\n","godcode/scrolls/covenant.god":"# The Scroll of the Covenant -- making and sealing binding promises.\n# Rites: NEW_COVENANT, SEAL_COVENANT.\n\nDEFINE RITE NEW_COVENANT(name)\nRETURN contract(name)\nEND RITE\n\nDEFINE RITE SEAL_COVENANT(c)\nSEAL c\nEND RITE\n","godcode/scrolls/covenant.toml":"name = \"covenant\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of the Covenant: making and sealing binding promises. Rites: NEW_COVENANT, SEAL_COVENANT.\"\nentry = \"covenant.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/lists.god":"# The Scroll of Multitudes -- reckonings over gathered lists.\n# Rites: SUM, AVG, CONTAINS, SECOND, TAIL, COUNT.\n\nDEFINE RITE SUM(xs)\nDECLARE total AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nDECLARE total AS total + xs[i]\nDECLARE i AS i + 1\nENDWHILE\nRETURN total\nEND RITE\n\nDEFINE RITE AVG(xs)\nRETURN SUM(xs) / LEN(xs)\nEND RITE\n\nDEFINE RITE CONTAINS(xs, x)\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nRETURN 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN 0\nEND RITE\n\nDEFINE RITE SECOND(xs)\nRETURN xs[1]\nEND RITE\n\nDEFINE RITE TAIL(xs)\nDECLARE tail AS []\nDECLARE i AS 1\nWHILE i < LEN(xs) DO\nDECLARE tail AS PUSH(tail, xs[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN tail\nEND RITE\n\nDEFINE RITE COUNT(xs, x)\nDECLARE n AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nDECLARE n AS n + 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN n\nEND RITE\n","godcode/scrolls/lists.toml":"name = \"lists\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Multitudes: reckonings over gathered lists. Rites: SUM, AVG, CONTAINS, SECOND, TAIL, COUNT.\"\nentry = \"lists.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/math.god":"# The Scroll of Numbers -- divine arithmetic for the children of creation.\n# Rites: SQRT, POW, ABS, MIN, MAX, FACTORIAL, IS_EVEN.\n\nDEFINE RITE SQRT(x)\nIF x IS 0 THEN\nRETURN 0\nENDIF\nIF x < 0 THEN\nRETURN 0\nENDIF\nDECLARE guess AS x\nWHILE ABS(guess * guess - x) > 0.000000001 DO\nDECLARE guess AS guess - (guess * guess - x) / (2 * guess)\nENDWHILE\nRETURN guess\nEND RITE\n\nDEFINE RITE POW(b, e)\nDECLARE result AS 1\nDECLARE i AS 0\nWHILE i < e DO\nDECLARE result AS result * b\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE ABS(x)\nIF x < 0 THEN\nRETURN 0 - x\nENDIF\nRETURN x\nEND RITE\n\nDEFINE RITE MIN(a, b)\nIF a < b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE MAX(a, b)\nIF a > b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE FACTORIAL(n)\nDECLARE result AS 1\nDECLARE i AS 1\nWHILE i <= n DO\nDECLARE result AS result * i\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE IS_EVEN(n)\nIF n % 2 IS 0 THEN\nRETURN 1\nENDIF\nRETURN 0\nEND RITE\n","godcode/scrolls/math.toml":"name = \"math\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Numbers: divine arithmetic. Rites: SQRT, POW, ABS, MIN, MAX, FACTORIAL, IS_EVEN.\"\nentry = \"math.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/prophecy.god":"# The Scroll of Lots -- discerning choice by sacred chance.\n# Rites: PROPHESY_NUMBER, CAST_LOTS, CHOOSE.\n\nDEFINE RITE PROPHESY_NUMBER(n)\nRETURN RANDOM(n)\nEND RITE\n\nDEFINE RITE CAST_LOTS()\nRETURN RANDOM(2)\nEND RITE\n\nDEFINE RITE CHOOSE(xs)\nRETURN xs[RANDOM(LEN(xs))]\nEND RITE\n","godcode/scrolls/prophecy.toml":"name = \"prophecy\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Lots: discerning choice by sacred chance. Rites: PROPHESY_NUMBER, CAST_LOTS, CHOOSE.\"\nentry = \"prophecy.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/strings.god":"# The Scroll of Tongues -- words shaped, lifted up, and proclaimed.\n# Rites: SHOUT, WHISPER, WORDS, CHARS, FIRST, LAST.\n\nDEFINE RITE SHOUT(s)\nRETURN UPPER(s) + \"!\"\nEND RITE\n\nDEFINE RITE WHISPER(s)\nRETURN LOWER(s)\nEND RITE\n\nDEFINE RITE WORDS(s)\nRETURN SPLIT(s, \" \")\nEND RITE\n\nDEFINE RITE CHARS(s)\nDECLARE chars AS []\nDECLARE i AS 0\nWHILE i < LEN(s) DO\nDECLARE chars AS PUSH(chars, s[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN chars\nEND RITE\n\nDEFINE RITE FIRST(s)\nRETURN s[0]\nEND RITE\n\nDEFINE RITE LAST(s)\nRETURN s[LEN(s) - 1]\nEND RITE\n","godcode/scrolls/strings.toml":"name = \"strings\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Tongues: words shaped, lifted up, and proclaimed. Rites: SHOUT, WHISPER, WORDS, CHARS, FIRST, LAST.\"\nentry = \"strings.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/time.god":"# The Scroll of Appointed Times -- beholding the hour and the day.\n# Rites: NOW, TODAY.\n\nDEFINE RITE NOW()\nRETURN BEHOLD()\nEND RITE\n\nDEFINE RITE TODAY()\nRETURN SPLIT(BEHOLD(), \"T\")[0]\nEND RITE\n","godcode/scrolls/time.toml":"name = \"time\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Appointed Times: beholding the hour and the day. Rites: NOW, TODAY.\"\nentry = \"time.god\"\ngodcode = \">=2.0\"\n","godcode/spirit.py":"\"\"\"SpiritEngine -- discerns the spiritual intent behind words. 🕊\n\nLoads the God Code training dataset, builds a keyword index over each row's\nprimary_action + spiritual_intent + logic_flows, and classifies new text by\nkeyword overlap. When nothing resonates, it falls back to silent contemplation.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport csv\nimport re\nfrom collections import Counter\nfrom pathlib import Path\n\n_WORD_RE = re.compile(r\"[a-z0-9]+\")\n\nSTOPWORDS = frozenset(\n \"\"\"\n a an the of and to in for on with by or is are was were be been being\n this that these those it its as at from into over under between through\n during before after above below up down out off again further then once\n here there when where why how all any both each few more most other some\n such no nor not only own same so than too very can will just don should\n now your you we they them their our us my me him her his she he i\n do does did have has had shall may might must would could ought\n \"\"\".split()\n)\n\nSILENT_CONTEMPLATION = {\n \"intent\": \"Silent contemplation\",\n \"confidence\": 0.0,\n \"spiritual_intent\": \"The Spirit is quiet on this matter.\",\n \"suggestion\": \"BREATHE and try again.\",\n \"keywords\": [],\n}\n\n\ndef _keywords(text: str) -> set[str]:\n \"\"\"Lowercase word tokens with stopwords removed.\"\"\"\n return {w for w in _WORD_RE.findall((text or \"\").lower()) if w not in STOPWORDS}\n\n\nclass SpiritEngine:\n \"\"\"Keyword-overlap classifier over the God Code training dataset.\"\"\"\n\n def __init__(self, dataset_path: str | Path | None = None) -> None:\n if dataset_path is None:\n # Default: god_code_training_dataset.csv at the repo root.\n dataset_path = Path(__file__).resolve().parent.parent / \"god_code_training_dataset.csv\"\n self.dataset_path = Path(dataset_path)\n self.rows: list[dict] = self._load()\n # v4.0 -- declared intents: rite name -> natural-language intent text,\n # registered by DECLARE INTENT and consulted by resolve_intent().\n self.declared_intents: dict[str, str] = {}\n\n def _load(self) -> list[dict]:\n try:\n with open(self.dataset_path, newline=\"\", encoding=\"utf-8\") as f:\n records = list(csv.reader(f))\n except OSError:\n # No dataset beside the engine (e.g. an installed copy):\n # the Spirit is quiet, and classify() falls back gracefully.\n return []\n if not records:\n return []\n header, records = records[0], records[1:]\n rows: list[dict] = []\n buf: list[str] = []\n for rec in records:\n if len(rec) == len(header):\n # A row ends here: the code field may have spanned earlier\n # physical lines (unquoted), accumulated in buf.\n code = \"\\n\".join(buf + [rec[0]])\n row = dict(zip(header, [code] + rec[1:]))\n row[\"keywords\"] = _keywords(\n \" \".join(row[c] for c in (\"primary_action\", \"spiritual_intent\", \"logic_flows\"))\n )\n rows.append(row)\n buf = []\n else:\n # Continuation line of the multi-line code field.\n buf.extend(rec)\n return rows\n\n def classify(self, text: str) -> dict:\n \"\"\"Classify text -> {intent, confidence, spiritual_intent, suggestion, keywords}.\"\"\"\n words = _keywords(text)\n best: dict | None = None\n best_overlap = 0\n best_confidence = 0.0\n for row in self.rows:\n overlap = len(words & row[\"keywords\"])\n if overlap == 0:\n continue\n confidence = overlap / max(1, len(row[\"keywords\"]))\n # Most shared keywords wins; ties go to the row whose\n # vocabulary best explains the input (highest confidence),\n # so an incidental word cannot outshout the true theme.\n if overlap > best_overlap or (\n overlap == best_overlap and confidence > best_confidence\n ):\n best, best_overlap, best_confidence = row, overlap, confidence\n if best is None:\n return dict(SILENT_CONTEMPLATION)\n confidence = min(1.0, best_overlap / max(1, len(best[\"keywords\"])))\n return {\n \"intent\": best[\"primary_action\"],\n \"confidence\": round(confidence, 4),\n \"spiritual_intent\": best[\"spiritual_intent\"],\n \"suggestion\": best[\"next_suggestions\"],\n \"keywords\": sorted(words & best[\"keywords\"]),\n }\n\n def prophesy(self, program_text: str) -> str:\n \"\"\"Compose a 2-3 sentence divine forecast over a program's lines.\"\"\"\n lines = [ln.strip() for ln in (program_text or \"\").splitlines() if ln.strip()]\n results = [self.classify(ln) for ln in lines] or [dict(SILENT_CONTEMPLATION)]\n counts = Counter(r[\"intent\"] for r in results)\n top = max(counts.values())\n # Dominant intent = mode; ties resolve to the earliest line's intent.\n dominant = next(r for r in results if counts[r[\"intent\"]] == top)\n avg_conf = sum(r[\"confidence\"] for r in results) / len(results)\n pct = round(avg_conf * 100)\n return (\n f\"Thus the Spirit speaks over this creation: the prevailing wind is \"\n f\"'{dominant['intent']}', discerned with {pct}% certainty. \"\n f\"{dominant['spiritual_intent']} \"\n f\"Therefore the counsel of heaven is this: {dominant['suggestion']}\"\n )\n\n # ------------------------------------------------- v4.0: intent layer\n\n def declare_intent(self, rite_name: str, text: str) -> None:\n \"\"\"Register a natural-language intent on a named rite.\"\"\"\n self.declared_intents[str(rite_name)] = str(text)\n\n def intents_aligned(self, declared: str, discerned: dict) -> bool:\n \"\"\"True when the declared intent shares a keyword with the discerned one.\n\n *declared* is the natural-language text from DECLARE INTENT;\n *discerned* is a classify() result for the rite's actual words.\n The Spirit counsels on divergence; it never condemns.\n \"\"\"\n declared_words = _keywords(declared)\n discerned_words = (\n _keywords(discerned.get(\"intent\") or \"\")\n | _keywords(discerned.get(\"spiritual_intent\") or \"\")\n | {str(k).lower() for k in (discerned.get(\"keywords\") or [])}\n )\n return bool(declared_words & discerned_words)\n\n def resolve_intent(self, text: str) -> dict:\n \"\"\"Classify *text* and report which declared intents it aligns with.\n\n Returns the classify() payload plus ``aligned_with``: a list of\n ``{rite, declared, shared_keywords}`` for every declared intent\n sharing at least one keyword with the text.\n \"\"\"\n result = self.classify(text)\n words = _keywords(text)\n aligned_with = []\n for rite, declared in self.declared_intents.items():\n shared = sorted(words & _keywords(declared))\n if shared:\n aligned_with.append(\n {\"rite\": rite, \"declared\": declared,\n \"shared_keywords\": shared}\n )\n result[\"aligned_with\"] = aligned_with\n return result\n\n def counsel(self, question: str) -> str:\n \"\"\"Speak 2-3 sentences of counsel over a question, in prophesy's voice.\"\"\"\n r = self.classify(question)\n pct = round(r[\"confidence\"] * 100)\n return (\n f\"Concerning '{question}', the Spirit discerns '{r['intent']}' \"\n f\"with {pct}% certainty. {r['spiritual_intent']} \"\n f\"Therefore the counsel of heaven is this: {r['suggestion']}\"\n )\n","godcode/stdlib_commons.py":"\"\"\"God Code standard library, part 4: the commons.\n\nThis module holds the everyday tools a working language needs: trimming\nand searching words, sorting and gathering lists, reading maps, and\nrounding numbers. They are kept apart from the interpreter core so the\nlanguage's heart stays small.\n\nWiring\n------\n``register(interp)`` adds the builtins to ``interp._builtins``. Each\nbuiltin is a plain callable ``(args, line)`` in the style of the core\nbuiltins (arity through ``interp._arity``, plain-word GodRuntimeError\nmessages).\n\nSandbox honesty\n---------------\nEvery rite here is pure computation: words, lists, maps, and numbers\nin, new values out. They touch no files, no network, and no host\nresources. They need no sandbox grant and behave the same under\n``godcode run --sandbox``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport math\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodRuntimeError\n\n__all__ = [\"register\"]\n\n\n# ------------------------------------------------------------ value helpers\n\n\ndef _as_word(interp, name: str, value: Any, line) -> str:\n \"\"\"Take a God Code word, number, or truth as plain text.\n\n Lists, maps, void, rites, and contracts have no plain-text shape\n for a word tool, so they are refused with a gentle error.\n \"\"\"\n from godcode.values import Symbol\n\n if not isinstance(value, (str, bool, int, float, Symbol)):\n raise GodRuntimeError(\n f\"{name} works on words, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return interp.stringify(value)\n\n\ndef _need_list(interp, name: str, value: Any, line) -> list:\n if not isinstance(value, list):\n raise GodRuntimeError(\n f\"{name} gathers a list, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return value\n\n\ndef _need_map(interp, name: str, value: Any, line) -> dict:\n if not isinstance(value, dict):\n raise GodRuntimeError(\n f\"{name} reads a map, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return value\n\n\ndef _need_number(interp, name: str, value: Any, line) -> int | float:\n if isinstance(value, bool) or not isinstance(value, (int, float)):\n raise GodRuntimeError(\n f\"{name} weighs a number, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return value\n\n\ndef _need_int(interp, name: str, value: Any, line) -> int:\n number = _need_number(interp, name, value, line)\n if isinstance(number, float) and not number.is_integer():\n raise GodRuntimeError(\n f\"{name} counts in whole numbers, but {interp.stringify(value)} \"\n \"was offered.\",\n line,\n )\n return int(number)\n\n\ndef _sort_key(interp, name: str, value: Any, line):\n \"\"\"A sortable key for one list member: numbers, words, or truths.\n\n Mixed kinds cannot be ordered against each other, so they are\n refused with a gentle error.\n \"\"\"\n if isinstance(value, bool):\n return (2, int(value))\n if isinstance(value, (int, float)):\n return (0, value)\n if isinstance(value, str):\n return (1, value)\n raise GodRuntimeError(\n f\"{name} can order numbers, words, and truths together, but \"\n f\"a {interp.type_name(value)} was found among them.\",\n line,\n )\n\n\ndef _ordered(interp, name: str, values: list, line) -> list:\n \"\"\"Check every member is orderable; refuse mixed kinds gently.\"\"\"\n kinds = set()\n for value in values:\n if isinstance(value, bool):\n kinds.add(\"truth\")\n elif isinstance(value, (int, float)):\n kinds.add(\"number\")\n elif isinstance(value, str):\n kinds.add(\"word\")\n else:\n raise GodRuntimeError(\n f\"{name} can order numbers, words, and truths, but a \"\n f\"{interp.type_name(value)} was found among them.\",\n line,\n )\n if len(kinds) > 1:\n raise GodRuntimeError(\n f\"{name} cannot order a gathering of mixed kinds \"\n f\"({', '.join(sorted(kinds))}).\",\n line,\n )\n return values\n\n\n# ------------------------------------------------------------------ words\n\n\ndef trim(args, line, interp):\n interp._arity(\"TRIM\", args, 1, line)\n return _as_word(interp, \"TRIM\", args[0], line).strip()\n\n\ndef replace(args, line, interp):\n interp._arity(\"REPLACE\", args, 3, line)\n word = _as_word(interp, \"REPLACE\", args[0], line)\n old = _as_word(interp, \"REPLACE\", args[1], line)\n new = _as_word(interp, \"REPLACE\", args[2], line)\n if old == \"\":\n raise GodRuntimeError(\n \"REPLACE needs something to find: an empty word hides \"\n \"everywhere at once.\",\n line,\n )\n return word.replace(old, new)\n\n\ndef starts_with(args, line, interp):\n interp._arity(\"STARTS_WITH\", args, 2, line)\n word = _as_word(interp, \"STARTS_WITH\", args[0], line)\n prefix = _as_word(interp, \"STARTS_WITH\", args[1], line)\n return word.startswith(prefix)\n\n\ndef ends_with(args, line, interp):\n interp._arity(\"ENDS_WITH\", args, 2, line)\n word = _as_word(interp, \"ENDS_WITH\", args[0], line)\n suffix = _as_word(interp, \"ENDS_WITH\", args[1], line)\n return word.endswith(suffix)\n\n\ndef substring(args, line, interp):\n interp._arity(\"SUBSTRING\", args, (2, 3), line)\n word = _as_word(interp, \"SUBSTRING\", args[0], line)\n start = _need_int(interp, \"SUBSTRING\", args[1], line)\n end = _need_int(interp, \"SUBSTRING\", args[2], line) if len(args) == 3 else len(word)\n start = max(0, min(start, len(word)))\n end = max(0, min(end, len(word)))\n return word[start:end]\n\n\ndef contains(args, line, interp):\n interp._arity(\"CONTAINS\", args, 2, line)\n haystack, needle = args[0], args[1]\n if isinstance(haystack, str):\n return _as_word(interp, \"CONTAINS\", needle, line) in haystack\n if isinstance(haystack, list):\n return any(item == needle for item in haystack)\n raise GodRuntimeError(\n \"CONTAINS searches a word or a list, but a \"\n f\"{interp.type_name(haystack)} was offered.\",\n line,\n )\n\n\ndef count(args, line, interp):\n interp._arity(\"COUNT\", args, 2, line)\n word = _as_word(interp, \"COUNT\", args[0], line)\n part = _as_word(interp, \"COUNT\", args[1], line)\n if part == \"\":\n raise GodRuntimeError(\n \"COUNT needs something to count: an empty word hides \"\n \"everywhere at once.\",\n line,\n )\n return word.count(part)\n\n\ndef repeat(args, line, interp):\n interp._arity(\"REPEAT\", args, 2, line)\n word = _as_word(interp, \"REPEAT\", args[0], line)\n times = _need_int(interp, \"REPEAT\", args[1], line)\n if times < 0:\n raise GodRuntimeError(\n \"REPEAT counts from zero upward: a negative count was offered.\",\n line,\n )\n return word * times\n\n\n# ------------------------------------------------------------------ lists\n\n\ndef sort_list(args, line, interp):\n interp._arity(\"SORT\", args, 1, line)\n values = _ordered(interp, \"SORT\", _need_list(interp, \"SORT\", args[0], line), line)\n return sorted(values, key=lambda v: _sort_key(interp, \"SORT\", v, line)[1:])\n\n\ndef min_of(args, line, interp):\n interp._arity(\"MIN_OF\", args, 1, line)\n values = _ordered(interp, \"MIN_OF\", _need_list(interp, \"MIN_OF\", args[0], line), line)\n if not values:\n raise GodRuntimeError(\n \"MIN_OF found an empty gathering: there is no least among nothing.\",\n line,\n )\n return min(values, key=lambda v: _sort_key(interp, \"MIN_OF\", v, line)[1:])\n\n\ndef max_of(args, line, interp):\n interp._arity(\"MAX_OF\", args, 1, line)\n values = _ordered(interp, \"MAX_OF\", _need_list(interp, \"MAX_OF\", args[0], line), line)\n if not values:\n raise GodRuntimeError(\n \"MAX_OF found an empty gathering: there is no greatest among nothing.\",\n line,\n )\n return max(values, key=lambda v: _sort_key(interp, \"MAX_OF\", v, line)[1:])\n\n\ndef sum_of(args, line, interp):\n interp._arity(\"SUM_OF\", args, 1, line)\n values = _need_list(interp, \"SUM_OF\", args[0], line)\n total: int | float = 0\n for value in values:\n number = _need_number(interp, \"SUM_OF\", value, line)\n total += number\n return total\n\n\ndef first(args, line, interp):\n interp._arity(\"FIRST\", args, 1, line)\n values = _need_list(interp, \"FIRST\", args[0], line)\n if not values:\n raise GodRuntimeError(\n \"FIRST found an empty gathering: nothing stands at its head.\",\n line,\n )\n return values[0]\n\n\ndef last(args, line, interp):\n interp._arity(\"LAST\", args, 1, line)\n values = _need_list(interp, \"LAST\", args[0], line)\n if not values:\n raise GodRuntimeError(\n \"LAST found an empty gathering: nothing stands at its end.\",\n line,\n )\n return values[-1]\n\n\ndef unique(args, line, interp):\n interp._arity(\"UNIQUE\", args, 1, line)\n values = _need_list(interp, \"UNIQUE\", args[0], line)\n seen: list = []\n for value in values:\n if not any(value == other for other in seen):\n seen.append(value)\n return seen\n\n\ndef index_of(args, line, interp):\n interp._arity(\"INDEX_OF\", args, 2, line)\n values = _need_list(interp, \"INDEX_OF\", args[0], line)\n for position, value in enumerate(values):\n if value == args[1]:\n return position\n return -1\n\n\n# ------------------------------------------------------------------- maps\n\n\ndef keys(args, line, interp):\n interp._arity(\"KEYS\", args, 1, line)\n return list(_need_map(interp, \"KEYS\", args[0], line).keys())\n\n\ndef values_of(args, line, interp):\n interp._arity(\"VALUES\", args, 1, line)\n return list(_need_map(interp, \"VALUES\", args[0], line).values())\n\n\ndef has_key(args, line, interp):\n interp._arity(\"HAS_KEY\", args, 2, line)\n mapping = _need_map(interp, \"HAS_KEY\", args[0], line)\n key = args[1]\n if not isinstance(key, str):\n raise GodRuntimeError(\n \"HAS_KEY looks up a word, but a \"\n f\"{interp.type_name(key)} was offered as the key.\",\n line,\n )\n return str(key) in mapping\n\n\ndef merge(args, line, interp):\n interp._arity(\"MERGE\", args, 2, line)\n first_map = _need_map(interp, \"MERGE\", args[0], line)\n second_map = _need_map(interp, \"MERGE\", args[1], line)\n merged = dict(first_map)\n merged.update(second_map)\n return merged\n\n\n# ---------------------------------------------------------------- numbers\n\n\ndef absolute(args, line, interp):\n interp._arity(\"ABS\", args, 1, line)\n return abs(_need_number(interp, \"ABS\", args[0], line))\n\n\ndef round_number(args, line, interp):\n interp._arity(\"ROUND\", args, (1, 2), line)\n number = _need_number(interp, \"ROUND\", args[0], line)\n places = _need_int(interp, \"ROUND\", args[1], line) if len(args) == 2 else 0\n if places < 0:\n raise GodRuntimeError(\n \"ROUND counts places from zero upward: a negative count \"\n \"was offered.\",\n line,\n )\n rounded = Decimal(str(number)).quantize(\n Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP\n )\n if places == 0:\n return int(rounded)\n return float(rounded)\n\n\ndef floor_number(args, line, interp):\n interp._arity(\"FLOOR\", args, 1, line)\n return math.floor(_need_number(interp, \"FLOOR\", args[0], line))\n\n\ndef ceil_number(args, line, interp):\n interp._arity(\"CEIL\", args, 1, line)\n return math.ceil(_need_number(interp, \"CEIL\", args[0], line))\n\n\ndef sqrt_number(args, line, interp):\n interp._arity(\"SQRT\", args, 1, line)\n number = _need_number(interp, \"SQRT\", args[0], line)\n if number < 0:\n raise GodRuntimeError(\n \"SQRT cannot root a negative number: no real answer lives there.\",\n line,\n )\n rooted = math.sqrt(number)\n if float(rooted).is_integer():\n return int(rooted)\n return rooted\n\n\ndef power(args, line, interp):\n interp._arity(\"POW\", args, 2, line)\n base = _need_number(interp, \"POW\", args[0], line)\n exp = _need_number(interp, \"POW\", args[1], line)\n try:\n result = math.pow(base, exp)\n except (ValueError, OverflowError):\n raise GodRuntimeError(\n \"POW cannot raise that pair: the answer leaves the real numbers.\",\n line,\n ) from None\n if float(result).is_integer() and abs(result) < 1e15:\n return int(result)\n return result\n\n\n# ---------------------------------------------------------------- wiring\n\n\ndef register(interp) -> dict[str, Callable[..., Any]]:\n \"\"\"Add the commons builtins to ``interp._builtins``; return them.\"\"\"\n names_funcs = [\n (\"TRIM\", trim),\n (\"REPLACE\", replace),\n (\"STARTS_WITH\", starts_with),\n (\"ENDS_WITH\", ends_with),\n (\"SUBSTRING\", substring),\n (\"CONTAINS\", contains),\n (\"COUNT\", count),\n (\"REPEAT\", repeat),\n (\"SORT\", sort_list),\n (\"MIN_OF\", min_of),\n (\"MAX_OF\", max_of),\n (\"SUM_OF\", sum_of),\n (\"FIRST\", first),\n (\"LAST\", last),\n (\"UNIQUE\", unique),\n (\"INDEX_OF\", index_of),\n (\"KEYS\", keys),\n (\"VALUES\", values_of),\n (\"HAS_KEY\", has_key),\n (\"MERGE\", merge),\n (\"ABS\", absolute),\n (\"ROUND\", round_number),\n (\"FLOOR\", floor_number),\n (\"CEIL\", ceil_number),\n (\"SQRT\", sqrt_number),\n (\"POW\", power),\n ]\n builtins: dict[str, Callable[..., Any]] = {}\n for name, func in names_funcs:\n\n def _builtin(args, line, _func=func):\n return _func(args, line, interp)\n\n builtins[name] = _builtin\n interp._builtins.update(builtins)\n return builtins\n","godcode/stdlib_hashes.py":"\"\"\"God Code standard library, part 3: the scrollhouse of hashes and veils.\n\nThis module holds builtins that fingerprint and seal words: SHA-256\ndigests, HMAC-SHA-256 signatures, and the veils of base64. They are kept\napart from the interpreter core so the language's heart stays small.\n\nWiring\n------\n``register(interp)`` adds the builtins to ``interp._builtins``. Each\nbuiltin is a plain callable ``(args, line)`` in the style of the core\nbuiltins (arity through ``interp._arity``, plain-word GodRuntimeError\nmessages).\n\nSandbox honesty\n---------------\nSHA256, HMAC, BASE64_ENCODE, and BASE64_DECODE are pure computation:\nthey touch no files, no network, and no host resources. They need no\nsandbox grant and behave the same under ``godcode run --sandbox``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport base64\nimport hashlib\nimport hmac\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodRuntimeError\n\n__all__ = [\"register\"]\n\n\n# ------------------------------------------------------------ value helpers\n\n\ndef _as_text(interp, name: str, value: Any, line) -> str:\n \"\"\"Take a God Code word, number, or truth as plain text.\n\n Lists, maps, void, rites, and contracts have no plain-text shape\n for a fingerprint, so they are refused with a gentle error.\n \"\"\"\n from godcode.values import Symbol\n\n if not isinstance(value, (str, bool, int, float, Symbol)):\n raise GodRuntimeError(\n f\"{name} can fingerprint a word, a number, or a truth, \"\n f\"but a {interp.type_name(value)} was offered.\",\n line,\n )\n return interp.stringify(value)\n\n\ndef sha256(args, line, interp):\n interp._arity(\"SHA256\", args, 1, line)\n text = _as_text(interp, \"SHA256\", args[0], line)\n return hashlib.sha256(text.encode(\"utf-8\")).hexdigest()\n\n\ndef hmac_sha256(args, line, interp):\n interp._arity(\"HMAC\", args, 2, line)\n key = _as_text(interp, \"HMAC\", args[0], line)\n message = _as_text(interp, \"HMAC\", args[1], line)\n digest = hmac.new(\n key.encode(\"utf-8\"), message.encode(\"utf-8\"), hashlib.sha256\n )\n return digest.hexdigest()\n\n\ndef base64_encode(args, line, interp):\n interp._arity(\"BASE64_ENCODE\", args, 1, line)\n text = _as_text(interp, \"BASE64_ENCODE\", args[0], line)\n return base64.b64encode(text.encode(\"utf-8\")).decode(\"ascii\")\n\n\ndef base64_decode(args, line, interp):\n interp._arity(\"BASE64_DECODE\", args, 1, line)\n value = args[0]\n from godcode.values import Symbol\n\n if not isinstance(value, (str, Symbol)):\n raise GodRuntimeError(\n \"BASE64_DECODE needs a veiled word to lift, \"\n f\"but a {interp.type_name(value)} was offered.\",\n line,\n )\n veiled = str(value)\n try:\n raw = base64.b64decode(veiled, validate=True)\n return raw.decode(\"utf-8\")\n except (ValueError, UnicodeDecodeError):\n raise GodRuntimeError(\n \"BASE64_DECODE met a veil it cannot lift: the word is not \"\n \"well-formed base64.\",\n line,\n ) from None\n\n\ndef register(interp) -> dict[str, Callable[..., Any]]:\n \"\"\"Add the hash builtins to ``interp._builtins``; return them.\"\"\"\n arity = interp._arity\n\n def _sha256(args, line):\n return sha256(args, line, interp)\n\n def _hmac(args, line):\n return hmac_sha256(args, line, interp)\n\n def _b64e(args, line):\n return base64_encode(args, line, interp)\n\n def _b64d(args, line):\n return base64_decode(args, line, interp)\n\n builtins: dict[str, Callable[..., Any]] = {\n \"SHA256\": _sha256,\n \"HMAC\": _hmac,\n \"BASE64_ENCODE\": _b64e,\n \"BASE64_DECODE\": _b64d,\n }\n interp._builtins.update(builtins)\n return builtins\n","godcode/stdlib_times.py":"\"\"\"Date, time, and web rites for the God Code standard library (part 2).\n\n``register(interp)`` adds four rites to an interpreter's ``_builtins``:\n\n- ``DATE_TODAY()`` — today's local date as a word: ``\"2026-09-24\"``.\n- ``TIME_NOW()`` — the current local time as an ISO 8601 word.\n- ``FORMAT_DATE(date_text, pattern)`` — a ``\"YYYY-MM-DD\"`` word shaped by\n a strftime-style pattern word.\n- ``HTTP_GET(url)`` — the body of an HTTP GET request, as a UTF-8 word.\n\nThe names avoid ``NOW`` and ``TODAY`` on purpose: the bundled scroll\n``godcode/scrolls/time.god`` already defines rites by those names, and a\nbuiltin would shadow them. ``DATE_TODAY``, ``TIME_NOW``, ``FORMAT_DATE``,\nand ``HTTP_GET`` keep their distance.\n\n``HTTP_GET`` follows redirects and waits up to ten seconds. Under\n``godcode run --sandbox`` the rite is withheld when the policy denies\nnetwork (see ``godcode/sandbox.py``): it raises instead of reaching out.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport urllib.error\nimport urllib.request\nfrom datetime import date, datetime\n\nfrom godcode.errors import GodRuntimeError\n\n__all__ = [\"register\"]\n\n_HTTP_TIMEOUT_SECONDS = 10\n\n\ndef register(interp) -> None:\n \"\"\"Add the date/time and web rites to ``interp._builtins``.\n\n Each rite is a callable taking ``(args, line)``, in the same shape as\n the core builtins in ``godcode/interpreter.py``.\n \"\"\"\n builtins = interp._builtins\n\n def date_today(args, line):\n interp._arity(\"DATE_TODAY\", args, 0, line)\n return date.today().isoformat()\n\n def time_now(args, line):\n interp._arity(\"TIME_NOW\", args, 0, line)\n return datetime.now().astimezone().isoformat()\n\n def format_date(args, line):\n interp._arity(\"FORMAT_DATE\", args, 2, line)\n date_text, pattern = args\n if not isinstance(date_text, str):\n raise GodRuntimeError(\n \"FORMAT_DATE needs the date as a word, not \"\n f\"{interp.type_name(date_text)}.\",\n line,\n )\n if not isinstance(pattern, str):\n raise GodRuntimeError(\n \"FORMAT_DATE needs the pattern as a word, not \"\n f\"{interp.type_name(pattern)}.\",\n line,\n )\n try:\n day = datetime.strptime(date_text.strip(), \"%Y-%m-%d\")\n except ValueError:\n raise GodRuntimeError(\n f\"FORMAT_DATE cannot read '{date_text}' as a date. \"\n \"Write it YYYY-MM-DD.\",\n line,\n ) from None\n return day.strftime(str(pattern))\n\n def http_get(args, line):\n interp._arity(\"HTTP_GET\", args, 1, line)\n url = args[0]\n if not isinstance(url, str):\n raise GodRuntimeError(\n \"HTTP_GET needs the address as a word, not \"\n f\"{interp.type_name(url)}.\",\n line,\n )\n request = urllib.request.Request(\n str(url), headers={\"User-Agent\": \"GodCode\"}\n )\n try:\n with urllib.request.urlopen(\n request, timeout=_HTTP_TIMEOUT_SECONDS\n ) as response:\n body = response.read()\n except Exception:\n # Every network failure — refused, unroutable, timed out,\n # bad address — is answered the same plain way. It never\n # hangs past the timeout and never succeeds silently.\n raise GodRuntimeError(\n f\"HTTP_GET could not reach '{url}'. The web did not answer.\",\n line,\n ) from None\n return body.decode(\"utf-8\", errors=\"replace\")\n\n builtins[\"DATE_TODAY\"] = date_today\n builtins[\"TIME_NOW\"] = time_now\n builtins[\"FORMAT_DATE\"] = format_date\n builtins[\"HTTP_GET\"] = http_get\n","godcode/stdlib_vault.py":"\"\"\"God Code standard library, part 1: the vault of JSON and the filesystem.\n\nThis module holds builtins that read and write the outer world: parsing\nand rendering JSON, and reading, writing, and listing files. It is kept\napart from the interpreter core so the language's heart stays small.\n\nWiring\n------\n``register(interp)`` adds the builtins to ``interp._builtins``. Each\nbuiltin is a plain callable ``(args, line)`` in the style of the core\nbuiltins (arity through ``interp._arity``, plain-word GodRuntimeError\nmessages).\n\nSandbox honesty\n---------------\nREAD_FILE, WRITE_FILE, LIST_DIR, and FILE_EXISTS reach the host\nfilesystem. When the interpreter runs under ``godcode.sandbox``, the\nsandbox guard (``interp._sandbox_guard``, installed by\n``Sandbox.install``) carries the policy, and these builtins honor it:\n\n* writes are refused unless the policy grants ``allow_write``;\n* reads are refused unless the policy grants ``allow_read_paths``,\n and then only under one of the granted directories.\n\nJSON_PARSE and JSON_STRING are pure and need no grant.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodRuntimeError, SandboxViolation\nfrom godcode.values import Contract, RiteFunction, Symbol\n\n__all__ = [\"register\"]\n\n\n# ------------------------------------------------------------ value helpers\n\n\ndef _as_word(interp, name: str, value: Any, line) -> str:\n \"\"\"Take a God Code word as plain text. Symbols give up their text.\"\"\"\n if isinstance(value, Symbol):\n return str(value)\n if isinstance(value, str):\n return value\n raise GodRuntimeError(\n f\"{name} needs a word, but a {interp.type_name(value)} was offered.\",\n line,\n )\n\n\ndef _from_json(value: Any) -> Any:\n \"\"\"Turn a json.loads result into God Code values.\n\n Objects become maps, arrays become lists, null becomes void.\n Numbers, words, and booleans cross over unchanged.\n \"\"\"\n if value is None or isinstance(value, (bool, int, float, str)):\n return value\n if isinstance(value, list):\n return [_from_json(item) for item in value]\n if isinstance(value, dict):\n return {str(key): _from_json(item) for key, item in value.items()}\n raise GodRuntimeError(f\"JSON_PARSE met a value it cannot carry: {value!r}.\")\n\n\ndef _to_json_text(interp, value: Any, line) -> str:\n \"\"\"Render a God Code value as compact JSON.\n\n Raises a plain GodRuntimeError for values JSON cannot carry:\n rites, contracts, symbols, non-word map keys, and numbers with no\n JSON shape (infinity, not-a-number).\n \"\"\"\n if value is None:\n return \"null\"\n if isinstance(value, bool):\n return \"true\" if value else \"false\"\n if isinstance(value, Symbol):\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a symbol. \"\n \"Only words, numbers, booleans, lists, and maps have a JSON shape.\",\n line,\n )\n if isinstance(value, str):\n return json.dumps(value)\n if isinstance(value, (int, float)):\n try:\n return json.dumps(value, allow_nan=False)\n except ValueError:\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a number with no JSON shape, \"\n \"like infinity or not-a-number.\",\n line,\n ) from None\n if isinstance(value, list):\n inner = \",\".join(_to_json_text(interp, item, line) for item in value)\n return \"[\" + inner + \"]\"\n if isinstance(value, dict):\n parts = []\n for key, item in value.items():\n if isinstance(key, Symbol) or not isinstance(key, str):\n raise GodRuntimeError(\n \"JSON_STRING needs map keys that are words. \"\n f\"A {interp.type_name(key)} key was found.\",\n line,\n )\n parts.append(json.dumps(key) + \":\" + _to_json_text(interp, item, line))\n return \"{\" + \",\".join(parts) + \"}\"\n if isinstance(value, RiteFunction):\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a rite. Rites have no JSON shape.\",\n line,\n )\n if isinstance(value, Contract):\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a contract. Contracts have no JSON shape.\",\n line,\n )\n raise GodRuntimeError(\n f\"JSON_STRING cannot carry {interp.type_name(value)}. \"\n \"Only words, numbers, booleans, lists, and maps have a JSON shape.\",\n line,\n )\n\n\n# ------------------------------------------------------------ sandbox guard\n\n\ndef _guard(interp):\n \"\"\"The sandbox guard, if this interpreter runs under godcode.sandbox.\"\"\"\n return getattr(interp, \"_sandbox_guard\", None)\n\n\ndef _check_read_grant(interp, rite: str, path: str, line) -> None:\n \"\"\"Refuse filesystem reads the sandbox policy does not grant.\n\n No guard means no sandbox: the read proceeds. Under a guard, reads\n need ``allow_read_paths``, and the resolved path must lie under one\n of the granted directories (the same rule the sandbox applies to\n scroll imports).\n \"\"\"\n guard = _guard(interp)\n if guard is None:\n return\n allowed = guard.policy.allow_read_paths\n if not allowed:\n raise SandboxViolation(\n f\"The sandbox withholds this power: the rite {rite} would read \"\n \"from the outer world. It is not granted.\",\n line,\n )\n resolved = os.path.realpath(path)\n for base in allowed:\n base_resolved = os.path.realpath(base)\n # A grant on the filesystem root blesses everything, as in a\n # plain `godcode run` with no guard installed.\n if base_resolved == os.path.realpath(os.sep):\n _check_manifest_path(interp, \"read\", rite, path, line)\n return\n if resolved == base_resolved or resolved.startswith(base_resolved + os.sep):\n _check_manifest_path(interp, \"read\", rite, path, line)\n return\n raise SandboxViolation(\n f\"The sandbox withholds this power: the rite {rite} may not read \"\n f\"'{path}'. It lies outside the granted paths.\",\n line,\n )\n\n\ndef _check_manifest_path(interp, kind: str, rite: str, path: str, line) -> None:\n \"\"\"Refuse filesystem access the scroll's permission manifest withholds.\n\n The guard's own ``check_rite`` already polices the call through the\n interpreter's dispatch; the vault reaches the filesystem directly, so\n it applies the manifest's target rule here as well.\n \"\"\"\n manifest = getattr(interp, \"manifest\", None)\n if not manifest:\n return\n # The manifest holds absolute prefixes; realpath() resolves the\n # runtime target exactly the way open() will, so the check mirrors\n # the file the rite is about to touch.\n allowed = (\n manifest.allows_read(path) if kind == \"read\"\n else manifest.allows_write(path)\n )\n if not allowed:\n raise SandboxViolation(\n f\"The scroll reaches for a power it did not declare: the rite \"\n f\"{rite} may not touch '{path}'. Declare it at the top of the \"\n f\"scroll with DECLARE PERMISSION TO, or leave the power \"\n f\"untouched.\",\n line,\n )\n\n\ndef _check_write_grant(interp, path: str, line) -> None:\n \"\"\"Refuse filesystem writes the sandbox policy does not grant.\"\"\"\n guard = _guard(interp)\n if guard is None:\n return\n if not guard.policy.allow_write:\n raise SandboxViolation(\n \"The sandbox withholds this power: the rite WRITE_FILE would \"\n f\"write '{path}' to the outer world. It is not granted.\",\n line,\n )\n _check_manifest_path(interp, \"write\", \"WRITE_FILE\", path, line)\n\n\n# ------------------------------------------------------------------ register\n\n\ndef register(interp) -> None:\n \"\"\"Add the vault builtins to ``interp._builtins``.\n\n Idempotent: calling it twice simply replaces the same six entries.\n \"\"\"\n arity = interp._arity\n\n def json_parse(args, line):\n arity(\"JSON_PARSE\", args, 1, line)\n text = _as_word(interp, \"JSON_PARSE\", args[0], line)\n try:\n return _from_json(json.loads(text))\n except json.JSONDecodeError as exc:\n raise GodRuntimeError(\n f\"JSON_PARSE could not read that word as JSON. {exc.msg}: \"\n f\"line {exc.lineno} column {exc.colno}.\",\n line,\n ) from None\n\n def json_string(args, line):\n arity(\"JSON_STRING\", args, 1, line)\n return _to_json_text(interp, args[0], line)\n\n def read_file(args, line):\n arity(\"READ_FILE\", args, 1, line)\n path = _as_word(interp, \"READ_FILE\", args[0], line)\n _check_read_grant(interp, \"READ_FILE\", path, line)\n try:\n with open(path, \"r\", encoding=\"utf-8\") as handle:\n return handle.read()\n except OSError as exc:\n raise GodRuntimeError(\n f\"READ_FILE could not read '{path}'. {exc.strerror or exc}.\",\n line,\n ) from None\n\n def write_file(args, line):\n arity(\"WRITE_FILE\", args, 2, line)\n path = _as_word(interp, \"WRITE_FILE\", args[0], line)\n text = _as_word(interp, \"WRITE_FILE\", args[1], line)\n _check_write_grant(interp, path, line)\n try:\n with open(path, \"w\", encoding=\"utf-8\") as handle:\n return handle.write(text)\n except OSError as exc:\n raise GodRuntimeError(\n f\"WRITE_FILE could not write '{path}'. {exc.strerror or exc}.\",\n line,\n ) from None\n\n def file_exists(args, line):\n arity(\"FILE_EXISTS\", args, 1, line)\n path = _as_word(interp, \"FILE_EXISTS\", args[0], line)\n _check_read_grant(interp, \"FILE_EXISTS\", path, line)\n return os.path.exists(path)\n\n def list_dir(args, line):\n arity(\"LIST_DIR\", args, 1, line)\n path = _as_word(interp, \"LIST_DIR\", args[0], line)\n _check_read_grant(interp, \"LIST_DIR\", path, line)\n if not os.path.isdir(path):\n raise GodRuntimeError(\n f\"LIST_DIR needs a directory, but '{path}' is not one.\",\n line,\n )\n try:\n entries = os.listdir(path)\n except OSError as exc:\n raise GodRuntimeError(\n f\"LIST_DIR could not open '{path}'. {exc.strerror or exc}.\",\n line,\n ) from None\n return sorted(str(entry) for entry in entries)\n\n builtins: dict[str, Callable[..., Any]] = {\n \"JSON_PARSE\": json_parse,\n \"JSON_STRING\": json_string,\n \"READ_FILE\": read_file,\n \"WRITE_FILE\": write_file,\n \"FILE_EXISTS\": file_exists,\n \"LIST_DIR\": list_dir,\n }\n interp._builtins.update(builtins)\n","godcode/tester.py":"\"\"\"The God Code test runner, behind `godcode test`.\n\nConvention: a *test scroll* is any `.god` file named `test_*.god` or\n`*_test.god`. Inside it, every rite named `TEST_*` (case-insensitive) is\none test case. The scroll is parsed once; then each `TEST_*` rite runs in\na FRESH `Interpreter`, so tests cannot leak state into each other. A\n`TESTIFY` failure fails that test, and any runtime error fails it too,\nwith the error message carried in the report.\n\nDiscovery reads only the given directory itself; subfolders are not\nentered. The runner binds no Spirit, no covenant ledger, and no audit log\n(`log_path=None`), and it runs scrolls the same way `godcode run` does\n(not sandboxed): only test scrolls you wrote or trust.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\nfrom godcode.ast import CreationBlock, DefineRite\nfrom godcode.errors import GodCodeError\nfrom godcode.interpreter import Interpreter\nfrom godcode.tongues import parse_source\nfrom godcode.values import RiteFunction\n\n#: Rite label used when the failure belongs to the scroll itself (it could\n#: not be read or parsed), not to any single rite.\nSCROLL_LEVEL = \"(scroll)\"\n\n\n# ---------------------------------------------------------------------------\n# results\n# ---------------------------------------------------------------------------\n@dataclass\nclass TestResult:\n \"\"\"One test's outcome. `ok` is True (passed), False (failed), or None\n (skipped, e.g. the rite asks for offerings).\"\"\"\n\n file: str\n rite: str\n ok: bool | None\n message: str = \"\"\n\n\n@dataclass\nclass TestReport:\n results: list[TestResult] = field(default_factory=list)\n #: Names of test scrolls that held no TEST_ rites at all.\n empty_files: list[str] = field(default_factory=list)\n\n @property\n def passed(self) -> int:\n return sum(1 for r in self.results if r.ok is True)\n\n @property\n def failed(self) -> int:\n return sum(1 for r in self.results if r.ok is False)\n\n @property\n def skipped(self) -> int:\n return sum(1 for r in self.results if r.ok is None)\n\n def text_lines(self) -> list[str]:\n \"\"\"Human report: one line per test, then the summary line.\"\"\"\n lines = []\n for r in self.results:\n status = \"PASS\" if r.ok is True else (\"SKIP\" if r.ok is None else \"FAIL\")\n line = f\"{status} {r.file} :: {r.rite}\"\n if r.message:\n line += f\" :: {r.message}\"\n lines.append(line)\n for name in self.empty_files:\n lines.append(f\"{name} :: no TEST_ rites found.\")\n parts = [f\"{self.passed} passed\", f\"{self.failed} failed\"]\n if self.skipped:\n parts.append(f\"{self.skipped} skipped\")\n lines.append(\", \".join(parts) + \".\")\n return lines\n\n def payload(self, dir_label: str) -> dict:\n \"\"\"Machine report for `godcode test --json`.\"\"\"\n return {\n \"tool\": \"godcode\",\n \"command\": \"test\",\n \"dir\": dir_label,\n \"tests\": [\n {\"file\": r.file, \"rite\": r.rite, \"ok\": r.ok, \"message\": r.message}\n for r in self.results\n ],\n \"passed\": self.passed,\n \"failed\": self.failed,\n \"skipped\": self.skipped,\n }\n\n\n# ---------------------------------------------------------------------------\n# discovery\n# ---------------------------------------------------------------------------\ndef is_test_file(name: str) -> bool:\n \"\"\"True for `test_*.god` and `*_test.god` (case-insensitive).\"\"\"\n lowered = name.lower()\n return lowered.endswith(\".god\") and (\n lowered.startswith(\"test_\") or lowered[:-4].endswith(\"_test\")\n )\n\n\ndef discover_test_files(directory: Path) -> list[Path]:\n \"\"\"Test scrolls in `directory`, sorted by name. Non-recursive: only the\n directory itself is read, subfolders are not entered.\"\"\"\n return sorted(\n (p for p in directory.iterdir() if p.is_file() and is_test_file(p.name)),\n key=lambda p: p.name,\n )\n\n\n# ---------------------------------------------------------------------------\n# collection\n# ---------------------------------------------------------------------------\ndef _top_level_statements(program) -> list:\n stmts = getattr(program, \"statements\", None) or []\n if len(stmts) == 1 and isinstance(stmts[0], CreationBlock):\n return stmts[0].statements\n return stmts\n\n\ndef collect_test_rites(program) -> list[DefineRite]:\n \"\"\"The `TEST_*` rites defined at the scroll's top level, in definition\n order. A repeated name keeps its first position but the last definition\n wins when the rite runs (as `DECLARE` would).\"\"\"\n found: dict[str, DefineRite] = {}\n for stmt in _top_level_statements(program):\n if isinstance(stmt, DefineRite) and stmt.name.upper().startswith(\"TEST_\"):\n found[stmt.name] = stmt\n return list(found.values())\n\n\n# ---------------------------------------------------------------------------\n# execution\n# ---------------------------------------------------------------------------\ndef _parse_scroll(path: Path):\n source = path.read_text(encoding=\"utf-8\")\n return parse_source(source)\n\n\ndef _run_rite(program, rite_node: DefineRite, file_label: str) -> TestResult:\n \"\"\"Run one TEST_ rite in a fresh interpreter and report the outcome.\"\"\"\n interp = Interpreter(log_path=None)\n buf = io.StringIO()\n # The runner's own report must stay one line per test: swallow REVEAL\n # lines, [TESTIFY] notices, and any other chatter the scroll makes.\n with contextlib.redirect_stdout(buf):\n try:\n interp.run(program, source_name=file_label)\n except GodCodeError as err:\n return TestResult(file_label, rite_node.name, False,\n f\"the scroll could not be prepared: {err}\")\n except Exception as exc: # an engine fault, not a test failure\n return TestResult(file_label, rite_node.name, False,\n f\"the scroll could not be prepared: \"\n f\"{type(exc).__name__}: {exc}\")\n target = interp.env.get(rite_node.name) \\\n if interp.env.is_bound(rite_node.name) else None\n if not isinstance(target, RiteFunction):\n return TestResult(\n file_label, rite_node.name, False,\n f\"the rite {rite_node.name} was not found \"\n f\"after the scroll ran.\")\n if target.params:\n n = len(target.params)\n return TestResult(\n file_label, rite_node.name, None,\n f\"the rite asks for {n} offering{'s' if n != 1 else ''}, \"\n f\"so it was not called.\")\n try:\n interp._call_rite(target, [], rite_node.line)\n except GodCodeError as err:\n return TestResult(file_label, rite_node.name, False, str(err))\n except Exception as exc: # an engine fault, not a test failure\n return TestResult(file_label, rite_node.name, False,\n f\"{type(exc).__name__}: {exc}\")\n return TestResult(file_label, rite_node.name, True, \"\")\n\n\ndef run_test_file(path: Path) -> tuple[list[TestResult], bool]:\n \"\"\"Parse `path` once, then run each TEST_ rite in isolation.\n\n Returns (results, is_empty). A scroll that cannot be read or parsed\n yields one file-level failure and never crashes the runner.\n \"\"\"\n label = path.name\n try:\n program = _parse_scroll(path)\n except GodCodeError as err:\n return [TestResult(label, SCROLL_LEVEL, False, str(err))], False\n except OSError as exc:\n return [TestResult(\n label, SCROLL_LEVEL, False,\n f\"the scroll could not be read: {exc.strerror or exc}\")], False\n rites = collect_test_rites(program)\n if not rites:\n return [], True\n return [_run_rite(program, rite, label) for rite in rites], False\n\n\ndef run_tests(directory: Path) -> TestReport:\n \"\"\"Discover test scrolls in `directory` and run them all.\"\"\"\n report = TestReport()\n for path in discover_test_files(directory):\n results, is_empty = run_test_file(path)\n report.results.extend(results)\n if is_empty:\n report.empty_files.append(path.name)\n return report\n","godcode/tokens.py":"\"\"\"Token types and the Token dataclass for God Code v2.0.\n\nKeyword tokens carry their canonical UPPER name as ``value``;\nidentifiers preserve the author's casing.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\n\nclass TokenType(Enum):\n # --- keywords -----------------------------------------------------------\n BEGIN = auto()\n CREATION = auto()\n END = auto()\n DECLARE = auto()\n AS = auto()\n BREATHE = auto()\n LIFE = auto()\n INTO = auto()\n REVEAL = auto()\n PROPHESY = auto()\n ASCEND = auto()\n IF = auto()\n THEN = auto()\n ELSE = auto()\n ENDIF = auto()\n FOR = auto()\n IN = auto()\n ENDFOR = auto()\n WHILE = auto()\n DO = auto()\n ENDWHILE = auto()\n BREAK = auto()\n CONTINUE = auto()\n TRY = auto()\n CATCH = auto()\n ENDTRY = auto()\n DEFINE = auto()\n RITE = auto()\n INVOKE = auto()\n RETURN = auto()\n IMPORT = auto()\n IS = auto()\n NOT = auto()\n AND = auto()\n OR = auto()\n # §4 additions (missed in §1's list)\n REFLECT = auto()\n BLESS = auto()\n ANOINT = auto()\n SEAL = auto()\n TESTIFY = auto()\n # boolean / void literals (added for fmt <-> parse round-trip fidelity)\n TRUE = auto()\n FALSE = auto()\n VOID = auto()\n # --- literals -----------------------------------------------------------\n NUMBER = auto()\n STRING = auto()\n IDENT = auto()\n # --- operators ----------------------------------------------------------\n PLUS = auto() # +\n MINUS = auto() # -\n STAR = auto() # *\n SLASH = auto() # /\n PERCENT = auto() # %\n EQ = auto() # = or ==\n NEQ = auto() # !=\n LT = auto() # <\n GT = auto() # >\n LTE = auto() # <=\n GTE = auto() # >=\n # --- punctuation --------------------------------------------------------\n LPAREN = auto()\n RPAREN = auto()\n LBRACKET = auto()\n RBRACKET = auto()\n COMMA = auto()\n # --- structural ---------------------------------------------------------\n NEWLINE = auto()\n EOF = auto()\n\n\n@dataclass\nclass Token:\n type: TokenType\n value: object # NUMBER -> int|float, STRING -> str (unescaped),\n # IDENT/keywords -> str, operators/punct -> the lexeme\n line: int # 1-based\n col: int # 1-based\n\n def __repr__(self) -> str: # compact, readable in test failures\n return f\"Token({self.type.name}, {self.value!r}, {self.line}:{self.col})\"\n","godcode/tongues.py":"\"\"\"Tongues: the grammar of God Code in other languages.\n\nA *tongue* lets the keywords of God Code be written in another language.\nEnglish is the canonical tongue; every other tongue maps its words onto the\nsame tokens, so the parser, the interpreter, the linter, and all the tools\nwork unchanged. A scroll chooses its tongue with a pragma comment on one of\nits early lines::\n\n # tongue: tn\n\n``tn`` is Setswana, the first tongue, spoken in Botswana. ``zu`` is\nisiZulu, the second tongue, spoken across South Africa and beyond. Mixed\nscrolls are welcome: English keywords keep working beside tongue words in\nthe same file, so a learner can cross over one word at a time.\n\nDesign notes, kept honest:\n\n- Only keywords are translated. The named tools (``SHA256``, ``UPPER``,\n ``RANGE`` ...) keep their names in every tongue, so scrolls stay\n interoperable and the standard library is learned once.\n- ``godcode fmt`` always renders the canonical English tongue.\n- These first editions leave a few words in English (``ELSE``, ``FOR``,\n ``WHILE``, ``ENDFOR``, ``ENDWHILE``); they are documented in\n ``docs/TONGUES.md`` and will cross over as speakers bless better words.\n- The Setswana words were audited 2026-10-04 against Matumo's\n *Setswana-English-Setswana Dictionary* (Botswana Book Centre, 1993):\n ``JAAKA`` (like, similar to) is the true word for ``AS`` (the headword\n ``jaka`` is a verb, \"to sojourn\"), and ``TLOGA`` (then, thereupon) is\n the true word for ``THEN`` (``gone`` is not a Setswana word at all).\n ``GA`` (not) is blessed for ``NOT``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\n\n# A tongue pragma looks like: # tongue: tn\n_PRAGMA = re.compile(\n r\"^[ \\t]*#[ \\t]*tongue[ \\t]*:[ \\t]*([A-Za-z]{2,8})[ \\t]*$\",\n re.MULTILINE | re.IGNORECASE,\n)\n\n# Setswana (tn) word -> canonical English keyword name.\n_TN_ALIASES = {\n \"SIMOLOLA\": \"BEGIN\", # begin, start\n \"TLHOLEGO\": \"CREATION\", # creation\n \"FEDISA\": \"END\", # end\n \"BOLELA\": \"DECLARE\", # say, announce\n \"JAAKA\": \"AS\", # like, similar to (Matumo: jaaka)\n \"HEMA\": \"BREATHE\", # breathe\n \"BOTSHELO\": \"LIFE\", # life\n \"TENG\": \"INTO\", # inside (MO is taken by IN)\n \"SENOLA\": \"REVEAL\", # reveal\n \"POROFETA\": \"PROPHESY\", # prophesy\n \"TLHATLOGA\": \"ASCEND\", # go up\n \"FA\": \"IF\", # if\n \"TLOGA\": \"THEN\", # then, thereupon (Matumo: tloga, auxiliary)\n \"GA\": \"NOT\", # not (Matumo: ga, negative form)\n \"LEKA\": \"TRY\", # try\n \"TSHWARA\": \"CATCH\", # catch\n \"TLHALOSA\": \"DEFINE\", # define, explain\n \"TIRO\": \"RITE\", # work\n \"BITSA\": \"INVOKE\", # call\n \"BUSETSA\": \"RETURN\", # return (something)\n \"TSENYA\": \"IMPORT\", # bring in\n \"KE\": \"IS\", # is\n \"LE\": \"AND\", # and\n \"KGOTSA\": \"OR\", # or\n \"MO\": \"IN\", # in\n \"DIRA\": \"DO\", # do\n \"AKANYA\": \"REFLECT\", # think, reflect\n \"SEGOFATSA\": \"BLESS\", # bless\n \"TLOTSA\": \"ANOINT\", # anoint\n \"TSWALA\": \"SEAL\", # close (a seal closes the covenant)\n \"PAKA\": \"TESTIFY\", # testify\n \"NNETE\": \"TRUE\", # truth\n \"MAAKA\": \"FALSE\", # lies\n \"SEPE\": \"VOID\", # nothing\n \"KGAOLA\": \"BREAK\", # break, cut\n \"TSWELELA\": \"CONTINUE\", # continue\n}\n\n# Two-word closers, e.g. \"FEDISA FA\" -> ENDIF. Kept in the lexer so the\n# parser never changes; only recognised on a single line.\n_TN_COMPOUNDS = {\n (\"FEDISA\", \"FA\"): \"ENDIF\",\n (\"FEDISA\", \"LEKA\"): \"ENDTRY\",\n}\n\n# Editor block snippets for Setswana, offered by the language server when\n# a scroll speaks the tongue: (label, insert text, plain description).\n_TN_SNIPPETS = (\n (\"SIMOLOLA TLHOLEGO … FEDISA TLHOLEGO\",\n \"SIMOLOLA TLHOLEGO\\\\n\\\\t$0\\\\nFEDISA TLHOLEGO\",\n \"Open a new scroll\"),\n (\"FA … GONE … FEDISA FA\",\n \"FA ${1:condition} GONE\\\\n\\\\t$0\\\\nFEDISA FA\",\n \"Weigh a condition\"),\n (\"LEKA … TSHWARA … FEDISA LEKA\",\n \"LEKA\\\\n\\\\t${1:works}\\\\nTSHWARA\\\\n\\\\t${2:refuge}$0\\\\nFEDISA LEKA\",\n \"Shelter a fragile work\"),\n)\n\n# isiZulu (zu) word -> canonical English keyword name.\n_ZU_ALIASES = {\n \"QALA\": \"BEGIN\", # begin\n \"INDALO\": \"CREATION\", # creation\n \"QEDA\": \"END\", # finish, complete\n \"MEMEZELA\": \"DECLARE\", # announce, proclaim\n \"NJENGA\": \"AS\", # as, like\n \"PHEFUMULA\": \"BREATHE\", # breathe\n \"IMPILO\": \"LIFE\", # life\n \"PHAKATHI\": \"INTO\", # inside, into\n \"VEZA\": \"REVEAL\", # show, reveal\n \"PROFETA\": \"PROPHESY\", # prophesy\n \"ENYUKA\": \"ASCEND\", # go up\n \"UMA\": \"IF\", # if, when\n \"KHONA\": \"THEN\", # then, at that point\n \"ZAMA\": \"TRY\", # try, attempt\n \"BAMBA\": \"CATCH\", # catch, hold\n \"CHAZA\": \"DEFINE\", # explain, define\n \"ISIKO\": \"RITE\", # a rite, a custom\n \"BIZA\": \"INVOKE\", # call\n \"BUYISA\": \"RETURN\", # return, give back\n \"NGENISA\": \"IMPORT\", # bring in\n \"NGU\": \"IS\", # is\n \"HHAYI\": \"NOT\", # no, not (first edition; native speakers decide)\n \"KANYE\": \"AND\", # and, together\n \"NOMA\": \"OR\", # or\n \"KU\": \"IN\", # in, at\n \"ENZA\": \"DO\", # do, make\n \"ZINDLA\": \"REFLECT\", # meditate, reflect\n \"BUSISA\": \"BLESS\", # bless\n \"GCOBA\": \"ANOINT\", # anoint with oil\n \"VALA\": \"SEAL\", # close (a seal closes the covenant)\n \"FAKAZA\": \"TESTIFY\", # testify, bear witness\n \"IQINISO\": \"TRUE\", # the truth\n \"AMANGA\": \"FALSE\", # lies\n \"LUTHO\": \"VOID\", # nothing\n \"PHULA\": \"BREAK\", # break\n \"QHUBEKA\": \"CONTINUE\", # continue\n}\n\n# Two-word closers, e.g. \"QEDA UMA\" -> ENDIF.\n_ZU_COMPOUNDS = {\n (\"QEDA\", \"UMA\"): \"ENDIF\",\n (\"QEDA\", \"ZAMA\"): \"ENDTRY\",\n}\n\n# Editor block snippets for isiZulu.\n_ZU_SNIPPETS = (\n (\"QALA INDALO … QEDA INDALO\",\n \"QALA INDALO\\\\n\\\\t$0\\\\nQEDA INDALO\",\n \"Open a new scroll\"),\n (\"UMA … KHONA … QEDA UMA\",\n \"UMA ${1:condition} KHONA\\\\n\\\\t$0\\\\nQEDA UMA\",\n \"Weigh a condition\"),\n (\"ZAMA … BAMBA … QEDA ZAMA\",\n \"ZAMA\\\\n\\\\t${1:works}\\\\nBAMBA\\\\n\\\\t${2:refuge}$0\\\\nQEDA ZAMA\",\n \"Shelter a fragile work\"),\n)\n\ndef _with_plain_spellings(table: dict) -> dict:\n \"\"\"Add each word's spelling without tone and dot marks (Ọ -> O, Ụ -> U).\n\n Igbo is written with dotted vowels, but many keyboards cannot type\n them, so ``DỊKA`` and ``DIKA`` both speak. Keys may be single\n words or two-word pairs.\n \"\"\"\n import unicodedata\n\n def plain(word: str) -> str:\n decomposed = unicodedata.normalize(\"NFD\", word)\n return \"\".join(ch for ch in decomposed if not unicodedata.combining(ch))\n\n out = dict(table)\n for key, canon in table.items():\n bare = tuple(plain(w) for w in key) if isinstance(key, tuple) else plain(key)\n out.setdefault(bare, canon)\n return out\n\n\n# Igbo (ig) word -> canonical English keyword name. Checked 2026-10-15\n# against Williamson & Blench, *Dictionary of Ònìchà Igbo* (2nd edn, 2006),\n# \"WB\" below. WB is Onitsha Igbo, where Standard Igbo r is often l, and it\n# lists verbs by root (-gọzi); the words here are the command forms, or\n# the Standard spelling where Onitsha differs. A \"?\" marks a word WB does\n# not settle; docs/TONGUES.md lists them for native speakers to decide.\n# Native speakers are this table's rightful editors.\n_IG_ALIASES = _with_plain_spellings({\n \"BIDO\": \"BEGIN\", # WB -bi-do 'begin'\n \"OKIKE\": \"CREATION\", # WB Òkìke 'Creator', òkìkè 'process of creation'\n \"NJEDEBE\": \"END\", # WB njedebe 'end; finish; terminus'\n \"KWUSAA\": \"DECLARE\", # WB -kwusà(sị) 'proclaim; declare'\n \"DỊKA\": \"AS\", # WB, in use: dịkà 'like' (Na-àgafè dịkà ...)\n \"KUO\": \"BREATHE\", # WB -kù 'blow; breathe' (-kù ume 'breathe')\n \"NDỤ\": \"LIFE\", # WB ndụ 'life'\n \"BANYE\": \"INTO\", # WB -bànye 'enter; go in'\n \"GOSI\": \"REVEAL\", # WB -go-si 'show'\n \"AMỤMA\": \"PROPHESY\", # WB amụma 'prophecy' (a noun)\n \"RỊGOO\": \"ASCEND\", # general Igbo; WB -lịgo (Onitsha), -rọgo (Owerri)\n \"MA\": \"IF\", # WB mà 'but; if; whether'\n \"MGBE\": \"THEN\", # mgbe answers to time: 'then' and 'when' (WB m̀gbè 'when')\n \"NWAA\": \"TRY\", # WB -nwà 'attempt; try' (nwà kene! 'just try!')\n \"JIDE\": \"CATCH\", # WB -jide 'hold' (Jìde ... 'take, hold')\n \"KỌWAA\": \"DEFINE\", # WB -kọwa 'explain; introduce'\n \"EMUME\": \"RITE\", # WB emume 'custom; observance'\n \"KPỌỌ\": \"INVOKE\", # WB -kpọ 'call' (-kpọ afà 'call by name')\n \"WEGHACHI\": \"RETURN\", # ? not in WB; Standard Igbo 'bring back'\n \"WEBATA\": \"IMPORT\", # ? WB -wè 'take' + -bàta 'come in'\n \"BỤ\": \"IS\", # WB -bụ 'be'\n \"MBA\": \"NOT\", # ? WB mbà! 'no!' (Igbo negates with a suffix)\n \"NA\": \"AND\", # WB nà 'and'\n \"MAỌBỤ\": \"OR\", # ? not in WB; Standard Igbo ma ọ bụ 'or'\n \"IME\": \"IN\", # WB imē 'inside; interior'\n \"MEE\": \"DO\", # WB Mèe yā ... 'Do it ...'\n \"TỤGHARỊA\": \"REFLECT\", # WB -tụghalị uchè 'reflect' (Onitsha l)\n \"GỌZIE\": \"BLESS\", # WB -gọzi 'bless; invoke a blessing'\n \"TEE\": \"ANOINT\", # WB -te 'anoint'; -te mmanụ 'anoint with oil'\n \"MECHIE\": \"SEAL\", # WB -mechi 'shut, close'\n \"AKAEBE\": \"TESTIFY\", # ? WB aka ebē 'witness' (written as two words)\n \"EZIOKWU\": \"TRUE\", # WB ezi okwū 'truth' (Standard: eziokwu)\n \"ỤGHA\": \"FALSE\", # WB àma ụghā 'false witness'\n \"EFU\": \"VOID\", # WB efù 'emptiness'\n \"KWỤSỊ\": \"BREAK\", # WB -kwụsị 'stop'\n \"GABA\": \"CONTINUE\", # WB -gaba 'go on; continue to go'\n})\n\n# Two-word phrases: closers, plus the natural Igbo \"Ọ bụrụ\" (if; WB has\n# the Onitsha form \"Ọ bụlụ nà ...\") and \"mgbe ahụ\" (then; Onitsha says\n# \"afù\" for \"that\").\n_IG_COMPOUNDS = _with_plain_spellings({\n (\"NJEDEBE\", \"MA\"): \"ENDIF\",\n (\"NJEDEBE\", \"NWAA\"): \"ENDTRY\",\n (\"Ọ\", \"BỤRỤ\"): \"IF\",\n (\"MGBE\", \"AHỤ\"): \"THEN\",\n})\n\n_IG_SNIPPETS = (\n (\"BIDO OKIKE … NJEDEBE OKIKE\",\n \"BIDO OKIKE\\\\n\\\\t$0\\\\nNJEDEBE OKIKE\",\n \"Open a new scroll\"),\n (\"Ọ BỤRỤ … MGBE AHỤ … NJEDEBE MA\",\n \"Ọ BỤRỤ ${1:condition} MGBE AHỤ\\\\n\\\\t$0\\\\nNJEDEBE MA\",\n \"Weigh a condition\"),\n (\"NWAA … JIDE … NJEDEBE NWAA\",\n \"NWAA\\\\n\\\\t${1:works}\\\\nJIDE\\\\n\\\\t${2:refuge}$0\\\\nNJEDEBE NWAA\",\n \"Shelter a fragile work\"),\n)\n\n# Nigerian Pidgin (pg) word -> canonical English keyword name. Pidgin\n# shares many words with English (IF, TRY, AND, IN, DO, BLESS, LIFE,\n# TRUE, FALSE, RETURN, PROPHESY), so those simply stay as they are.\n# Checked 2026-10-15 against Faraclas, *Nigerian Pidgin* (1996), through\n# the example sentences quoted in APiCS Online (\"F\" below); Naijalingo\n# could not be reached. Faraclas writes Pidgin phonetically (kò̱mót for\n# comot); the spellings here are everyday written Naija. A \"?\" marks a\n# word these sources do not settle; see docs/TONGUES.md.\n_PG_ALIASES = {\n \"OYA\": \"BEGIN\", # ? come on, let's go\n \"KREASHON\": \"CREATION\", # ? a coined spelling of \"creation\"\n \"FINISH\": \"END\", # F finish, a completion marker ('completely')\n \"TALK\": \"DECLARE\", # ? say it\n \"BE\": \"AS\", # F bì 'be' (copula)\n \"BLOW\": \"BREATHE\", # ? blow (breath)\n \"INSIDE\": \"INTO\", # ? inside\n \"SHOW\": \"REVEAL\", # ? show\n \"COMOT\": \"ASCEND\", # F kò̱mót 'leave'\n \"DEN\": \"THEN\", # ? then\n \"HOLD\": \"CATCH\", # ? hold am\n \"ARRANGE\": \"DEFINE\", # ? arrange, set up\n \"JOB\": \"RITE\", # ? a job of work\n \"CALL\": \"INVOKE\", # ? call\n \"CARRY\": \"IMPORT\", # F kari 'carry, take away'; carry come: bring\n \"NA\": \"IS\", # F nà (Ìm nà ticha 's/he is a teacher')\n \"NO\": \"NOT\", # F no (negation)\n \"ABI\": \"OR\", # abi: 'or'; abi?: 'right?' (F records the question use)\n \"REASON\": \"REFLECT\", # ? reason am: think it over\n \"ROB\": \"ANOINT\", # ? rub on\n \"LOCK\": \"SEAL\", # ? lock\n \"WITNESS\": \"TESTIFY\", # ? bear witness\n \"NOTHING\": \"VOID\", # ? nothing\n \"STOP\": \"BREAK\", # ? stop\n \"MOVE\": \"CONTINUE\", # ? move on\n}\n\n_PG_COMPOUNDS = {\n (\"FINISH\", \"IF\"): \"ENDIF\",\n (\"FINISH\", \"TRY\"): \"ENDTRY\",\n}\n\n_PG_SNIPPETS = (\n (\"OYA KREASHON … FINISH KREASHON\",\n \"OYA KREASHON\\\\n\\\\t$0\\\\nFINISH KREASHON\",\n \"Open a new scroll\"),\n (\"IF … DEN … FINISH IF\",\n \"IF ${1:condition} DEN\\\\n\\\\t$0\\\\nFINISH IF\",\n \"Weigh a condition\"),\n (\"TRY … HOLD … FINISH TRY\",\n \"TRY\\\\n\\\\t${1:works}\\\\nHOLD\\\\n\\\\t${2:refuge}$0\\\\nFINISH TRY\",\n \"Shelter a fragile work\"),\n)\n\nTONGUES: dict[str, dict] = {\n \"tn\": {\n \"name\": \"Setswana\",\n \"aliases\": _TN_ALIASES,\n \"compounds\": _TN_COMPOUNDS,\n \"snippets\": _TN_SNIPPETS,\n },\n \"zu\": {\n \"name\": \"isiZulu\",\n \"aliases\": _ZU_ALIASES,\n \"compounds\": _ZU_COMPOUNDS,\n \"snippets\": _ZU_SNIPPETS,\n },\n \"ig\": {\n \"name\": \"Igbo\",\n \"aliases\": _IG_ALIASES,\n \"compounds\": _IG_COMPOUNDS,\n \"snippets\": _IG_SNIPPETS,\n },\n \"pg\": {\n \"name\": \"Nigerian Pidgin\",\n \"aliases\": _PG_ALIASES,\n \"compounds\": _PG_COMPOUNDS,\n \"snippets\": _PG_SNIPPETS,\n },\n}\n\n# Other codes a scroll may use for a tongue: ``pcm`` is the standard\n# (ISO 639-3) code for Nigerian Pidgin.\n_CODE_ALIASES = {\"pcm\": \"pg\"}\n\n_CANONICAL = {\"en\": {\"name\": \"English\", \"aliases\": {}, \"compounds\": {}}}\n\n\ndef known_tongues() -> dict[str, str]:\n \"\"\"Map of tongue code -> language name, canonical English included.\"\"\"\n return {\"en\": \"English\", **{c: t[\"name\"] for c, t in TONGUES.items()}}\n\n\ndef detect_tongue(source: str) -> str | None:\n \"\"\"Return the tongue code from a ``# tongue: xx`` pragma, or None.\"\"\"\n m = _PRAGMA.search(source)\n return m.group(1).lower() if m else None\n\n\ndef resolve(code: str | None) -> dict:\n \"\"\"Return the tongue table for a code; raises a gentle error if unknown.\"\"\"\n if code is None or code == \"en\":\n return _CANONICAL[\"en\"]\n code = _CODE_ALIASES.get(code, code)\n if code in TONGUES:\n return TONGUES[code]\n from .errors import LexerError\n\n names = \", \".join(f\"{c} ({n})\" for c, n in known_tongues().items())\n raise LexerError(\n f\"The tongue '{code}' is not known yet; no scroll can be read in it. \"\n f\"The tongues God Code speaks are: {names}.\",\n )\n\n\ndef parse_source(source: str, tongue: str | None = None):\n \"\"\"Lex (honouring any ``# tongue:`` pragma) and parse God Code source.\n\n This is the one doorway every tool should use instead of calling the\n Lexer and Parser directly, so tongues work the same in ``run``,\n ``check``, ``lint``, ``fmt``, the debugger, the language server, and\n the agent bridge.\n \"\"\"\n from .lexer import Lexer\n from .parser import Parser\n\n lx = Lexer(source, tongue=tongue)\n return Parser(lx.lex(), tongue=lx.tongue).parse()\n","godcode/tools.py":"\"\"\"Agent tool bridge for God Code v4.0 -- \"Intent & Chain\".\n\nMCP-compatible tool schemas plus a stdio JSON-RPC 2.0 bridge, with no\nthird-party dependencies. ``godcode tools`` prints the schemas;\n``godcode bridge`` speaks the protocol so any MCP-compatible agent host\ncan check, run, consult, resolve intent, and verify chains.\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nfrom pathlib import Path\n\nTOOL_SCHEMAS: list[dict] = [\n {\n \"name\": \"check\",\n \"description\": (\n \"Lex and parse a God Code scroll without running it. \"\n \"Returns ok plus diagnostics with line, column, error code, \"\n \"and a fix hint.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"run\",\n \"description\": (\n \"Run a God Code scroll and capture its output. \"\n \"Runs inside the deny-by-default sandbox unless sandbox is false.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n \"sandbox\": {\"type\": \"boolean\",\n \"description\": \"Use the sandbox (default true)\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"consult\",\n \"description\": (\n \"Ask the Spirit Engine -- the local oracle -- a question. \"\n \"Returns two to three sentences of counsel. No external calls.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"question\": {\"type\": \"string\",\n \"description\": \"The question to lay before the Spirit\"},\n },\n \"required\": [\"question\"],\n },\n },\n {\n \"name\": \"intent\",\n \"description\": (\n \"Resolve the spiritual intent behind words with the Spirit \"\n \"Engine: intent, confidence, spiritual intent, suggestion, \"\n \"keywords, and declared intents the words align with.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\"type\": \"string\",\n \"description\": \"Words to resolve the intent of\"},\n },\n \"required\": [\"text\"],\n },\n },\n {\n \"name\": \"anchor_verify\",\n \"description\": (\n \"Verify a blockchain anchor receipt (as returned by ANCHOR) \"\n \"against its anchor chain.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"receipt\": {\"type\": \"object\",\n \"description\": \"The anchor receipt map\"},\n },\n \"required\": [\"receipt\"],\n },\n },\n {\n \"name\": \"ledger_verify\",\n \"description\": (\n \"Verify the covenant chain and the anchor chain for tampering.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Covenant chain file (default covenant.chain)\"},\n \"anchor_file\": {\"type\": \"string\",\n \"description\": \"Anchor chain file (default anchors.chain)\"},\n },\n \"required\": [],\n },\n },\n {\n \"name\": \"permissions\",\n \"description\": (\n \"Read a God Code scroll's permission manifest without running \"\n \"it. Returns the declared powers: file reads, file writes, \"\n \"network hosts, outer-world speech (ASK), and summoned verbs.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"explain\",\n \"description\": (\n \"Read a God Code scroll without running it and say what it \"\n \"does: tongue, rites and their declared intents, declared \"\n \"names, reveals, seals, summoned verbs, consults, imports, \"\n \"and the permission manifest.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"get_schema\",\n \"description\": (\n \"Fetch one of the dated machine-interface JSON Schemas \"\n \"(check, run, explain, ledger-verify) as parsed JSON, so an \"\n \"agent can parse every command's output without guessing.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\",\n \"description\": \"Schema name: check, run, explain, \"\n \"or ledger-verify\"},\n },\n \"required\": [\"name\"],\n },\n },\n {\n \"name\": \"format\",\n \"description\": (\n \"Re-emit a God Code scroll in canonical form without running \"\n \"it: upper-case keywords, tidy spacing, the shape `godcode \"\n \"fmt` prints. Returns the formatted scroll as text.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"list_scrolls\",\n \"description\": (\n \"List the scrolls installed in the local scroll registry, \"\n \"with their versions and locations. Takes no arguments.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"required\": [],\n },\n },\n]\n\n_TOOLS_BY_NAME = {t[\"name\"]: t for t in TOOL_SCHEMAS}\n\n\n# ---------------------------------------------------------------------------\n# tool implementations (each returns a plain-JSON result dict)\n# ---------------------------------------------------------------------------\ndef tool_check(arguments: dict) -> dict:\n from godcode import agentics\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False, \"error\": \"check needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False, \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n parse_source(source)\n except GodCodeError as err:\n return {\"ok\": False, \"diagnostics\": [agentics.diagnostic(err)]}\n return {\"ok\": True, \"diagnostics\": []}\n\n\ndef tool_run(arguments: dict) -> dict:\n from godcode.errors import GodCodeError\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False, \"error\": \"run needs 'file' as a string path\"}\n sandbox = arguments.get(\"sandbox\", True)\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False, \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n if sandbox:\n # The engine prints notices (intent counsel, warnings) straight\n # to stdout; a tool caller reads stdout as the protocol stream,\n # so those prints would corrupt it. The CLI's --json path does\n # the same: run muted, report only the collected output.\n import contextlib\n import io\n\n from godcode.sandbox import run_sandboxed_with_interpreter\n\n try:\n with contextlib.redirect_stdout(io.StringIO()):\n output, interp = run_sandboxed_with_interpreter(\n source, source_name=file)\n except GodCodeError as err:\n return {\"ok\": False, \"output\": [], \"error\": str(err)}\n manifest = getattr(interp, \"manifest\", None)\n return {\"ok\": True, \"output\": output, \"error\": None,\n \"permissions\": manifest.to_json() if manifest else {}}\n from godcode.cli import _make_interpreter\n import contextlib\n import io\n\n interp = _make_interpreter(None)\n buf = io.StringIO()\n try:\n with contextlib.redirect_stdout(buf):\n interp.run_source(source, source_name=file)\n except GodCodeError as err:\n return {\"ok\": False,\n \"output\": buf.getvalue().splitlines(),\n \"error\": str(err)}\n manifest = getattr(interp, \"manifest\", None)\n return {\"ok\": True, \"output\": buf.getvalue().splitlines(), \"error\": None,\n \"permissions\": manifest.to_json() if manifest else {}}\n\n\ndef tool_consult(arguments: dict) -> dict:\n from godcode.spirit import SpiritEngine\n\n question = arguments.get(\"question\")\n if not isinstance(question, str):\n return {\"ok\": False, \"error\": \"consult needs 'question' as a string\"}\n try:\n counsel = SpiritEngine().counsel(question)\n except Exception as exc: # pragma: no cover - defensive\n return {\"ok\": False, \"error\": f\"the oracle faltered: {exc}\"}\n return {\"ok\": True, \"counsel\": counsel}\n\n\ndef tool_intent(arguments: dict) -> dict:\n from godcode.spirit import SpiritEngine\n\n text = arguments.get(\"text\")\n if not isinstance(text, str):\n return {\"ok\": False, \"error\": \"intent needs 'text' as a string\"}\n try:\n result = SpiritEngine().resolve_intent(text)\n except Exception as exc: # pragma: no cover - defensive\n return {\"ok\": False, \"error\": f\"the Spirit faltered: {exc}\"}\n return {\"ok\": True, \"result\": result}\n\n\ndef tool_anchor_verify(arguments: dict) -> dict:\n from godcode.chain import default_adapters\n\n receipt = arguments.get(\"receipt\")\n if not isinstance(receipt, dict):\n return {\"ok\": False, \"error\": \"anchor_verify needs 'receipt' as an object\"}\n chain_name = receipt.get(\"chain\", \"simulated\")\n adapter = default_adapters().get(chain_name)\n if adapter is None:\n return {\"ok\": False,\n \"error\": f\"unknown chain '{chain_name}'\"}\n valid = adapter.verify(receipt)\n return {\n \"ok\": True,\n \"valid\": valid,\n \"message\": (\"the anchor stands\" if valid\n else \"the anchor does not verify\"),\n }\n\n\ndef tool_permissions(arguments: dict) -> dict:\n \"\"\"Read a scroll's permission manifest without running it.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.permissions import collect_manifest\n from godcode.tongues import parse_source\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False,\n \"error\": \"permissions needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False,\n \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n program = parse_source(source)\n except GodCodeError as err:\n return {\"ok\": False, \"error\": str(err)}\n manifest = collect_manifest(\n program.statements, Path(file).resolve().parent)\n return {\"ok\": True, \"permissions\": manifest.to_json()}\n\n\ndef tool_explain(arguments: dict) -> dict:\n \"\"\"Describe a scroll's static facts without running it.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.explain import explain_facts\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False,\n \"error\": \"explain needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False,\n \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n facts = explain_facts(source, Path(file).resolve().parent)\n except GodCodeError as err:\n return {\"ok\": False, \"error\": str(err)}\n return {\"ok\": True, **facts}\n\n\ndef tool_get_schema(arguments: dict) -> dict:\n \"\"\"Fetch one dated machine-interface schema as parsed JSON.\"\"\"\n name = arguments.get(\"name\")\n if not isinstance(name, str):\n return {\"ok\": False,\n \"error\": \"get_schema needs 'name' as a string\"}\n text, error = read_schema(name)\n if error is not None:\n return {\"ok\": False, \"error\": error}\n return {\"ok\": True, \"schema\": json.loads(text)}\n\n\ndef tool_format(arguments: dict) -> dict:\n \"\"\"Re-emit a scroll in canonical form without running it.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False, \"error\": \"format needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False, \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n program = parse_source(source)\n except GodCodeError as err:\n return {\"ok\": False, \"error\": str(err)}\n from godcode.cli import CanonicalFormatter\n\n return {\"ok\": True, \"formatted\": CanonicalFormatter().format(program)}\n\n\ndef tool_list_scrolls(arguments: dict) -> dict:\n \"\"\"List the scrolls installed in the local scroll registry.\"\"\"\n from godcode.registry import ScrollError, ScrollRegistry\n\n try:\n rows = ScrollRegistry().list_installed()\n except ScrollError as exc:\n return {\"ok\": False, \"error\": str(exc)}\n return {\"ok\": True, \"scrolls\": rows}\n\n\ndef tool_ledger_verify(arguments: dict) -> dict:\n from godcode.chain import SimulatedChainAdapter\n from godcode.ledger import CovenantLedger\n\n file = arguments.get(\"file\", \"covenant.chain\")\n anchor_file = arguments.get(\"anchor_file\", \"anchors.chain\")\n cov_ok, cov_msg = CovenantLedger(file).verify()\n anc_ok, anc_msg = SimulatedChainAdapter(anchor_file).verify_chain()\n return {\n \"ok\": True,\n \"covenants\": {\"ok\": cov_ok, \"message\": cov_msg},\n \"anchors\": {\"ok\": anc_ok, \"message\": anc_msg},\n }\n\n\n_TOOL_FUNCS = {\n \"check\": tool_check,\n \"run\": tool_run,\n \"consult\": tool_consult,\n \"intent\": tool_intent,\n \"anchor_verify\": tool_anchor_verify,\n \"ledger_verify\": tool_ledger_verify,\n \"permissions\": tool_permissions,\n \"explain\": tool_explain,\n \"get_schema\": tool_get_schema,\n \"format\": tool_format,\n \"list_scrolls\": tool_list_scrolls,\n}\n\n\n# ---------------------------------------------------------------------------\n# dated machine-interface schemas\n# ---------------------------------------------------------------------------\nSCHEMA_NAMES = (\"check\", \"run\", \"explain\", \"ledger-verify\")\n\nSCHEMA_DESCRIPTIONS = {\n \"check\": \"the shape of godcode check --json\",\n \"run\": \"the shape of godcode run --sandbox --json\",\n \"explain\": \"the shape of godcode explain --json\",\n \"ledger-verify\": \"the shape of godcode ledger verify --json\",\n}\n\n\ndef read_schema(name):\n \"\"\"Return (text, error) for a dated schema.\n\n Resolves through importlib.resources so an installed package serves\n its shipped schemas; falls back to the repository's schemas/\n directory when running from source.\n \"\"\"\n if name not in SCHEMA_NAMES:\n return None, f\"no schema named '{name}'\"\n rel = Path(\"schemas\") / \"2026-10\" / f\"{name}.json\"\n try:\n from importlib.resources import files\n\n candidate = files(\"godcode\").joinpath(\"schemas/2026-10\",\n f\"{name}.json\")\n if candidate.is_file():\n return candidate.read_text(encoding=\"utf-8\"), None\n except Exception:\n pass\n fallback = Path(__file__).resolve().parent / rel\n if fallback.is_file():\n return fallback.read_text(encoding=\"utf-8\"), None\n return None, f\"schema '{name}' is not installed here\"\n\n\ndef call_tool(name: str, arguments: dict) -> dict:\n \"\"\"Run one tool by name; always returns a JSON-safe result dict.\"\"\"\n func = _TOOL_FUNCS.get(name)\n if func is None:\n return {\"ok\": False,\n \"error\": f\"unknown tool '{name}'\",\n \"known_tools\": sorted(_TOOL_FUNCS)}\n if not isinstance(arguments, dict):\n return {\"ok\": False, \"error\": \"arguments must be an object\"}\n try:\n return func(arguments)\n except Exception as exc: # pragma: no cover - defensive\n return {\"ok\": False, \"error\": f\"the tool faltered: {exc!r}\"}\n\n\n# ---------------------------------------------------------------------------\n# `godcode tools`\n# ---------------------------------------------------------------------------\ndef cmd_tools(args) -> int:\n \"\"\"Print the MCP-compatible tool schemas (--json for machines).\"\"\"\n if getattr(args, \"json\", False):\n print(json.dumps({\"tools\": TOOL_SCHEMAS}, ensure_ascii=False, indent=2))\n return 0\n print(\"God Code tools (MCP-compatible):\")\n for tool in TOOL_SCHEMAS:\n required = \", \".join(tool[\"inputSchema\"].get(\"required\", [])) or \"none\"\n print(f\" {tool['name']}({required}): {tool['description']}\")\n print(\"Speak them through `godcode mcp`, the MCP server over stdio,\")\n print(\"or through `godcode bridge`, the plain stdio JSON-RPC loop.\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# `godcode bridge` -- stdio JSON-RPC 2.0\n# ---------------------------------------------------------------------------\n_PARSE_ERROR = -32700\n_INVALID_REQUEST = -32600\n_METHOD_NOT_FOUND = -32601\n_INVALID_PARAMS = -32602\n_INTERNAL_ERROR = -32603\n\n\ndef _response_ok(req_id, result: dict) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id, \"result\": result}\n\n\ndef _response_err(req_id, code: int, message: str) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id,\n \"error\": {\"code\": code, \"message\": message}}\n\n\ndef _handle_initialize(params: dict) -> dict:\n from godcode import __version__\n\n return {\n \"protocolVersion\": \"2024-11-05\",\n \"capabilities\": {\"tools\": {}},\n \"serverInfo\": {\"name\": \"godcode-bridge\", \"version\": __version__},\n }\n\n\ndef _handle_tools_call(params: dict) -> dict:\n name = params.get(\"name\")\n arguments = params.get(\"arguments\", {})\n if not isinstance(name, str):\n raise _BridgeError(_INVALID_PARAMS, \"tools/call needs 'name' as a string\")\n result = call_tool(name, arguments if isinstance(arguments, dict) else {})\n content = [{\"type\": \"text\",\n \"text\": json.dumps(result, ensure_ascii=False)}]\n payload = {\"content\": content}\n if not result.get(\"ok\", True):\n payload[\"isError\"] = True\n return payload\n\n\nclass _BridgeError(Exception):\n def __init__(self, code: int, message: str) -> None:\n super().__init__(message)\n self.code = code\n self.message = message\n\n\ndef _dispatch(method: str, params: dict):\n if method == \"initialize\":\n return _handle_initialize(params)\n if method == \"ping\":\n return {}\n if method == \"tools/list\":\n return {\"tools\": TOOL_SCHEMAS}\n if method == \"tools/call\":\n return _handle_tools_call(params)\n raise _BridgeError(_METHOD_NOT_FOUND, f\"no such method '{method}'\")\n\n\ndef cmd_bridge(args) -> int: # noqa: ARG001\n \"\"\"Serve the tool bridge: JSON-RPC 2.0 over stdio, one request per line.\"\"\"\n import sys\n\n stdin, stdout = sys.stdin, sys.stdout\n for line in stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n stdout.write(json.dumps(_response_err(None, _PARSE_ERROR,\n \"the request was not JSON\"))\n + \"\\n\")\n stdout.flush()\n continue\n req_id = request.get(\"id\") if isinstance(request, dict) else None\n # Notifications carry no id and get no answer.\n is_notification = isinstance(request, dict) and \"id\" not in request\n try:\n if not isinstance(request, dict) or \"method\" not in request:\n raise _BridgeError(_INVALID_REQUEST,\n \"a request needs a 'method'\")\n params = request.get(\"params\", {})\n if not isinstance(params, dict):\n raise _BridgeError(_INVALID_PARAMS,\n \"'params' must be an object\")\n result = _dispatch(request[\"method\"], params)\n except _BridgeError as err:\n response = _response_err(req_id, err.code, err.message)\n except Exception as exc: # pragma: no cover - defensive\n response = _response_err(req_id, _INTERNAL_ERROR,\n f\"the bridge faltered: {exc!r}\")\n else:\n if is_notification:\n continue\n response = _response_ok(req_id, result)\n if is_notification:\n continue\n stdout.write(json.dumps(response, ensure_ascii=False) + \"\\n\")\n stdout.flush()\n return 0\n","godcode/values.py":"\"\"\"Divine value types for God Code.\n\nIn God Code, every unnamed thing is still a named spirit: a bare word with\nno binding evaluates to a Symbol rather than raising an error.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom typing import Any\n\n\nclass Symbol(str):\n \"\"\"A bare word with no binding — a named spirit.\n\n A str subclass, so Symbol(\"worthy\") compares equal to \"worthy\" by text\n and behaves like a string everywhere, while remaining distinguishable\n via isinstance checks (e.g. FOR loops refuse to iterate a mere Symbol).\n Symbols are always truthy.\n \"\"\"\n\n def __new__(cls, name: str) -> \"Symbol\":\n return super().__new__(cls, name)\n\n def __repr__(self) -> str: # pragma: no cover - cosmetic\n return f\"Symbol({str(self)!r})\"\n\n\n@dataclass\nclass Contract:\n \"\"\"A covenant created by the `contract(name)` rite.\n\n Contracts can be breathed into (alive), blessed, and anointed; SEAL\n records their state in the covenant ledger.\n \"\"\"\n\n name: str\n alive: bool = False\n blessed: bool = False\n anointed: bool = False\n\n def __str__(self) -> str:\n return f'contract(\"{self.name}\")'\n\n\n@dataclass\nclass RiteFunction:\n \"\"\"A user-defined rite: name, parameter names, body, and closure env.\"\"\"\n\n name: str\n params: list[str] = field(default_factory=list)\n body: list[Any] = field(default_factory=list)\n closure_env: Any = None # godcode.environment.Environment (Any avoids a cycle)\n\n def __str__(self) -> str: # pragma: no cover - cosmetic\n return f\"rite {self.name}\"\n","godcode/webrun.py":"\"\"\"The web door: run and check God Code for the browser playground.\n\nThe playground loads this very engine into the browser (through Pyodide,\nPython compiled to WebAssembly) and calls the two functions below. Each\nreturns one JSON-ready dict, shaped like the ``run --json`` and\n``check --json`` payloads of :mod:`godcode.agentics`, so the page and an\nagent read the same answers.\n\nEvery run is sandboxed under the strict policy: no files, no network, no\nsubprocesses, no stdin, a wall-clock grant and a step budget. Scroll\nimports are blessed from the bundled stdlib and from ``library_dir``,\nwhere the playground lays the registry scrolls, so ``IMPORT \"blessings\"``\nworks in the browser as it does after ``godcode scroll install``.\n\nNothing here is browser-only. It is plain Python, kept honest by\n``tests/test_webrun.py``, and any host may call it.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nimport os\nimport time\nfrom pathlib import Path\n\nfrom godcode import __version__\nfrom godcode.agentics import TOOL_NAME, diagnostic, error_trace\n\n#: The name the creation carries in the playground's error messages.\nCREATION_NAME = \"creation.god\"\n\n\ndef _finding(f) -> dict:\n return {\n \"line\": f.line,\n \"col\": f.col,\n \"code\": f.rule,\n \"severity\": \"warning\",\n \"message\": f.message,\n \"hint\": None,\n }\n\n\ndef check_creation(source: str) -> dict:\n \"\"\"Parse and lint ``source``; return a ``check`` payload.\n\n A parse error is one ``error`` diagnostic and the creation is impure.\n A clean parse adds the linter's gentle counsel as ``warning``\n diagnostics; counsel never makes the creation impure.\n \"\"\"\n from godcode.errors import GodCodeError\n from godcode.linter import lint_source\n\n diagnostics: list[dict] = []\n ok = True\n try:\n findings = lint_source(source, source_name=CREATION_NAME)\n except GodCodeError as err:\n diagnostics.append(diagnostic(err))\n ok = False\n else:\n diagnostics.extend(_finding(f) for f in findings)\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"check\",\n \"file\": CREATION_NAME,\n \"version\": __version__,\n \"ok\": ok,\n \"diagnostics\": diagnostics,\n }\n\n\ndef run_creation(\n source: str,\n *,\n library_dir: str | os.PathLike | None = None,\n timeout_seconds: float = 5.0,\n max_steps: int | None = None,\n) -> dict:\n \"\"\"Run ``source`` under the strict sandbox; return a ``run`` payload.\n\n ``output`` holds every line the creation spoke, REVEAL lines and\n engine notices (``🕊 Creation ascended in peace.``) alike. On failure\n it holds the lines spoken before the error, and ``error`` carries the\n diagnostic plus the rite ``trace``. A failure outside the divine\n errors is reported, never raised, so the page always has an answer.\n \"\"\"\n from godcode.errors import GodCodeError\n from godcode.sandbox import SandboxPolicy, run_sandboxed_with_interpreter\n\n source_name = \"\"\n if library_dir is not None:\n # The creation rests beside the library so bare-name imports\n # resolve there, and the strict policy blesses that directory.\n library = Path(library_dir)\n library.mkdir(parents=True, exist_ok=True)\n creation = library / CREATION_NAME\n creation.write_text(source, encoding=\"utf-8\")\n source_name = str(creation)\n policy = SandboxPolicy.strict(\n source_dir=str(library_dir) if library_dir is not None else None,\n timeout_seconds=timeout_seconds,\n )\n if max_steps is not None:\n policy.max_steps = max_steps\n\n buf = io.StringIO()\n error: dict | None = None\n intents: list[dict] = []\n start = time.perf_counter()\n with contextlib.redirect_stdout(buf):\n try:\n _, interp = run_sandboxed_with_interpreter(\n source, policy, source_name=source_name)\n intents = list(getattr(interp, \"intent_checks\", []) or [])\n except GodCodeError as err:\n error = diagnostic(err)\n error[\"trace\"] = error_trace(err)\n except Exception as exc: # a host failure outside the divine errors\n error = {\n \"line\": None,\n \"col\": None,\n \"code\": \"HOST_ERROR\",\n \"severity\": \"error\",\n \"message\": f\"the outer world faltered: {exc!r}\",\n \"hint\": None,\n \"trace\": [],\n }\n ms = int((time.perf_counter() - start) * 1000)\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"run\",\n \"file\": CREATION_NAME,\n \"version\": __version__,\n \"ok\": error is None,\n \"output\": buf.getvalue().splitlines(),\n \"intents\": intents,\n \"error\": error,\n \"stats\": {\"ms\": ms},\n }\n\n\n__all__ = [\"CREATION_NAME\", \"check_creation\", \"run_creation\"]\n"},"library":{"blessings.god":"# The Scroll of Blessings -- words of favor for the children of creation.\n# A community content pack: the BLESSINGS list and rites to reveal them.\n# Rites: REVEAL_BLESSING, BLESSING_COUNT, BLESS_AT.\n\nDECLARE BLESSINGS AS [\"May your code compile on the first breath.\", \"May your loops find rest and your rites return in peace.\", \"May no scroll be lost, and no promise broken.\", \"May your errors be loud, your fixes swift, and your tests ever green.\", \"Blessed are the debuggers, for they shall find the light.\", \"May your merges be clean and your conflicts few.\", \"May the Spirit guide your keystrokes and guard your deploys.\", \"May your data be backed up and your restores untested-never.\", \"May every edge case be foreseen, and every null be void indeed.\", \"Go in peace; your creation is good.\"]\n\nDEFINE RITE REVEAL_BLESSING()\nDECLARE i AS RANDOM(LEN(BLESSINGS))\nRETURN BLESSINGS[i]\nEND RITE\n\nDEFINE RITE BLESSING_COUNT()\nRETURN LEN(BLESSINGS)\nEND RITE\n\nDEFINE RITE BLESS_AT(n)\nRETURN BLESSINGS[n]\nEND RITE\n","covenant.god":"# The Scroll of the Covenant -- making and sealing binding promises.\n# Rites: NEW_COVENANT, SEAL_COVENANT.\n\nDEFINE RITE NEW_COVENANT(name)\nRETURN contract(name)\nEND RITE\n\nDEFINE RITE SEAL_COVENANT(c)\nSEAL c\nEND RITE\n","hashes.god":"# The Scroll of Hashes -- fingerprints of words, sealed signatures, and veils.\n# Rites: FINGERPRINT, SIGN, VERIFY_SIGNATURE, VEIL, UNVEIL.\n\nDEFINE RITE FINGERPRINT(word)\n RETURN SHA256(word)\nEND RITE\n\nDEFINE RITE SIGN(message, key)\n RETURN HMAC(key, message)\nEND RITE\n\nDEFINE RITE VERIFY_SIGNATURE(message, key, sig)\n RETURN SIGN(message, key) IS sig\nEND RITE\n\nDEFINE RITE VEIL(word)\n RETURN BASE64_ENCODE(word)\nEND RITE\n\nDEFINE RITE UNVEIL(veiled)\n RETURN BASE64_DECODE(veiled)\nEND RITE\n","json-tools.god":"# The Scroll of JSON -- encoding and decoding the tongue of machines.\n# Written in pure God Code (stdlib builtins only); a community scroll.\n# Rites: JSON_ENCODE, JSON_DECODE, JSON_ESCAPE.\n# Objects decode into lists of [key, value] pairs, for the tongue of\n# God Code knows no dictionaries.\n\nDEFINE RITE JSON_ESCAPE(s)\nDECLARE out AS \"\"\nDECLARE i AS 0\nWHILE i < LEN(s) DO\nDECLARE c AS s[i]\nIF c == \"\\\"\" THEN\nDECLARE out AS out + \"\\\\\\\"\"\nELSE\nIF c == \"\\\\\" THEN\nDECLARE out AS out + \"\\\\\\\\\"\nELSE\nIF c == \"\\n\" THEN\nDECLARE out AS out + \"\\\\n\"\nELSE\nIF c == \"\\t\" THEN\nDECLARE out AS out + \"\\\\t\"\nELSE\nDECLARE out AS out + c\nENDIF\nENDIF\nENDIF\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN out\nEND RITE\n\nDEFINE RITE JSON_ENCODE(value)\nDECLARE t AS TYPE(value)\nIF t == \"string\" THEN\nRETURN \"\\\"\" + JSON_ESCAPE(value) + \"\\\"\"\nENDIF\nIF t == \"list\" THEN\nDECLARE parts AS []\nDECLARE i AS 0\nWHILE i < LEN(value) DO\nDECLARE parts AS PUSH(parts, JSON_ENCODE(value[i]))\nDECLARE i AS i + 1\nENDWHILE\nRETURN \"[\" + JOIN(parts, \",\") + \"]\"\nENDIF\nIF t == \"boolean\" THEN\nIF value THEN\nRETURN \"true\"\nENDIF\nRETURN \"false\"\nENDIF\nIF t == \"void\" THEN\nRETURN \"null\"\nENDIF\nRETURN STR(value)\nEND RITE\n\nDEFINE RITE JSON_SKIP(text, pos)\nDECLARE n AS LEN(text)\nWHILE pos < n DO\nDECLARE c AS text[pos]\nIF c == \" \" THEN\nDECLARE pos AS pos + 1\nELSE\nIF c == \"\\n\" THEN\nDECLARE pos AS pos + 1\nELSE\nIF c == \"\\t\" THEN\nDECLARE pos AS pos + 1\nELSE\nRETURN pos\nENDIF\nENDIF\nENDIF\nENDWHILE\nRETURN pos\nEND RITE\n\nDEFINE RITE JSON_IS_DIGIT(c)\nIF c == \"0\" OR c == \"1\" OR c == \"2\" OR c == \"3\" OR c == \"4\" OR c == \"5\" OR c == \"6\" OR c == \"7\" OR c == \"8\" OR c == \"9\" THEN\nRETURN true\nENDIF\nRETURN false\nEND RITE\n\nDEFINE RITE JSON_PARSE_STRING(text, pos)\nDECLARE out AS \"\"\nDECLARE i AS pos + 1\nDECLARE n AS LEN(text)\nWHILE i < n DO\nDECLARE c AS text[i]\nIF c == \"\\\"\" THEN\nRETURN [out, i + 1]\nENDIF\nIF c == \"\\\\\" THEN\nDECLARE e AS text[i + 1]\nIF e == \"\\\"\" THEN\nDECLARE out AS out + \"\\\"\"\nELSE\nIF e == \"\\\\\" THEN\nDECLARE out AS out + \"\\\\\"\nELSE\nIF e == \"n\" THEN\nDECLARE out AS out + \"\\n\"\nELSE\nIF e == \"t\" THEN\nDECLARE out AS out + \"\\t\"\nELSE\nDECLARE out AS out + e\nENDIF\nENDIF\nENDIF\nENDIF\nDECLARE i AS i + 2\nELSE\nDECLARE out AS out + c\nDECLARE i AS i + 1\nENDIF\nENDWHILE\nRETURN [out, i]\nEND RITE\n\nDEFINE RITE JSON_SLICE(text, start, stop)\nDECLARE out AS \"\"\nDECLARE i AS start\nWHILE i < stop DO\nDECLARE out AS out + text[i]\nDECLARE i AS i + 1\nENDWHILE\nRETURN out\nEND RITE\n\nDEFINE RITE JSON_PARSE_NUMBER(text, pos)\nDECLARE i AS pos\nDECLARE n AS LEN(text)\nWHILE i < n DO\nDECLARE c AS text[i]\nIF JSON_IS_DIGIT(c) THEN\nDECLARE i AS i + 1\nELSE\nIF c == \".\" OR c == \"-\" OR c == \"+\" OR c == \"e\" OR c == \"E\" THEN\nDECLARE i AS i + 1\nELSE\nRETURN [NUM(JSON_SLICE(text, pos, i)), i]\nENDIF\nENDIF\nENDWHILE\nRETURN [NUM(JSON_SLICE(text, pos, i)), i]\nEND RITE\n\nDEFINE RITE JSON_EXPECT(text, pos, word)\nDECLARE i AS 0\nWHILE i < LEN(word) DO\nIF text[pos + i] == word[i] THEN\nDECLARE i AS i + 1\nELSE\nRETURN -1\nENDIF\nENDWHILE\nRETURN pos + LEN(word)\nEND RITE\n\nDEFINE RITE JSON_PARSE_VALUE(text, pos)\nDECLARE i AS JSON_SKIP(text, pos)\nDECLARE c AS text[i]\nIF c == \"\\\"\" THEN\nRETURN JSON_PARSE_STRING(text, i)\nENDIF\nIF c == \"[\" THEN\nRETURN JSON_PARSE_ARRAY(text, i)\nENDIF\nIF c == \"{{\" THEN\nRETURN JSON_PARSE_OBJECT(text, i)\nENDIF\nIF c == \"t\" THEN\nRETURN [true, JSON_EXPECT(text, i, \"true\")]\nENDIF\nIF c == \"f\" THEN\nRETURN [false, JSON_EXPECT(text, i, \"false\")]\nENDIF\nIF c == \"n\" THEN\nRETURN [void, JSON_EXPECT(text, i, \"null\")]\nENDIF\nRETURN JSON_PARSE_NUMBER(text, i)\nEND RITE\n\nDEFINE RITE JSON_PARSE_ARRAY(text, pos)\nDECLARE items AS []\nDECLARE i AS JSON_SKIP(text, pos + 1)\nIF text[i] == \"]\" THEN\nRETURN [items, i + 1]\nENDIF\nWHILE true DO\nDECLARE valres AS JSON_PARSE_VALUE(text, i)\nDECLARE items AS PUSH(items, valres[0])\nDECLARE i AS JSON_SKIP(text, valres[1])\nIF text[i] == \",\" THEN\nDECLARE i AS i + 1\nELSE\nRETURN [items, i + 1]\nENDIF\nENDWHILE\nEND RITE\n\nDEFINE RITE JSON_PARSE_OBJECT(text, pos)\nDECLARE pairs AS []\nDECLARE i AS JSON_SKIP(text, pos + 1)\nIF text[i] == \"}\" THEN\nRETURN [pairs, i + 1]\nENDIF\nWHILE true DO\nDECLARE i AS JSON_SKIP(text, i)\nDECLARE keyres AS JSON_PARSE_STRING(text, i)\nDECLARE key AS keyres[0]\nDECLARE i AS JSON_SKIP(text, keyres[1] + 1)\nDECLARE valres AS JSON_PARSE_VALUE(text, i)\nDECLARE pairs AS PUSH(pairs, [key, valres[0]])\nDECLARE i AS JSON_SKIP(text, valres[1])\nIF text[i] == \",\" THEN\nDECLARE i AS i + 1\nELSE\nRETURN [pairs, i + 1]\nENDIF\nENDWHILE\nEND RITE\n\nDEFINE RITE JSON_DECODE(text)\nDECLARE res AS JSON_PARSE_VALUE(text, 0)\nRETURN res[0]\nEND RITE\n","lists.god":"# The Scroll of Multitudes -- reckonings over gathered lists.\n# Rites: SUM, AVG, CONTAINS, SECOND, TAIL, COUNT.\n\nDEFINE RITE SUM(xs)\nDECLARE total AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nDECLARE total AS total + xs[i]\nDECLARE i AS i + 1\nENDWHILE\nRETURN total\nEND RITE\n\nDEFINE RITE AVG(xs)\nRETURN SUM(xs) / LEN(xs)\nEND RITE\n\nDEFINE RITE CONTAINS(xs, x)\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nRETURN 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN 0\nEND RITE\n\nDEFINE RITE SECOND(xs)\nRETURN xs[1]\nEND RITE\n\nDEFINE RITE TAIL(xs)\nDECLARE tail AS []\nDECLARE i AS 1\nWHILE i < LEN(xs) DO\nDECLARE tail AS PUSH(tail, xs[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN tail\nEND RITE\n\nDEFINE RITE COUNT(xs, x)\nDECLARE n AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nDECLARE n AS n + 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN n\nEND RITE\n","math.god":"# The Scroll of Numbers -- divine arithmetic for the children of creation.\n# Rites: SQRT, POW, ABS, MIN, MAX, FACTORIAL, IS_EVEN.\n\nDEFINE RITE SQRT(x)\nIF x IS 0 THEN\nRETURN 0\nENDIF\nIF x < 0 THEN\nRETURN 0\nENDIF\nDECLARE guess AS x\nWHILE ABS(guess * guess - x) > 0.000000001 DO\nDECLARE guess AS guess - (guess * guess - x) / (2 * guess)\nENDWHILE\nRETURN guess\nEND RITE\n\nDEFINE RITE POW(b, e)\nDECLARE result AS 1\nDECLARE i AS 0\nWHILE i < e DO\nDECLARE result AS result * b\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE ABS(x)\nIF x < 0 THEN\nRETURN 0 - x\nENDIF\nRETURN x\nEND RITE\n\nDEFINE RITE MIN(a, b)\nIF a < b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE MAX(a, b)\nIF a > b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE FACTORIAL(n)\nDECLARE result AS 1\nDECLARE i AS 1\nWHILE i <= n DO\nDECLARE result AS result * i\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE IS_EVEN(n)\nIF n % 2 IS 0 THEN\nRETURN 1\nENDIF\nRETURN 0\nEND RITE\n","my-blessing.god":"# my-blessing, a newborn scroll.\n# Run it with: godcode run main.god\n# Test it with: godcode test .\n\nBEGIN CREATION\n\n DECLARE INTENT \"speak a blessing of peace over the household\" ON evening_blessing\n\n DEFINE RITE evening_blessing()\n REVEAL(\"Peace be upon this house.\")\n REVEAL(\"May the morning bring grace and the evening bring rest.\")\n END RITE\n\n DECLARE day AS \"a new day\"\n evening_blessing()\n REVEAL(\"Walk into {day} with courage.\")\n\nEND CREATION\n","prophecy.god":"# The Scroll of Lots -- discerning choice by sacred chance.\n# Rites: PROPHESY_NUMBER, CAST_LOTS, CHOOSE.\n\nDEFINE RITE PROPHESY_NUMBER(n)\nRETURN RANDOM(n)\nEND RITE\n\nDEFINE RITE CAST_LOTS()\nRETURN RANDOM(2)\nEND RITE\n\nDEFINE RITE CHOOSE(xs)\nRETURN xs[RANDOM(LEN(xs))]\nEND RITE\n","strings.god":"# The Scroll of Tongues -- words shaped, lifted up, and proclaimed.\n# Rites: SHOUT, WHISPER, WORDS, CHARS, FIRST, LAST.\n\nDEFINE RITE SHOUT(s)\nRETURN UPPER(s) + \"!\"\nEND RITE\n\nDEFINE RITE WHISPER(s)\nRETURN LOWER(s)\nEND RITE\n\nDEFINE RITE WORDS(s)\nRETURN SPLIT(s, \" \")\nEND RITE\n\nDEFINE RITE CHARS(s)\nDECLARE chars AS []\nDECLARE i AS 0\nWHILE i < LEN(s) DO\nDECLARE chars AS PUSH(chars, s[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN chars\nEND RITE\n\nDEFINE RITE FIRST(s)\nRETURN s[0]\nEND RITE\n\nDEFINE RITE LAST(s)\nRETURN s[LEN(s) - 1]\nEND RITE\n","time.god":"# The Scroll of Appointed Times -- beholding the hour and the day.\n# Rites: NOW, TODAY.\n\nDEFINE RITE NOW()\nRETURN BEHOLD()\nEND RITE\n\nDEFINE RITE TODAY()\nRETURN SPLIT(BEHOLD(), \"T\")[0]\nEND RITE\n"},"samples":[{"code":"# The commons at work: everyday tools for words, lists, maps, and numbers.\n# Twenty-six small builtins, always present, no import needed.\n\nBEGIN CREATION\n # Words: trim the edges, renew a name, ask what it holds\n DECLARE raw AS \" manna, manna, honey \"\n REVEAL(TRIM(raw)) # \"manna, manna, honey\"\n REVEAL(REPLACE(TRIM(raw), \"manna\", \"bread\")) # \"bread, bread, honey\"\n REVEAL(REPEAT(\"Pula! \", 3)) # \"Pula! Pula! Pula! \"\n REVEAL(STARTS_WITH(\"dawn breaks\", \"dawn\")) # true\n REVEAL(ENDS_WITH(\"dawn breaks\", \"breaks\")) # true\n REVEAL(SUBSTRING(\"blessing\", 2, 6)) # \"essi\"\n REVEAL(COUNT(\"banana bread\", \"an\")) # 2\n\n # Lists: order them, weigh them, find their members\n DECLARE harvest AS [12, 7, 19, 7, 12, 4]\n REVEAL(SORT(harvest)) # [4, 7, 7, 12, 12, 19]\n REVEAL(harvest) # untouched: [12, 7, 19, 7, 12, 4]\n REVEAL(SUM_OF(harvest)) # 61\n REVEAL(MIN_OF(harvest)) # 4\n REVEAL(MAX_OF(harvest)) # 19\n REVEAL(UNIQUE(harvest)) # [12, 7, 19, 4]\n REVEAL(INDEX_OF(SORT(harvest), 19)) # 5\n REVEAL(FIRST(SORT(harvest))) # 4\n REVEAL(LAST(SORT(harvest))) # 19\n\n # Maps: read their keys, weave them together\n DECLARE store AS JSON_PARSE(\"{{\\\"bread\\\": 30, \\\"honey\\\": 12}}\")\n REVEAL(KEYS(store)) # [bread, honey]\n REVEAL(VALUES(store)) # [30, 12]\n REVEAL(HAS_KEY(store, \"bread\")) # true\n DECLARE fuller AS MERGE(store, JSON_PARSE(\"{{\\\"milk\\\": 8}}\"))\n REVEAL(fuller) # {bread: 30, honey: 12, milk: 8}\n\n # Numbers: round them kindly, root them, raise them\n REVEAL(ROUND(2.5)) # 3\n REVEAL(ROUND(19.995, 2)) # 20\n REVEAL(FLOOR(3.9)) # 3\n REVEAL(CEIL(3.1)) # 4\n REVEAL(SQRT(144)) # 12\n REVEAL(POW(2, 10)) # 1024\n REVEAL(ABS(4 - 9)) # 5\nEND CREATION\n","file":"commons_demo.god","label":"The Commons (everyday builtins)"},{"code":"# Strings Demo — the scroll of strings: SHOUT, WHISPER, WORDS.\nBEGIN CREATION\n IMPORT \"strings\"\n DECLARE greeting AS \"peace be with you\"\n REVEAL(SHOUT(greeting))\n REVEAL(WHISPER(\"LOUD PRAISE\"))\n REVEAL(WORDS(greeting))\n ASCEND\nEND CREATION\n","file":"strings_demo.god","label":"The Scroll of Strings"},{"code":"# Time Demo — the scroll of hours: NOW and TODAY.\nBEGIN CREATION\n IMPORT \"time\"\n REVEAL(NOW())\n REVEAL(TODAY())\n ASCEND\nEND CREATION\n","file":"time_demo.god","label":"The Scroll of Hours (NOW, TODAY)"},{"code":"# Intent demo — DECLARE INTENT names a rite's purpose in plain words.\n# When the rite is invoked, the Spirit discerns whether its words still\n# walk in the declared intent: alignment is blessed, drift is counseled.\n# Nothing here can fail the run; the Spirit counsels, it does not condemn.\nBEGIN CREATION\n DECLARE INTENT \"bring peace to the household\" ON evening_blessing\n DECLARE INTENT \"bring peace to the household\" ON war_drum\n\n DEFINE RITE evening_blessing()\n REVEAL(\"peace upon this house\")\n END RITE\n\n DEFINE RITE war_drum()\n DECLARE tally AS 1 + 2\n REVEAL(tally)\n END RITE\n\n INVOKE evening_blessing()\n INVOKE war_drum()\nEND CREATION\n","file":"intent_demo.god","label":"Declared Intent"},{"code":"# Anchor demo — ANCHOR writes a value's hash to the chain and returns a\n# receipt map: {chain, anchor_hash, height, timestamp, payload_hash}.\n# Run `godcode ledger verify` afterward to see both chains attested.\nBEGIN CREATION\n DECLARE covenant AS contract(\"everlasting\")\n BREATHE LIFE INTO covenant\n BLESS covenant\n DECLARE receipt AS ANCHOR(covenant)\n REVEAL(receipt)\n REVEAL(\"chain: \" + receipt[\"chain\"])\n REVEAL(\"height: \" + STR(receipt[\"height\"]))\n REVEAL(\"anchor hash: \" + receipt[\"anchor_hash\"])\nEND CREATION\n","file":"anchor_demo.god","label":"Anchored Seals (ANCHOR)"},{"code":"# Consult demo — CONSULT lays a question before the local Spirit oracle\n# and receives two to three sentences of counsel. No external calls;\n# the oracle lives inside the engine.\nBEGIN CREATION\n REVEAL(CONSULT(\"How should I structure this covenant?\"))\n REVEAL(CONSULT(\"What is the wisest next step for this work?\"))\nEND CREATION\n","file":"consult_demo.god","label":"Consult the Oracle"},{"code":"# Scroll Blessings Demo — borrow a blessing from the scroll registry.\n#\n# Install the scroll first:\n# godcode scroll install blessings\n# (installs from the local registry into ~/.godcode/scrolls/).\n# IMPORT then finds it through the normal resolution order —\n# stdlib first, then installed registry scrolls.\n\nBEGIN CREATION\n IMPORT \"blessings\"\n REVEAL(\"the registry bestows this blessing\")\n REVEAL(REVEAL_BLESSING())\n ASCEND\nEND CREATION\n","file":"scroll_blessings_demo.god","label":"Scroll Registry (IMPORT \"blessings\")"},{"code":"# Rites Demo — define a named blessing with parameters,\n# RETURN a value from it, and INVOKE it.\nBEGIN CREATION\n DEFINE RITE BLESSING(name)\n RETURN \"grace upon \" + name\n END RITE\n INVOKE BLESSING(\"seeker\")\n DECLARE word AS BLESSING(\"seeker\")\n REVEAL(word)\n ASCEND\nEND CREATION\n","file":"rites_demo.god","label":"Rites and Closures"},{"code":"# Casting Lots — the scroll of prophecy: let the Spirit choose.\nBEGIN CREATION\n IMPORT \"prophecy\"\n DECLARE tribes AS [Judah, Reuben, Gad, Asher]\n REVEAL(CHOOSE(tribes))\n REVEAL(CAST_LOTS())\n ASCEND\nEND CREATION\n","file":"lots.god","label":"Casting Lots"},{"code":"# tongue: ig\n# Ndewo. The first blessing spoken in Igbo.\n# Run it: godcode run examples/first_blessing_ig.god\n# Dotted vowels are optional: DỊKA and DIKA both speak.\nBIDO OKIKE\nKWUSAA aha DỊKA \"enyi m\"\nGOSI(\"Ndewo, {aha}.\")\n\nKWUSAA ubochi DỊKA [\"Eke\", \"Orie\", \"Afọ\", \"Nkwọ\"]\nGOSI(\"Ụbọchị ahịa anọ: {ubochi}\")\n\nỌ BỤRỤ LEN(ubochi) BỤ 0 MGBE AHỤ\n GOSI(\"Enweghị ụbọchị\")\nELSE\n GOSI(\"Ụbọchị ahịa dị {LEN(ubochi)}\")\nNJEDEBE MA\n\nNWAA\n KWUSAA oke DỊKA 10 / 0\nJIDE\n GOSI(\"E jidere njehie, mana ọrụ ka na-aga n'ihu\")\nNJEDEBE NWAA\n\nGOSI(\"Daalụ.\")\nNJEDEBE OKIKE\n","file":"first_blessing_ig.god","label":"Ndewo (Igbo)"},{"code":"# tongue: pg\n# How far! The first blessing spoken in Nigerian Pidgin.\n# Run it: godcode run examples/first_blessing_pg.god\n# Pidgin shares many words with English (IF, TRY, ELSE), so they stay.\nOYA KREASHON\nTALK name BE \"my padi\"\nSHOW(\"How far, {name}?\")\n\nTALK days BE [\"Monday\", \"Tuesday\", \"Wednesday\"]\nSHOW(\"Three days for the week: {days}\")\n\nIF LEN(days) NA 0 DEN\n SHOW(\"No day dey\")\nELSE\n SHOW(\"We get {LEN(days)} days\")\nFINISH IF\n\nTRY\n TALK share BE 10 / 0\nHOLD\n SHOW(\"Wahala don happen, but the work still dey go\")\nFINISH TRY\n\nSHOW(\"God dey.\")\nFINISH KREASHON\n","file":"first_blessing_pg.god","label":"How far (Nigerian Pidgin)"}],"version":"4.1.0"} +{"files":{"god_code_training_dataset.csv":"code,primary_action,logic_flows,spiritual_intent,next_suggestions\nBEGIN CREATION\nDECLARE soul AS contract(\"redemption\")\nBREATHE life INTO soul\nASCEND\nEND CREATION,Deploy smart contract,contract deployment | symbolic syntax,Manifest a redemptive contract,REFLECT on contract values\nBEGIN CREATION\nPROPHESY outcome OF mission IN 3 cycles\nREVEAL(\"result\")\nASCEND\nEND CREATION,Forecast future outcome,predictive logic | prophecy-based evaluation,Foresee the success or delay of a divine mission,Log prophecy and evaluate\nBEGIN CREATION\nIF seeker IS worthy THEN\nREVEAL(truth)\nENDIF\nASCEND\nEND CREATION,Controlled data access,conditional logic | spiritual worthiness,Reveal hidden truth to worthy seekers,Reflect on seeker metrics\nBEGIN CREATION\nDEFINE RITE evening_blessing()\nREVEAL(\"peace upon this house\")\nEND RITE\nINVOKE evening_blessing()\nASCEND\nEND CREATION,Blessing of peace,rite invocation | spoken blessing,Bring peace to the household and rest to every heart within,Speak the blessing each evening without ceasing\nBEGIN CREATION\nDECLARE covenant AS contract(\"everlasting\")\nDECLARE seal AS ANCHOR(covenant)\nREVEAL(seal)\nASCEND\nEND CREATION,Anchor a covenant,sealing | hash-chained witness,Set the covenant in unbreakable remembrance upon the chain,Verify the anchor before you testify of it\nBEGIN CREATION\nREVEAL(CONSULT(\"How should I structure this covenant\"))\nASCEND\nEND CREATION,Seek counsel,question | oracle answer,Ask in humility and receive wisdom for the work ahead,Weigh the counsel and act in peace\n","godcode/__init__.py":"\"\"\"God Code v3.0 — the language of divine computation.\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any\n\n__version__ = \"4.1.0\"\n\n\n@dataclass\nclass RunResult:\n \"\"\"The outcome of running God Code from a host program.\n\n ``output`` is the captured REVEAL output (lines joined with ``\\\\n``);\n ``return_value`` is the value of a top-level ``RETURN`` (if the scroll\n ascends that way) or of the last expression statement evaluated, else\n ``None``; ``error`` is the divine error message (with line number) when\n the run failed; ``ok`` tells whether the run completed.\n \"\"\"\n\n output: str = \"\"\n return_value: Any = None\n error: str | None = None\n ok: bool = False\n\n\ndef run_source(source: str, *, filename: str = \"\") -> RunResult:\n \"\"\"Run God Code source from a host program and capture the outcome.\n\n REVEAL output is captured per-interpreter (via the interpreter's ``emit``\n hook), so this is safe to call many times in one process. Plugin\n auto-loading still applies unless ``GODCODE_NO_PLUGINS=1`` is set.\n Embedding runs do not write the audit log.\n \"\"\"\n from godcode.errors import GodCodeError, ReturnSignal\n from godcode.interpreter import Interpreter\n\n lines: list[str] = []\n interpreter = Interpreter(log_path=None)\n interpreter.emit = lines.append\n try:\n interpreter.run_source(source, source_name=filename)\n except ReturnSignal as ret:\n # A top-level RETURN becomes the run's return value.\n return RunResult(\n output=\"\\n\".join(lines), return_value=ret.value, error=None, ok=True\n )\n except GodCodeError as err:\n return RunResult(\n output=\"\\n\".join(lines),\n return_value=None,\n error=str(err),\n ok=False,\n )\n except Exception as exc: # a host/plugin failure outside the divine errors\n return RunResult(\n output=\"\\n\".join(lines),\n return_value=None,\n error=f\"the outer world faltered: {exc!r}\",\n ok=False,\n )\n return RunResult(\n output=\"\\n\".join(lines),\n return_value=interpreter.last_value,\n error=None,\n ok=True,\n )\n\n\ndef run_file(path: str | Path) -> RunResult:\n \"\"\"Run a God Code scroll file from a host program; see :func:`run_source`.\"\"\"\n try:\n source = Path(path).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return RunResult(\n output=\"\",\n return_value=None,\n error=f\"cannot read '{path}': {exc.strerror or exc}\",\n ok=False,\n )\n return run_source(source, filename=str(path))\n\n\n__all__ = [\"__version__\", \"RunResult\", \"run_source\", \"run_file\"]\n","godcode/__main__.py":"\"\"\"Allow ``python -m godcode ``.\"\"\"\nimport sys\n\nfrom godcode.cli import main\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","godcode/agentics.py":"\"\"\"Machine-readable output for AI agents (Mini-Pillar 5 — Agentics).\n\nThis module turns God Code diagnostics and run results into stable JSON\npayloads an agent can parse without scraping divine prose. The CLI wires\nit in behind ``--json`` on the ``run`` and ``check`` commands.\n\nError-code mapping choice\n-------------------------\nCodes are a small, stable, language-agnostic vocabulary derived from the\nv2.0 exception hierarchy in :mod:`godcode.errors` (there is no\n``GodCodeSyntaxError`` class in v2.0, so the mapping below is explicit):\n\n LexerError -> LEXER_ERROR\n ParseError -> PARSE_ERROR\n GodRuntimeError -> RUNTIME_ERROR\n\nAny other ``GodCodeError`` subclass falls back to a mechanical\nCamelCase -> UPPER_SNAKE conversion of its class name\n(e.g. ``FooBarError`` -> ``FOO_BAR_ERROR``). Failures that are not God\nCode failures at all (an unreadable scroll file) use ``FILE_ERROR``,\nwhich is not an exception class.\n\nCapture choice\n--------------\n``run`` output is captured with :func:`contextlib.redirect_stdout` into\na :class:`io.StringIO` around the interpreter call — no dependency on\nany capture hooks from sibling pillars.\n\nSeals\n-----\nAfter the run we diff the interpreter's bound ``ledger`` (when present)\nagainst its block count before the run. Blocks sealed during the run are\nreported as ``{\"block\": , \"hash\": }``. When no ledger is\nbound or it cannot be read, ``seals`` is ``[]`` — never an error.\n\"\"\"\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nimport json\nimport re\nimport sys\nimport time\nfrom pathlib import Path\n\nTOOL_NAME = \"godcode\"\n\n# ---------------------------------------------------------------------------\n# error codes\n# ---------------------------------------------------------------------------\n_CODE_MAP = {\n \"LexerError\": \"LEXER_ERROR\",\n \"ParseError\": \"PARSE_ERROR\",\n \"GodRuntimeError\": \"RUNTIME_ERROR\",\n}\n\n_HINTS = {\n \"LEXER_ERROR\": (\n \"Scan the reported line for stray symbols or an unterminated \"\n \"string; God Code strings use double quotes.\"\n ),\n \"PARSE_ERROR\": (\n \"Every scroll needs BEGIN CREATION ... END CREATION; comparisons \"\n \"use IS / IS NOT, and every block needs its closer \"\n \"(ENDIF, ENDFOR, ENDWHILE, END RITE).\"\n ),\n \"RUNTIME_ERROR\": (\n \"The scroll parsed but stumbled while running. DECLARE every \"\n \"name before use and re-read the reported line.\"\n ),\n \"FILE_ERROR\": \"Check the path. The scroll must exist and be readable.\",\n}\n\n\ndef _to_snake(name: str) -> str:\n return re.sub(r\"(? str:\n \"\"\"Map a God Code exception to its stable machine code.\"\"\"\n name = type(err).__name__\n if name in _CODE_MAP:\n return _CODE_MAP[name]\n snake = _to_snake(name)\n return snake if snake.endswith(\"_ERROR\") else snake + \"_ERROR\"\n\n\ndef hint_for(code: str) -> str | None:\n \"\"\"One-line actionable suggestion for a code, or None.\"\"\"\n return _HINTS.get(code)\n\n\ndef diagnostic(err, *, severity: str = \"error\") -> dict:\n \"\"\"Turn a GodCodeError into a JSON-serializable diagnostic dict.\"\"\"\n code = error_code(err)\n # err.msg is the clean message; str(err) may append \"(line N)\" which\n # would duplicate the structured line/col fields below.\n return {\n \"line\": getattr(err, \"line\", None),\n \"col\": getattr(err, \"col\", None),\n \"code\": code,\n \"severity\": severity,\n \"message\": getattr(err, \"msg\", None) or str(err),\n \"hint\": hint_for(code),\n }\n\n\ndef error_trace(err) -> list[dict]:\n \"\"\"The ``run --json`` trace array for a failed run.\n\n A list of ``{\"rite\": name, \"line\": call-site line}``, oldest call first\n (the most recent call is last). Empty when the error rose at the top\n level, before any rite was called. The interpreter snapshots\n ``err.call_trace`` when the error first rises, before the call stack\n unwinds.\n \"\"\"\n return [\n {\"rite\": frame.get(\"rite\"), \"line\": frame.get(\"line\")}\n for frame in (getattr(err, \"call_trace\", None) or [])\n ]\n\n\ndef _file_error_diagnostic(path: str, exc: OSError) -> dict:\n detail = exc.strerror or str(exc)\n return {\n \"line\": None,\n \"col\": None,\n \"code\": \"FILE_ERROR\",\n \"severity\": \"error\",\n \"message\": f\"godcode: cannot read '{path}': {detail}\",\n \"hint\": hint_for(\"FILE_ERROR\"),\n }\n\n\n# ---------------------------------------------------------------------------\n# payload builders\n# ---------------------------------------------------------------------------\ndef check_payload(file: str, ok: bool, diagnostics: list[dict]) -> dict:\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"check\",\n \"file\": file,\n \"ok\": ok,\n \"diagnostics\": diagnostics,\n }\n\n\ndef run_payload(file: str, ok: bool, output: list[str],\n seals: list[dict], error: dict | None, ms: int,\n intents: list[dict] | None = None,\n permissions: dict | None = None) -> dict:\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"run\",\n \"file\": file,\n \"ok\": ok,\n \"output\": output,\n \"seals\": seals,\n \"intents\": intents if intents is not None else [],\n \"permissions\": permissions if permissions is not None else {},\n \"error\": error,\n \"stats\": {\"ms\": ms},\n }\n\n\ndef emit(payload: dict) -> None:\n \"\"\"Write one JSON document to stdout; nothing else may be printed.\"\"\"\n sys.stdout.write(json.dumps(payload, ensure_ascii=False) + \"\\n\")\n sys.stdout.flush()\n\n\n# ---------------------------------------------------------------------------\n# --json command implementations (called from godcode.cli)\n# ---------------------------------------------------------------------------\ndef cmd_check_json(args) -> int:\n \"\"\"`godcode check --json FILE`. Exit 0 if pure, 1 if diagnostics.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n emit(check_payload(args.file, False, [_file_error_diagnostic(args.file, exc)]))\n return 1\n try:\n parse_source(source)\n except GodCodeError as err:\n emit(check_payload(args.file, False, [diagnostic(err)]))\n return 1\n emit(check_payload(args.file, True, []))\n return 0\n\n\ndef _ledger_block_count(interp) -> int | None:\n ledger = getattr(interp, \"ledger\", None)\n if ledger is None:\n return None\n try:\n return len(ledger.read_all())\n except Exception:\n return None\n\n\ndef _new_seals(interp, before: int | None) -> list[dict]:\n \"\"\"Best-effort list of covenant blocks sealed during the run.\"\"\"\n if before is None:\n return []\n ledger = getattr(interp, \"ledger\", None)\n if ledger is None:\n return []\n try:\n blocks = ledger.read_all()[before:]\n except Exception:\n return []\n seals = []\n for block in blocks:\n if isinstance(block, dict) and \"hash\" in block:\n seals.append({\"block\": block.get(\"index\"), \"hash\": block.get(\"hash\")})\n return seals\n\n\ndef cmd_run_json(args) -> int:\n \"\"\"`godcode run --json FILE`. Exit 0 on success, 1 on failure.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.cli import _make_interpreter # shared with the plain run path\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n emit(run_payload(args.file, False, [], [], _file_error_diagnostic(args.file, exc), 0))\n return 1\n\n interp = _make_interpreter(args.log)\n seals_before = _ledger_block_count(interp)\n\n buf = io.StringIO()\n error: dict | None = None\n start = time.perf_counter()\n with contextlib.redirect_stdout(buf):\n try:\n interp.run_source(source, source_name=args.file)\n except GodCodeError as err:\n error = diagnostic(err)\n error[\"trace\"] = error_trace(err)\n ms = int((time.perf_counter() - start) * 1000)\n\n output = buf.getvalue().splitlines()\n seals = _new_seals(interp, seals_before)\n intents = list(getattr(interp, \"intent_checks\", []) or [])\n manifest = getattr(interp, \"manifest\", None)\n emit(run_payload(args.file, error is None, output, seals, error, ms,\n intents=intents,\n permissions=manifest.to_json() if manifest else {}))\n return 0 if error is None else 1\n","godcode/ast.py":"\"\"\"Abstract syntax tree nodes for God Code v2.0.\n\nEvery node carries 1-based ``line``/``col`` of the token that opened it.\nExpression fields are annotated with the ``Expr`` alias (a union of all\nexpression node types).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom typing import Union\n\n# Filled in below once the classes exist; string form keeps runtime cheap.\nExpr = Union[\n \"BinaryOp\", \"UnaryOp\", \"Literal\", \"Identifier\",\n \"ListLiteral\", \"Index\", \"CallExpr\",\n]\n\n\n# -- program structure -------------------------------------------------------\n\n@dataclass\nclass Program:\n statements: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass CreationBlock:\n statements: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n# -- statements --------------------------------------------------------------\n\n@dataclass\nclass Declare:\n name: str\n value: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass DeclareIntent:\n \"\"\"DECLARE INTENT \"words...\" ON rite_name -- the v4.0 intent layer.\"\"\"\n text: str\n rite: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass DeclarePermission:\n \"\"\"DECLARE PERMISSION TO -- the permission manifest.\n\n ``power`` is one of \"read\", \"write\", \"network\", \"stdin\", \"summon\";\n ``target`` is the granted path, host, or verb name (None for stdin).\n \"\"\"\n power: str\n target: str | None\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Breathe:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Reveal:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Prophesy:\n text: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Ascend:\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Reflect:\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Bless:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Anoint:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass SealStmt:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Testify:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass IfStmt:\n cond: Expr\n then_body: list = field(default_factory=list)\n else_body: list = field(default_factory=list)\n has_else: bool = False # True when an ELSE keyword was actually written\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass ForLoop:\n var: str\n iterable: Expr\n body: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass WhileLoop:\n cond: Expr\n body: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Break:\n \"\"\"BREAK: release the innermost enclosing loop at once.\"\"\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Continue:\n \"\"\"CONTINUE: skip to the next turn of the innermost enclosing loop.\"\"\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass TryStmt:\n \"\"\"TRY ... CATCH [name] ... ENDTRY: in-language error handling.\n\n The TRY block runs first; if a runtime error (GodRuntimeError) rises,\n the error's plain message is bound to ``error_name`` and the CATCH\n block runs. ``error_name`` defaults to \"ERROR\" when the CATCH carries\n no name. Control-flow signals (RETURN, ASCEND) are never caught.\n \"\"\"\n try_body: list = field(default_factory=list)\n catch_body: list = field(default_factory=list)\n error_name: str = \"ERROR\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass DefineRite:\n name: str\n params: list = field(default_factory=list) # list[str]\n body: list = field(default_factory=list)\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Return:\n expr: Expr | None = None\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Import:\n path: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass ExprStmt:\n expr: Expr\n line: int = 1\n col: int = 1\n\n\n# -- expressions -------------------------------------------------------------\n\n@dataclass\nclass BinaryOp:\n # op: '+','-','*','/','%', '==','!=','<','>','<=','>=', 'and','or'\n op: str\n left: Expr\n right: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass UnaryOp:\n # op: 'not', '-'\n op: str\n operand: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Literal:\n value: object # int | float | str | bool | None\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass InterpolatedString:\n \"\"\"A string holding ``{expr}`` blessings: parts are literal text (str)\n or expression nodes whose revealed value is breathed into the string.\n ``source`` keeps the original string content so formatters can re-emit it.\n \"\"\"\n\n parts: list = field(default_factory=list) # list[str | Expr]\n source: str = \"\"\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Identifier:\n name: str\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass ListLiteral:\n items: list = field(default_factory=list) # list[Expr]\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass Index:\n obj: Expr\n index: Expr\n line: int = 1\n col: int = 1\n\n\n@dataclass\nclass CallExpr:\n callee: str\n args: list = field(default_factory=list) # list[Expr]\n line: int = 1\n col: int = 1\n","godcode/chain.py":"\"\"\"Blockchain-anchored seals for God Code v4.0 -- \"Intent & Chain\".\n\nA ChainAdapter anchors a payload hash into a tamper-evident chain and\nlater verifies the receipt it handed back. The bundled\nSimulatedChainAdapter keeps the anchor chain as local JSONL\n(``anchors.chain``), mirroring :class:`godcode.ledger.CovenantLedger`;\nreal chain adapters (Ethereum, and the like) can be registered later\nwith :func:`register_adapter` -- that work belongs to the founder, not\nto this module. There are no network calls here, no wallets, no keys.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom datetime import datetime, timezone\nfrom pathlib import Path\n\nGENESIS_PREV_HASH = \"GENESIS\"\nDEFAULT_CHAIN_NAME = \"simulated\"\n\n\ndef _canonical(payload: dict) -> bytes:\n \"\"\"Canonical JSON bytes used for hashing (stable key order, no whitespace).\"\"\"\n return json.dumps(payload, sort_keys=True, separators=(\",\", \":\"),\n ensure_ascii=False).encode(\"utf-8\")\n\n\ndef _block_hash(index: int, timestamp: str, record: dict, prev_hash: str) -> str:\n return hashlib.sha256(\n _canonical(\n {\"index\": index, \"timestamp\": timestamp,\n \"record\": record, \"prev_hash\": prev_hash}\n )\n ).hexdigest()\n\n\nclass ChainAdapter:\n \"\"\"The contract every chain adapter honors.\n\n ``anchor(payload_hash)`` writes the hash into the chain and returns a\n receipt dict; ``verify(receipt)`` returns True only when the receipt\n matches a block that is still intact.\n \"\"\"\n\n name = \"adapter\"\n\n def anchor(self, payload_hash: str) -> dict:\n raise NotImplementedError\n\n def verify(self, receipt: dict) -> bool:\n raise NotImplementedError\n\n\nclass SimulatedChainAdapter(ChainAdapter):\n \"\"\"A local tamper-evident anchor chain (JSONL), standing in for a chain.\n\n Blocks look like ``{index, timestamp, record: {payload_hash},\n prev_hash, hash}``; the chain begins at ``\"GENESIS\"``. Receipts look\n like ``{chain, anchor_hash, height, timestamp, payload_hash}``.\n \"\"\"\n\n name = \"simulated\"\n\n def __init__(self, path: str | Path | None = \"anchors.chain\") -> None:\n self.path = Path(path) if path is not None else None\n self._memory: list[dict] = []\n if self.path is not None and str(self.path.parent) not in (\"\", \".\"):\n self.path.parent.mkdir(parents=True, exist_ok=True)\n\n # ---------------------------------------------------------- persistence\n\n def read_all(self) -> list[dict]:\n \"\"\"Every anchor block in chain order (empty when no chain yet).\"\"\"\n if self.path is None:\n return list(self._memory)\n if not self.path.exists():\n return []\n blocks: list[dict] = []\n with open(self.path, encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n if line:\n blocks.append(json.loads(line))\n return blocks\n\n def _append(self, block: dict) -> None:\n if self.path is None:\n self._memory.append(block)\n else:\n with open(self.path, \"a\", encoding=\"utf-8\") as f:\n f.write(json.dumps(block, ensure_ascii=False) + \"\\n\")\n\n # ------------------------------------------------------------- adapter\n\n def anchor(self, payload_hash: str) -> dict:\n \"\"\"Anchor a payload hash; return the receipt dict.\"\"\"\n blocks = self.read_all()\n index = len(blocks)\n prev_hash = blocks[-1][\"hash\"] if blocks else GENESIS_PREV_HASH\n timestamp = datetime.now(timezone.utc).isoformat()\n record = {\"payload_hash\": payload_hash}\n block = {\n \"index\": index,\n \"timestamp\": timestamp,\n \"record\": record,\n \"prev_hash\": prev_hash,\n \"hash\": _block_hash(index, timestamp, record, prev_hash),\n }\n self._append(block)\n return {\n \"chain\": self.name,\n \"anchor_hash\": block[\"hash\"],\n \"height\": block[\"index\"],\n \"timestamp\": block[\"timestamp\"],\n \"payload_hash\": payload_hash,\n }\n\n def verify(self, receipt: dict) -> bool:\n \"\"\"True when the receipt names a block that is present and intact.\"\"\"\n try:\n height = receipt[\"height\"]\n anchor_hash = receipt[\"anchor_hash\"]\n payload_hash = receipt[\"payload_hash\"]\n except (KeyError, TypeError, AttributeError):\n return False\n if not isinstance(height, int) or isinstance(height, bool):\n return False\n blocks = self.read_all()\n if height < 0 or height >= len(blocks):\n return False\n block = blocks[height]\n if block.get(\"hash\") != anchor_hash:\n return False\n if block.get(\"record\", {}).get(\"payload_hash\") != payload_hash:\n return False\n return _block_hash(\n block.get(\"index\"),\n block.get(\"timestamp\"),\n block.get(\"record\"),\n block.get(\"prev_hash\"),\n ) == block.get(\"hash\")\n\n def verify_chain(self) -> tuple[bool, str]:\n \"\"\"Recompute the whole anchor chain.\n\n (True, 'N anchors intact') or (False, 'anchor chain broken at\n block K').\n \"\"\"\n blocks = self.read_all()\n prev_hash = GENESIS_PREV_HASH\n for expected, block in enumerate(blocks):\n payload_ok = (\n block.get(\"index\") == expected\n and block.get(\"prev_hash\") == prev_hash\n and _block_hash(\n block.get(\"index\"),\n block.get(\"timestamp\"),\n block.get(\"record\"),\n block.get(\"prev_hash\"),\n )\n == block.get(\"hash\")\n )\n if not payload_ok:\n return False, f\"anchor chain broken at block {block.get('index')} ⚓💔\"\n prev_hash = block[\"hash\"]\n return True, f\"{len(blocks)} anchors intact ⚓\"\n\n\nclass MemoryChainAdapter(SimulatedChainAdapter):\n \"\"\"An ephemeral in-memory anchor chain: the sandbox's answer to ANCHOR.\n\n Same interface as the simulated chain, but nothing is written to\n disk. Anchors made here vanish when the run ends -- which is exactly\n what a deny-by-default sandbox requires.\n \"\"\"\n\n name = \"simulated\"\n\n def __init__(self) -> None:\n super().__init__(path=None)\n\n\n# ------------------------------------------------------------- registry\n\n_ADAPTERS: dict[str, ChainAdapter] = {}\n\n\ndef register_adapter(name: str, adapter: ChainAdapter) -> None:\n \"\"\"Register a chain adapter under *name* (e.g. a future real chain).\"\"\"\n if not isinstance(name, str) or not name:\n raise ValueError(\"a chain adapter needs a non-empty string name\")\n if not isinstance(adapter, ChainAdapter):\n raise ValueError(f\"'{name}' is not a ChainAdapter\")\n _ADAPTERS[name] = adapter\n\n\ndef get_adapter(name: str) -> ChainAdapter | None:\n \"\"\"The adapter registered under *name*, or None.\"\"\"\n return _ADAPTERS.get(name)\n\n\ndef default_adapters() -> dict[str, ChainAdapter]:\n \"\"\"A fresh per-interpreter registry holding the bundled adapters.\"\"\"\n adapters = dict(_ADAPTERS)\n adapters.setdefault(DEFAULT_CHAIN_NAME, SimulatedChainAdapter())\n return adapters\n\n\nregister_adapter(DEFAULT_CHAIN_NAME, SimulatedChainAdapter())\n","godcode/cli.py":"\"\"\"Command-line interface for the God Code engine.\n\nSubcommands: run, check, repl, fmt, ledger verify.\nSibling modules (lexer, parser, ast, interpreter, ledger, errors) are imported\nlazily inside each command so `--help` works even before they land.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\nimport os\nimport sys\nfrom pathlib import Path\n\n\n# ---------------------------------------------------------------------------\n# run\n# ---------------------------------------------------------------------------\ndef _print_run_error(source: str, err) -> None:\n \"\"\"Print a failed run's error the gentle way, then the call trace.\n\n The gentle rendering (message, line/col, source line, caret,\n Did-you-mean) is preserved exactly; the trace goes underneath in plain\n words. Errors raised at the top level carry an empty trace and show no\n trace section.\n \"\"\"\n from godcode.errors import format_call_trace, format_error\n\n print(format_error(source, err), file=sys.stderr)\n trace = list(getattr(err, \"call_trace\", None) or [])\n for line in format_call_trace(trace):\n print(line, file=sys.stderr)\n\n\n# --- v3: agentics --json ---\ndef _make_interpreter(log_path):\n \"\"\"Build an Interpreter the way `godcode run` always has, shared by the\n plain and --json run paths so they can never drift apart.\"\"\"\n from godcode.interpreter import Interpreter\n\n kwargs: dict = {}\n if log_path:\n kwargs[\"log_path\"] = log_path\n # Bind the Spirit and the covenant ledger by default; degrade\n # gracefully if either cannot be raised in this environment.\n try:\n from godcode.spirit import SpiritEngine\n kwargs[\"spirit\"] = SpiritEngine()\n except Exception:\n pass\n try:\n from godcode.ledger import CovenantLedger\n kwargs[\"ledger\"] = CovenantLedger()\n except Exception:\n pass\n return Interpreter(**kwargs)\n# --- end v3: agentics --json ---\n\n\ndef cmd_run(args: argparse.Namespace) -> int:\n from godcode.errors import GodCodeError\n\n # --- v3: sandbox commands ---\n if getattr(args, \"sandbox\", False):\n return _cmd_run_sandboxed(args)\n if getattr(args, \"allow_read\", None):\n print(\"godcode: --allow-read only has meaning with --sandbox. \"\n \"A plain run is unbound by the host, and the scroll's own \"\n \"permission manifest still narrows it.\",\n file=sys.stderr)\n return 2\n # --- end v3: sandbox commands ---\n\n # --- v3: agentics --json ---\n if getattr(args, \"json\", False):\n from godcode import agentics\n return agentics.cmd_run_json(args)\n # --- end v3: agentics --json ---\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n\n try:\n _make_interpreter(args.log).run_source(source, source_name=args.file)\n except GodCodeError as err:\n _print_run_error(source, err)\n return 1\n return 0\n\n\n# --- v3: sandbox commands ---\ndef _cmd_run_sandboxed(args: argparse.Namespace) -> int:\n \"\"\"Run a scroll under the strict sandbox policy.\n\n Spirit, covenant ledger, and the audit log stay unbound: they write\n to the host world, which the sandbox does not permit. The CLI itself\n reads the scroll file before the sandbox is entered — that read is\n the invoker's own act, not the creation's.\n \"\"\"\n from godcode.errors import GodCodeError\n from godcode.sandbox import SandboxPolicy, run_sandboxed\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(agentics.run_payload(\n args.file, False, [], [],\n agentics._file_error_diagnostic(args.file, exc), 0))\n else:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n\n source_dir = str(Path(args.file).resolve().parent)\n read_grants = tuple(\n str(Path(path).resolve())\n for path in (getattr(args, \"allow_read\", None) or []))\n policy = SandboxPolicy.strict(\n source_dir=source_dir,\n timeout_seconds=args.sandbox_timeout,\n allow_read_paths=read_grants or None,\n )\n if getattr(args, \"json\", False):\n # Machine-readable report; stdout carries exactly one JSON document.\n import contextlib\n import io\n import time as _time\n\n from godcode import agentics\n from godcode.sandbox import run_sandboxed_with_interpreter\n\n error = None\n output: list[str] = []\n intents: list[dict] = []\n interp = None\n start = _time.perf_counter()\n with contextlib.redirect_stdout(io.StringIO()):\n try:\n output, interp = run_sandboxed_with_interpreter(\n source, policy, source_name=args.file)\n intents = list(getattr(interp, \"intent_checks\", []) or [])\n except GodCodeError as err:\n error = agentics.diagnostic(err)\n error[\"trace\"] = agentics.error_trace(err)\n ms = int((_time.perf_counter() - start) * 1000)\n manifest = getattr(interp, \"manifest\", None)\n agentics.emit(agentics.run_payload(\n args.file, error is None, output, [], error, ms,\n intents=intents,\n permissions=manifest.to_json() if manifest else {}))\n return 0 if error is None else 1\n try:\n run_sandboxed(source, policy, source_name=args.file)\n except GodCodeError as err:\n _print_run_error(source, err)\n return 1\n return 0\n# --- end v3: sandbox commands ---\n\n\n# ---------------------------------------------------------------------------\n# check\n# ---------------------------------------------------------------------------\ndef cmd_check(args: argparse.Namespace) -> int:\n from godcode.errors import GodCodeError, format_error\n from godcode.tongues import parse_source\n\n # --- v3: agentics --json ---\n if getattr(args, \"json\", False):\n from godcode import agentics\n return agentics.cmd_check_json(args)\n # --- end v3: agentics --json ---\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n parse_source(source)\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n print(f\"✓ {args.file} is pure.\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# lint\n# ---------------------------------------------------------------------------\ndef cmd_lint(args: argparse.Namespace) -> int:\n import json as _json\n\n from godcode.errors import GodCodeError, format_error\n from godcode.linter import lint_source\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n findings = lint_source(source, source_name=args.file)\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n\n if getattr(args, \"json\", False):\n print(_json.dumps(\n {\"tool\": \"godcode\", \"command\": \"lint\", \"file\": args.file,\n \"ok\": not findings,\n \"findings\": [{\"line\": f.line, \"col\": f.col, \"rule\": f.rule,\n \"message\": f.message} for f in findings]},\n ensure_ascii=False))\n return 1 if findings else 0\n for f in findings:\n print(f\"line {f.line}, col {f.col} [{f.rule}] {f.message}\")\n return 1 if findings else 0\n\n\n# ---------------------------------------------------------------------------\n# test — the test runner\n# ---------------------------------------------------------------------------\ndef cmd_test(args: argparse.Namespace) -> int:\n import json as _json\n\n from godcode import tester\n\n target = Path(args.dir)\n if not target.is_dir():\n print(f\"godcode: '{args.dir}' is not a directory to test.\",\n file=sys.stderr)\n return 2\n report = tester.run_tests(target)\n if getattr(args, \"json\", False):\n print(_json.dumps(report.payload(args.dir), ensure_ascii=False))\n else:\n for line in report.text_lines():\n print(line)\n return 1 if report.failed else 0\n\n\n# ---------------------------------------------------------------------------\n# new — raise a fresh God Code project\n# ---------------------------------------------------------------------------\ndef cmd_new(args: argparse.Namespace) -> int:\n import json as _json\n\n from godcode.scaffold import ScaffoldError, create_project\n\n try:\n result = create_project(args.name, dest=args.path, author=args.author)\n except ScaffoldError as exc:\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"new\",\n \"ok\": False, \"error\": str(exc)},\n ensure_ascii=False))\n else:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n if getattr(args, \"json\", False):\n print(_json.dumps({\n \"tool\": \"godcode\", \"command\": \"new\", \"ok\": True,\n \"name\": result.name,\n \"directory\": str(result.directory),\n \"files\": result.files,\n }, ensure_ascii=False))\n return 0\n print(f\"🕊 A new scroll rises: {result.directory}\")\n for filename in result.files:\n print(f\" wrote {result.directory / filename}\")\n print(\"\")\n print(\"Next steps:\")\n print(f\" cd {result.directory}\")\n print(\" godcode run main.god # speak it\")\n print(\" godcode test . # test it\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# repl\n# ---------------------------------------------------------------------------\ndef cmd_repl(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.errors import GodCodeError, format_error\n from godcode.interpreter import Interpreter\n\n try:\n import readline # noqa: F401 (enables history + line editing)\n except ImportError:\n pass\n\n print(\"God Code Live Mode 🕊\")\n print(\"Speak your creation; end each utterance with a blank line. \"\n \"(:quit to ascend)\")\n interp = Interpreter(interactive=True)\n buf: list[str] = []\n while True:\n try:\n line = input(\"godcode> \" if not buf else \"...... \")\n except EOFError:\n print()\n break\n except KeyboardInterrupt:\n print()\n break\n if line.strip() in (\":quit\", \":q\"):\n break\n if not line.strip():\n if buf:\n chunk = \"\\n\".join(buf)\n buf = []\n try:\n interp.run_source(chunk, source_name=\"\")\n except GodCodeError as err:\n print(str(err), file=sys.stderr)\n continue\n buf.append(line)\n print(\"🕊 The sanctuary rests.\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# fmt — AST -> canonical God Code\n# ---------------------------------------------------------------------------\n_PRECEDENCE = {\n \"or\": 1, \"and\": 2,\n \"==\": 3, \"!=\": 3, \"<\": 3, \">\": 3, \"<=\": 3, \">=\": 3,\n \"+\": 4, \"-\": 4, \"*\": 5, \"/\": 5, \"%\": 5,\n}\n_UNARY_PREC = 6\n_BLOCK_NODES = {\"CreationBlock\", \"IfStmt\", \"ForLoop\", \"WhileLoop\",\n \"DefineRite\", \"TryStmt\"}\n\n\ndef _escape(text: str) -> str:\n return (text.replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"')\n .replace(\"\\n\", \"\\\\n\").replace(\"\\t\", \"\\\\t\"))\n\n\nclass CanonicalFormatter:\n \"\"\"Re-emit an AST as canonical God Code: keywords UPPER, 2-space indent,\n one statement per line, blank line between top-level blocks.\"\"\"\n\n def __init__(self) -> None:\n self._lines: list[str] = []\n self._depth = 0\n\n # -- driver ---------------------------------------------------------\n def format(self, program) -> str:\n prev_was_block = False\n for i, stmt in enumerate(program.statements):\n is_block = type(stmt).__name__ in _BLOCK_NODES\n if i and (is_block or prev_was_block):\n self._lines.append(\"\")\n self._emit_stmt(stmt)\n prev_was_block = is_block\n return \"\\n\".join(self._lines) + \"\\n\"\n\n def _emit_stmt(self, node) -> None:\n meth = getattr(self, \"_stmt_\" + type(node).__name__, None)\n if meth is None:\n raise ValueError(\n f\"the formatter knows not this node: {type(node).__name__}\")\n meth(node)\n\n def _line(self, text: str) -> None:\n self._lines.append(\" \" * self._depth + text)\n\n def _block(self, stmts) -> None:\n self._depth += 1\n for stmt in stmts:\n self._emit_stmt(stmt)\n self._depth -= 1\n\n # -- expressions ----------------------------------------------------\n def _expr(self, node, parent_prec: int = 0) -> str:\n kind = type(node).__name__\n if kind == \"BinaryOp\":\n prec = _PRECEDENCE[node.op]\n op = node.op.upper() if node.op in (\"and\", \"or\") else node.op\n text = (f\"{self._expr(node.left, prec)} {op} \"\n f\"{self._expr(node.right, prec + 1)}\")\n return f\"({text})\" if prec < parent_prec else text\n if kind == \"UnaryOp\":\n inner = self._expr(node.operand, _UNARY_PREC)\n if type(node.operand).__name__ == \"UnaryOp\":\n inner = f\"({inner})\"\n return f\"NOT {inner}\" if node.op == \"not\" else f\"-{inner}\"\n if kind == \"Literal\":\n return self._literal(node.value)\n if kind == \"InterpolatedString\":\n return f'\"{_escape(node.source)}\"'\n if kind == \"Identifier\":\n return node.name\n if kind == \"ListLiteral\":\n return \"[\" + \", \".join(self._expr(i) for i in node.items) + \"]\"\n if kind == \"Index\":\n return f\"{self._expr(node.obj, _UNARY_PREC)}[{self._expr(node.index)}]\"\n if kind == \"CallExpr\":\n return (f\"{node.callee}(\"\n + \", \".join(self._expr(a) for a in node.args) + \")\")\n raise ValueError(\n f\"the formatter knows not this expression: {kind}\")\n\n @staticmethod\n def _literal(value) -> str:\n if isinstance(value, str):\n return f'\"{_escape(value)}\"'\n if value is True:\n return \"true\"\n if value is False:\n return \"false\"\n if value is None:\n return \"void\"\n return repr(value)\n\n # -- statements -----------------------------------------------------\n def _stmt_CreationBlock(self, node) -> None:\n self._line(\"BEGIN CREATION\")\n self._block(node.statements)\n self._line(\"END CREATION\")\n\n def _stmt_Declare(self, node) -> None:\n value = node.value\n if type(value).__name__ == \"ListLiteral\":\n rhs = \", \".join(self._expr(i) for i in value.items)\n else:\n rhs = self._expr(value)\n self._line(f\"DECLARE {node.name} AS {rhs}\")\n\n def _stmt_DeclareIntent(self, node) -> None: # v4.0\n self._line(f'DECLARE INTENT \"{_escape(node.text)}\" ON {node.rite}')\n\n def _stmt_DeclarePermission(self, node) -> None:\n power = node.power.upper()\n if power == \"READ\":\n self._line(f'DECLARE PERMISSION TO READ \"{_escape(node.target)}\"')\n elif power == \"WRITE\":\n self._line(f'DECLARE PERMISSION TO WRITE \"{_escape(node.target)}\"')\n elif power == \"NETWORK\":\n self._line(f'DECLARE PERMISSION TO SPEAK WITH \"{_escape(node.target)}\"')\n elif power == \"STDIN\":\n self._line(\"DECLARE PERMISSION TO ASK THE WORLD\")\n elif power == \"SUMMON\":\n self._line(f'DECLARE PERMISSION TO SUMMON \"{_escape(node.target)}\"')\n\n def _stmt_Breathe(self, node) -> None:\n self._line(f\"BREATHE LIFE INTO {node.name}\")\n\n def _stmt_Reveal(self, node) -> None:\n self._line(f\"REVEAL({self._expr(node.expr)})\")\n\n def _stmt_Prophesy(self, node) -> None:\n self._line(f\"PROPHESY {node.text}\".rstrip())\n\n def _stmt_Ascend(self, node) -> None:\n self._line(\"ASCEND\")\n\n def _stmt_Reflect(self, node) -> None:\n self._line(\"REFLECT\")\n\n def _stmt_Bless(self, node) -> None:\n self._line(f\"BLESS {node.name}\")\n\n def _stmt_Anoint(self, node) -> None:\n self._line(f\"ANOINT {node.name}\")\n\n def _stmt_SealStmt(self, node) -> None:\n self._line(f\"SEAL {self._expr(node.expr)}\")\n\n def _stmt_Testify(self, node) -> None:\n self._line(f\"TESTIFY {self._expr(node.expr)}\")\n\n def _stmt_IfStmt(self, node) -> None:\n self._line(f\"IF {self._expr(node.cond)} THEN\")\n self._block(node.then_body)\n if node.else_body:\n self._line(\"ELSE\")\n self._block(node.else_body)\n self._line(\"ENDIF\")\n\n def _stmt_ForLoop(self, node) -> None:\n self._line(f\"FOR {node.var} IN {self._expr(node.iterable)}\")\n self._block(node.body)\n self._line(\"ENDFOR\")\n\n def _stmt_WhileLoop(self, node) -> None:\n self._line(f\"WHILE {self._expr(node.cond)} DO\")\n self._block(node.body)\n self._line(\"ENDWHILE\")\n\n def _stmt_TryStmt(self, node) -> None:\n self._line(\"TRY\")\n self._block(node.try_body)\n if node.error_name == \"ERROR\":\n self._line(\"CATCH\")\n else:\n self._line(f\"CATCH {node.error_name}\")\n self._block(node.catch_body)\n self._line(\"ENDTRY\")\n\n def _stmt_DefineRite(self, node) -> None:\n params = \", \".join(node.params)\n self._line(f\"DEFINE RITE {node.name}({params})\")\n self._block(node.body)\n self._line(\"END RITE\")\n\n def _stmt_Return(self, node) -> None:\n self._line(\"RETURN\" if node.expr is None\n else f\"RETURN {self._expr(node.expr)}\")\n\n def _stmt_Break(self, node) -> None:\n self._line(\"BREAK\")\n\n def _stmt_Continue(self, node) -> None:\n self._line(\"CONTINUE\")\n\n def _stmt_Import(self, node) -> None:\n self._line(f'IMPORT \"{_escape(node.path)}\"')\n\n def _stmt_ExprStmt(self, node) -> None:\n expr = node.expr\n if type(expr).__name__ == \"CallExpr\":\n args = \", \".join(self._expr(a) for a in expr.args)\n self._line(f\"INVOKE {expr.callee}({args})\")\n else:\n self._line(self._expr(expr))\n\n\ndef cmd_fmt(args: argparse.Namespace) -> int:\n from godcode.errors import GodCodeError, format_error\n from godcode.tongues import parse_source\n\n src_path = Path(args.file)\n try:\n source = src_path.read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n program = parse_source(source)\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n\n canonical = CanonicalFormatter().format(program)\n if args.in_place:\n src_path.write_text(canonical, encoding=\"utf-8\")\n else:\n sys.stdout.write(canonical)\n return 0\n\n\n# ---------------------------------------------------------------------------\n# ledger verify\n# ---------------------------------------------------------------------------\ndef cmd_ledger_verify(args: argparse.Namespace) -> int:\n # v4.0: verifies the covenant chain AND the anchor chain, reporting both.\n import json as _json\n\n from godcode.chain import SimulatedChainAdapter\n from godcode.ledger import CovenantLedger\n\n cov_ok, cov_message = CovenantLedger(args.file).verify()\n anc_ok, anc_message = SimulatedChainAdapter(args.anchor_file).verify_chain()\n if getattr(args, \"json\", False):\n _json_doc = {\n \"tool\": \"godcode\",\n \"command\": \"ledger\",\n \"subcommand\": \"verify\",\n \"ok\": cov_ok and anc_ok,\n \"covenant\": {\"ok\": cov_ok, \"message\": cov_message},\n \"anchors\": {\"ok\": anc_ok, \"message\": anc_message},\n }\n print(_json.dumps(_json_doc, ensure_ascii=False))\n return 0 if (cov_ok and anc_ok) else 1\n print(cov_message)\n print(anc_message)\n return 0 if (cov_ok and anc_ok) else 1\n\n\n# --- v3: scroll commands ---\n# Pillar 2 — Scroll Registry: publish/install/info/list installable scrolls.\n\n\ndef _scroll_registry():\n from godcode.registry import ScrollRegistry\n\n return ScrollRegistry()\n\n\ndef cmd_scroll_list(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.registry import ScrollError\n\n try:\n rows = _scroll_registry().list_installed()\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n if not rows:\n print(\"No scrolls installed. \"\n \"Publish one with `godcode scroll publish `, \"\n \"then `godcode scroll install `.\")\n return 0\n for row in rows:\n loc = \",\".join(row[\"locations\"])\n vers = \", \".join(row[\"versions\"])\n print(f\"{row['name']} {vers} [{loc}]\")\n return 0\n\n\ndef cmd_scroll_install(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError, ScrollNotFoundError\n\n try:\n try:\n receipt = _scroll_registry().install(\n args.name, version=args.version, project=args.project,\n remote=args.remote)\n except ScrollNotFoundError:\n if args.remote:\n raise\n # not in the local index: fall back to the remote registry\n receipt = _scroll_registry().install(\n args.name, version=args.version, project=args.project,\n remote=True)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n where = \"project-local\" if args.project else \"user-global\"\n desc = receipt[\"manifest\"][\"description\"][:60]\n deps = receipt.get(\"dependencies\") or {}\n dep_note = f\" (+{len(deps)} dependencies)\" if deps else \"\"\n print(f\"Installed {receipt['name']} {receipt['version']}{dep_note} \"\n f\"({where}, from {receipt.get('source', 'local')}: {desc}...)\")\n return 0\n\n\ndef cmd_scroll_publish(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError, read_manifest\n\n if not args.remote:\n try:\n manifest = _scroll_registry().publish(args.dir)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n print(f\"Published {manifest['name']} {manifest['version']} \"\n f\"to the local registry.\")\n return 0\n\n # --remote: push to the registry over HTTPS; needs a publish token.\n token = os.environ.get(\"GODCODE_PUBLISH_TOKEN\")\n if not token:\n print(\"godcode: publishing to the remote registry needs a publish \"\n \"token.\", file=sys.stderr)\n print(\"godcode: set the GODCODE_PUBLISH_TOKEN environment variable \"\n \"to your registry token and try again.\", file=sys.stderr)\n return 1\n from godcode.remote_registry import RegistryClientError, RemoteRegistry\n\n src = Path(args.dir)\n manifest_path = src / \"scroll.toml\"\n try:\n manifest = read_manifest(manifest_path)\n entry = src / manifest[\"entry\"]\n if not entry.is_file():\n raise ScrollError(\n f\"publish: entry file {manifest['entry']!r} not found in {src}\"\n )\n code = entry.read_text(encoding=\"utf-8\")\n except (ScrollError, OSError) as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n try:\n RemoteRegistry().publish_scroll(\n name=manifest[\"name\"],\n version=manifest[\"version\"],\n code=code,\n description=manifest[\"description\"],\n author=manifest[\"author\"],\n token=token,\n )\n except RegistryClientError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n print(f\"Published {manifest['name']} {manifest['version']} \"\n f\"to the remote registry.\")\n return 0\n\n\ndef cmd_scroll_search(args: argparse.Namespace) -> int:\n from godcode.remote_registry import RegistryClientError, RemoteRegistry\n\n try:\n rows = RemoteRegistry().search(args.query)\n except RegistryClientError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n if not rows:\n print(f\"No scrolls found for {args.query!r} in the remote registry.\")\n return 0\n for row in rows:\n desc = (row.get(\"description\") or \"\")[:70]\n print(f\"{row.get('name')} {row.get('latest', '?')} - {desc}\")\n return 0\n\n\ndef cmd_scroll_uninstall(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError\n\n try:\n removed = _scroll_registry().uninstall(args.name,\n version=args.version)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n for entry in removed:\n print(f\"Uninstalled {entry['name']} {entry['version']} \"\n f\"({entry['location']})\")\n return 0\n\n\ndef cmd_scroll_update(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError\n\n try:\n results = _scroll_registry().update(name=args.name,\n remote=args.remote)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n for result in results:\n if result.get(\"up_to_date\"):\n print(f\"{result['name']} is already at the newest version \"\n f\"({result['from']})\")\n else:\n print(f\"Updated {result['name']} {result['from']} -> \"\n f\"{result['to']} (from {result['source']})\")\n return 0\n\n\ndef cmd_scroll_info(args: argparse.Namespace) -> int:\n from godcode.registry import ScrollError\n\n try:\n info = _scroll_registry().info(args.name)\n except ScrollError as exc:\n print(f\"godcode: {exc}\", file=sys.stderr)\n return 1\n print(f\"name: {info['name']}\")\n if info[\"manifest\"]:\n manifest = info[\"manifest\"]\n print(f\"version: {info['latest']} (latest published)\")\n print(f\"author: {manifest['author']}\")\n print(f\"entry: {manifest['entry']}\")\n print(f\"godcode: {manifest['godcode']}\")\n print(f\"description: {manifest['description']}\")\n else:\n print(\"published: (not in the local registry)\")\n if info[\"published\"]:\n print(f\"published: {', '.join(info['published'])}\")\n if info[\"installed\"]:\n print(f\"installed: {', '.join(info['installed'])} \"\n f\"(project: {', '.join(info['installed_project']) or '--'}; \"\n f\"user: {', '.join(info['installed_user']) or '--'})\")\n else:\n print(f\"installed: (nowhere -- `godcode scroll install \"\n f\"{info['name']}` to receive it)\")\n return 0\n\n\ndef _add_scroll_commands(sub) -> None:\n p_scroll = sub.add_parser(\"scroll\", help=\"Scroll Registry commands\")\n scroll_sub = p_scroll.add_subparsers(dest=\"scroll_command\", required=True)\n\n p_list = scroll_sub.add_parser(\"list\", help=\"List installed scrolls\")\n p_list.set_defaults(func=cmd_scroll_list)\n\n p_install = scroll_sub.add_parser(\"install\",\n help=\"Install a scroll from the registry\")\n p_install.add_argument(\"name\", help=\"Scroll name, e.g. json-tools\")\n p_install.add_argument(\"--version\", default=None, metavar=\"X.Y.Z\",\n help=\"Exact version (default: latest published)\")\n p_install.add_argument(\"--project\", action=\"store_true\",\n help=\"Install project-local (.godcode/scrolls/) \"\n \"instead of user-global (~/.godcode/scrolls/)\")\n p_install.add_argument(\"--remote\", action=\"store_true\",\n help=\"Prefer the remote registry (default: local \"\n \"index first, remote as fallback)\")\n p_install.set_defaults(func=cmd_scroll_install)\n\n p_publish = scroll_sub.add_parser(\"publish\",\n help=\"Publish a scroll dir to the registry\")\n p_publish.add_argument(\"dir\", help=\"Directory holding scroll.toml\")\n p_publish.add_argument(\"--remote\", action=\"store_true\",\n help=\"Publish to the remote registry over HTTPS \"\n \"(needs the GODCODE_PUBLISH_TOKEN \"\n \"environment variable)\")\n p_publish.set_defaults(func=cmd_scroll_publish)\n\n p_info = scroll_sub.add_parser(\"info\",\n help=\"Show a scroll's manifest and state\")\n p_info.add_argument(\"name\", help=\"Scroll name\")\n p_info.set_defaults(func=cmd_scroll_info)\n\n p_search = scroll_sub.add_parser(\"search\",\n help=\"Search the remote registry\")\n p_search.add_argument(\"query\", help=\"Words to search for\")\n p_search.set_defaults(func=cmd_scroll_search)\n\n p_uninstall = scroll_sub.add_parser(\"uninstall\",\n help=\"Remove an installed scroll\")\n p_uninstall.add_argument(\"name\", help=\"Scroll name\")\n p_uninstall.add_argument(\"--version\", default=None, metavar=\"X.Y.Z\",\n help=\"Only remove this version \"\n \"(default: every installed version)\")\n p_uninstall.set_defaults(func=cmd_scroll_uninstall)\n\n p_update = scroll_sub.add_parser(\"update\",\n help=\"Update installed scrolls to the \"\n \"newest version\")\n p_update.add_argument(\"name\", nargs=\"?\", default=None,\n help=\"Scroll name (default: every installed scroll)\")\n p_update.add_argument(\"--remote\", action=\"store_true\",\n help=\"Prefer the remote registry when looking for \"\n \"newer versions\")\n p_update.set_defaults(func=cmd_scroll_update)\n\n\n# --- end v3: scroll commands ---\n\n# --- v3: lsp commands ---\ndef cmd_lsp(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.lsp import serve\n\n return serve()\n# --- end v3: lsp commands ---\n\n# --- v5.0: dap commands ---\ndef cmd_dap(args: argparse.Namespace) -> int: # noqa: ARG001\n from godcode.dap import serve\n\n return serve()\n# --- end v5.0: dap commands ---\n\n# --- permission manifests: `godcode permissions` ---\ndef cmd_permissions(args: argparse.Namespace) -> int:\n \"\"\"`godcode permissions scroll.god [--json]`: read the scroll's manifest.\n\n Parses the scroll and reports what powers it declares. No code runs,\n so reading a manifest is always safe.\n \"\"\"\n import json as _json\n\n from godcode.errors import GodCodeError\n from godcode.permissions import PermissionManifest, collect_manifest\n from godcode.tongues import parse_source\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n program = parse_source(source)\n except GodCodeError as err:\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"permissions\",\n \"file\": args.file, \"ok\": False,\n \"error\": str(err)}, ensure_ascii=False))\n else:\n print(f\"godcode: the scroll could not be read: {err}\",\n file=sys.stderr)\n return 1\n base_dir = Path(args.file).resolve().parent\n manifest: PermissionManifest = collect_manifest(program.statements, base_dir)\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"permissions\",\n \"file\": args.file, \"ok\": True,\n \"manifest\": manifest.to_json()},\n ensure_ascii=False))\n return 0\n lines = manifest.describe()\n if not lines:\n print(f\"{args.file} declares no permissions. It may touch nothing \"\n \"of the outer world.\")\n else:\n print(f\"The scroll {args.file} declares:\")\n for grant in lines:\n print(f\" - it {grant}\")\n return 0\n# --- end permission manifests ---\n\n# --- machine interfaces: `godcode explain` ---\ndef cmd_explain(args: argparse.Namespace) -> int:\n \"\"\"`godcode explain scroll.god [--json]`: say what a scroll does.\n\n Parses the scroll and reports its static facts: tongue, rites and\n their declared intents, declared names, reveals, seals, summons,\n consults, imports, and the permission manifest. No code runs, so\n explaining a scroll is always safe.\n \"\"\"\n import json as _json\n\n from godcode.errors import GodCodeError\n from godcode.explain import explain_facts, explain_payload, human_summary\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(explain_payload(\n args.file, False, [agentics._file_error_diagnostic(args.file, exc)]))\n else:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n try:\n facts = explain_facts(source, Path(args.file).resolve().parent)\n except GodCodeError as err:\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(explain_payload(\n args.file, False, [agentics.diagnostic(err)]))\n else:\n print(f\"godcode: the scroll could not be read: {err}\",\n file=sys.stderr)\n return 1\n if getattr(args, \"json\", False):\n from godcode import agentics\n agentics.emit(explain_payload(args.file, True, [], facts))\n return 0\n print(human_summary(args.file, facts))\n return 0\n# --- end machine interfaces ---\n\n# --- machine interfaces: `godcode schema` ---\ndef cmd_schema(args: argparse.Namespace) -> int:\n \"\"\"`godcode schema [name] [--json]`: list or print dated JSON schemas.\n\n The schemas freeze the machine shapes of `check --json`,\n `run --sandbox --json`, `explain --json`, and `ledger verify --json`\n under their dated contract; additive fields may appear but required\n fields never change meaning.\n \"\"\"\n import json as _json\n\n from godcode.tools import SCHEMA_DESCRIPTIONS, SCHEMA_NAMES, read_schema\n\n if not args.name:\n print(\"God Code machine interfaces (dated schemas):\")\n for name in SCHEMA_NAMES:\n print(f\" {name}: {SCHEMA_DESCRIPTIONS[name]}\")\n return 0\n text, error = read_schema(args.name)\n if error is not None:\n if getattr(args, \"json\", False):\n print(_json.dumps({\"tool\": \"godcode\", \"command\": \"schema\",\n \"ok\": False, \"error\": error},\n ensure_ascii=False))\n else:\n print(f\"godcode: {error}. The schemas are: \"\n f\"{', '.join(SCHEMA_NAMES)}.\", file=sys.stderr)\n return 1\n print(text)\n return 0\n# --- end machine interfaces ---\n\n# --- v4.0: intent command ---\ndef cmd_intent(args: argparse.Namespace) -> int:\n \"\"\"`godcode intent \"some words\" [--json]`: resolve intent via the Spirit.\"\"\"\n import json as _json\n\n from godcode.spirit import SpiritEngine\n\n result = SpiritEngine().resolve_intent(args.text)\n if getattr(args, \"json\", False):\n print(_json.dumps(\n {\"tool\": \"godcode\", \"command\": \"intent\",\n \"text\": args.text, \"result\": result},\n ensure_ascii=False))\n return 0\n pct = round(result[\"confidence\"] * 100)\n print(f\"[INTENT] The Spirit discerns: '{result['intent']}' \"\n f\"({pct}% certainty).\")\n print(f\"Spiritual intent: {result['spiritual_intent']}\")\n print(f\"Counsel: {result['suggestion']}\")\n aligned = result.get(\"aligned_with\") or []\n if aligned:\n for entry in aligned:\n print(f\"Aligned with: {entry['rite']} (\\\"{entry['declared']}\\\")\")\n else:\n print(\"Aligned with no declared intent.\")\n return 0\n# --- end v4.0: intent command ---\n\n\n# --- v4.0: tools + bridge commands (implemented in godcode.tools) ---\ndef cmd_tools(args: argparse.Namespace) -> int:\n from godcode.tools import cmd_tools as _cmd_tools\n\n return _cmd_tools(args)\n\n\ndef cmd_bridge(args: argparse.Namespace) -> int:\n from godcode.tools import cmd_bridge as _cmd_bridge\n\n return _cmd_bridge(args)\n\n\ndef cmd_mcp(args: argparse.Namespace) -> int:\n from godcode.mcp import cmd_mcp as _cmd_mcp\n\n return _cmd_mcp(args)\n# --- end v4.0 ---\n\n\n# --- v5.0: interactive debugger ---\ndef cmd_debug(args: argparse.Namespace) -> int:\n from godcode.debug_cli import cmd_debug as _cmd_debug\n\n return _cmd_debug(args)\n# --- end v5.0 ---\n\n\n# ---------------------------------------------------------------------------\n# parser assembly\n# ---------------------------------------------------------------------------\ndef build_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(\n prog=\"godcode\",\n description=\"God Code. The language of divine computation 🕊\")\n sub = parser.add_subparsers(dest=\"command\", required=True)\n\n p_run = sub.add_parser(\"run\", help=\"Execute a God Code scroll\")\n p_run.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_run.add_argument(\"--log\", default=None, metavar=\"PATH\",\n help=\"Audit log path (default: logs/godcode.log)\")\n # --- v3: sandbox commands ---\n p_run.add_argument(\"--sandbox\", action=\"store_true\",\n help=\"Run under the strict sandbox policy \"\n \"(deny fs writes, network, subprocesses, \"\n \"stdin; scroll imports limited to the \"\n \"scroll's own directory and the stdlib \"\n \"scrolls; time and step budgets enforced)\")\n p_run.add_argument(\"--sandbox-timeout\", type=float, default=5.0,\n metavar=\"SECS\",\n help=\"Wall-clock grant for --sandbox runs \"\n \"(default: 5.0 seconds)\")\n p_run.add_argument(\"--allow-read\", action=\"append\", default=[],\n metavar=\"DIR\",\n help=\"With --sandbox, grant the run host reads \"\n \"under DIR (repeatable). The scroll's \"\n \"permission manifest still narrows the \"\n \"grant: the run may read only what both \"\n \"the host and the scroll allow.\")\n # --- end v3: sandbox commands ---\n # --- v3: agentics --json ---\n p_run.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n # --- end v3: agentics --json ---\n p_run.set_defaults(func=cmd_run)\n\n p_check = sub.add_parser(\"check\",\n help=\"Lex and parse a scroll without running it\")\n p_check.add_argument(\"file\", help=\"Path to the .god scroll\")\n # --- v3: agentics --json ---\n p_check.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n # --- end v3: agentics --json ---\n p_check.set_defaults(func=cmd_check)\n\n p_repl = sub.add_parser(\"repl\", help=\"Enter the live sanctuary\")\n p_repl.set_defaults(func=cmd_repl)\n\n p_fmt = sub.add_parser(\"fmt\", help=\"Re-emit a scroll in canonical form\")\n p_fmt.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_fmt.add_argument(\"--in-place\", \"-w\", dest=\"in_place\",\n action=\"store_true\",\n help=\"Rewrite the file instead of printing\")\n p_fmt.set_defaults(func=cmd_fmt)\n\n p_lint = sub.add_parser(\"lint\",\n help=\"Lint a scroll for unused names, shadowing, \"\n \"empty blocks, and other quiet troubles\")\n p_lint.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_lint.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_lint.set_defaults(func=cmd_lint)\n\n p_test = sub.add_parser(\n \"test\",\n help=\"Run the TEST_ rites in a directory's test scrolls\")\n p_test.add_argument(\"dir\", nargs=\"?\", default=\".\",\n help=\"Directory holding test scrolls (default: the \"\n \"current directory). Only that directory is \"\n \"read; subfolders are not entered.\")\n p_test.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_test.set_defaults(func=cmd_test)\n\n p_new = sub.add_parser(\n \"new\",\n help=\"Raise a new God Code project (starter scroll, test scroll, \"\n \"scroll manifest, README)\")\n p_new.add_argument(\"name\", help=\"Project name (lowercase, e.g. my-scroll)\")\n p_new.add_argument(\"--path\", default=\".\", metavar=\"DIR\",\n help=\"Parent directory for the new project \"\n \"(default: the current directory)\")\n p_new.add_argument(\"--author\", default=\"\",\n help=\"Author name for the scroll manifest\")\n p_new.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_new.set_defaults(func=cmd_new)\n\n p_ledger = sub.add_parser(\"ledger\", help=\"Covenant ledger commands\")\n ledger_sub = p_ledger.add_subparsers(dest=\"ledger_command\", required=True)\n p_verify = ledger_sub.add_parser(\"verify\",\n help=\"Verify the covenant chain\")\n p_verify.add_argument(\"--file\", default=\"covenant.chain\", metavar=\"PATH\",\n help=\"Chain file (default: covenant.chain)\")\n # --- v4.0: the anchor chain is verified alongside the covenant chain ---\n p_verify.add_argument(\"--anchor-file\", default=\"anchors.chain\",\n metavar=\"PATH\",\n help=\"Anchor chain file (default: anchors.chain)\")\n # --- end v4.0 ---\n # --- machine interfaces: ledger verify --json ---\n p_verify.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report \"\n \"on stdout\")\n # --- end machine interfaces ---\n p_verify.set_defaults(func=cmd_ledger_verify)\n\n # --- v4.0: intent, tools, bridge commands ---\n p_intent = sub.add_parser(\"intent\",\n help=\"Resolve the intent behind words \"\n \"with the Spirit Engine\")\n p_intent.add_argument(\"text\", help=\"Words to resolve the intent of\")\n p_intent.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report on stdout\")\n p_intent.set_defaults(func=cmd_intent)\n\n p_permissions = sub.add_parser(\"permissions\",\n help=\"Read a scroll's permission manifest \"\n \"without running it\")\n p_permissions.add_argument(\"file\", help=\"The .god scroll to read\")\n p_permissions.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report \"\n \"on stdout\")\n p_permissions.set_defaults(func=cmd_permissions)\n\n p_tools = sub.add_parser(\"tools\",\n help=\"Show the MCP-compatible agent tool schemas\")\n p_tools.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit the schemas as JSON\")\n p_tools.set_defaults(func=cmd_tools)\n\n p_bridge = sub.add_parser(\"bridge\",\n help=\"Serve the agent tool bridge \"\n \"(JSON-RPC 2.0 over stdio)\")\n p_bridge.set_defaults(func=cmd_bridge)\n\n p_mcp = sub.add_parser(\"mcp\",\n help=\"Serve the MCP server over stdio \"\n \"(runs are always sandboxed)\")\n p_mcp.set_defaults(func=cmd_mcp)\n # --- end v4.0 ---\n\n # --- machine interfaces: explain + schema commands ---\n p_explain = sub.add_parser(\"explain\",\n help=\"Say what a scroll does, in plain words, \"\n \"without running it\")\n p_explain.add_argument(\"file\", help=\"The .god scroll to explain\")\n p_explain.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON report \"\n \"on stdout\")\n p_explain.set_defaults(func=cmd_explain)\n\n p_schema = sub.add_parser(\"schema\",\n help=\"List or print the dated JSON schemas \"\n \"for the machine interfaces\")\n p_schema.add_argument(\"name\", nargs=\"?\", default=None,\n help=\"Schema to print: check, run, explain, \"\n \"ledger-verify\")\n p_schema.add_argument(\"--json\", action=\"store_true\",\n help=\"Emit a machine-readable JSON error on \"\n \"stdout for unknown names\")\n p_schema.set_defaults(func=cmd_schema)\n # --- end machine interfaces ---\n\n # --- v3: scroll commands ---\n _add_scroll_commands(sub)\n # --- end v3: scroll commands ---\n\n # --- v3: lsp commands ---\n p_lsp = sub.add_parser(\"lsp\",\n help=\"Start the language server over stdio\")\n p_lsp.set_defaults(func=cmd_lsp)\n # --- end v3: lsp commands ---\n\n # --- v5.0: dap commands ---\n p_dap = sub.add_parser(\"dap\",\n help=\"Start the God Code debug adapter (DAP) \"\n \"over stdio\")\n p_dap.set_defaults(func=cmd_dap)\n # --- end v5.0: dap commands ---\n\n # --- v5.0: interactive debugger ---\n p_debug = sub.add_parser(\"debug\",\n help=\"Debug a God Code scroll interactively\")\n p_debug.add_argument(\"file\", help=\"Path to the .god scroll\")\n p_debug.add_argument(\"--break\", \"-b\", dest=\"breaks\", action=\"append\",\n type=int, default=[], metavar=\"LINE\",\n help=\"Pause at LINE as well as on entry \"\n \"(repeatable)\")\n p_debug.set_defaults(func=cmd_debug)\n # --- end v5.0 ---\n\n return parser\n\n\ndef main(argv=None) -> int:\n \"\"\"Entry point. Returns 0 on success; raises SystemExit(code) on failure.\"\"\"\n args = build_parser().parse_args(argv)\n code = args.func(args)\n if code:\n raise SystemExit(code)\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","godcode/dap.py":"\"\"\"Debug Adapter Protocol server for God Code (v5.0).\n\nA minimal DAP implementation over stdio, hand-rolled on top of the stdlib.\nMessages are framed with ``Content-Length`` headers, exactly like\n:mod:`godcode.lsp`.\n\nLifecycle::\n\n godcode dap # start serving on stdin/stdout\n\nThe message loop runs on the main thread. ``launch`` builds an interpreter\nthe same way ``godcode run`` does, attaches a\n:class:`godcode.debugger.DebugSession`, and starts the scroll on a daemon\nworker thread. Pauses surface as ``stopped`` events; the worker thread\nblocks inside the session until a ``continue`` / ``next`` / ``stepIn`` /\n``stepOut`` request resumes it.\n\nProtocol notes:\n * All logging goes to stderr. stdout is the protocol channel. Nothing\n else may ever be written there (REVEAL output is forwarded as DAP\n ``output`` events instead).\n * Unknown commands answer with JSON-RPC error -32601 (\"Method not found\").\n * Malformed frames are skipped; the server keeps serving.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport io\nimport json\nimport os\nimport re\nimport sys\nimport threading\n\nfrom godcode.debugger import DebugSession\nfrom godcode.errors import GodCodeError\n\n# A handler that already sent its own response returns this, so the\n# dispatcher does not answer twice (used by launch and disconnect).\n_HANDLED = object()\n\n_IDENT_RE = re.compile(r\"[A-Za-z_][A-Za-z0-9_]*$\")\n\n_CAPABILITIES = {\n \"supportsConfigurationDoneRequest\": True,\n \"supportsEvaluateForHovers\": False,\n}\n\n\ndef _log(message: str) -> None:\n sys.stderr.write(f\"[godcode-dap] {message}\\n\")\n sys.stderr.flush()\n\n\nclass DebugAdapter:\n \"\"\"Hand-rolled DAP server over stdio.\"\"\"\n\n def __init__(self,\n stdin: io.BufferedReader | None = None,\n stdout: io.BufferedWriter | None = None) -> None:\n self.stdin = stdin or sys.stdin.buffer\n self.stdout = stdout or sys.stdout.buffer\n self._write_lock = threading.Lock()\n self._seq = 0\n self._session: DebugSession | None = None\n self._worker: threading.Thread | None = None\n self._pending_breakpoints: dict[str, set[int]] = {}\n # Variable references: id -> (\"frame_locals\", frame_id)\n # or (\"value\", python_value). Allocated from 1.\n self._var_refs: dict[int, tuple] = {}\n self._next_var_ref = 1\n self._handlers = {\n \"initialize\": self._on_initialize,\n \"launch\": self._on_launch,\n \"configurationDone\": self._on_configuration_done,\n \"setBreakpoints\": self._on_set_breakpoints,\n \"threads\": self._on_threads,\n \"stackTrace\": self._on_stack_trace,\n \"scopes\": self._on_scopes,\n \"variables\": self._on_variables,\n \"evaluate\": self._on_evaluate,\n \"continue\": self._on_continue,\n \"next\": self._on_next,\n \"stepIn\": self._on_step_in,\n \"stepOut\": self._on_step_out,\n \"disconnect\": self._on_disconnect,\n }\n\n # ------------------------------------------------------------ transport\n def _read_message(self) -> dict | None:\n \"\"\"Read one Content-Length framed message. None on clean EOF.\"\"\"\n headers: dict[str, str] = {}\n while True:\n line = self.stdin.readline()\n if not line:\n return None # EOF\n line = line.decode(\"latin-1\").strip()\n if not line:\n break\n if \":\" in line:\n name, _, value = line.partition(\":\")\n headers[name.strip().lower()] = value.strip()\n try:\n length = int(headers.get(\"content-length\", \"\"))\n except (TypeError, ValueError):\n _log(\"malformed frame: bad Content-Length; skipping\")\n return {}\n try:\n body = self._read_exact(length)\n except EOFError:\n _log(\"malformed frame: truncated body; skipping\")\n return {}\n try:\n return json.loads(body.decode(\"utf-8\"))\n except (UnicodeDecodeError, json.JSONDecodeError) as exc:\n _log(f\"malformed frame: {exc}; skipping\")\n return {}\n\n def _read_exact(self, length: int) -> bytes:\n body = b\"\"\n while len(body) < length:\n chunk = self.stdin.read(length - len(body))\n if not chunk:\n raise EOFError(\"truncated frame\")\n body += chunk\n return body\n\n def _next_seq(self) -> int:\n with self._write_lock:\n self._seq += 1\n return self._seq\n\n def _write(self, payload: dict) -> None:\n body = json.dumps(payload, separators=(\",\", \":\")).encode(\"utf-8\")\n frame = (f\"Content-Length: {len(body)}\\r\\n\\r\\n\".encode(\"ascii\")\n + body)\n with self._write_lock:\n self.stdout.write(frame)\n self.stdout.flush()\n\n def _send_response(self, request_seq, command: str,\n success: bool = True,\n body: dict | None = None,\n message: str = \"\") -> None:\n payload: dict = {\n \"seq\": self._next_seq(),\n \"type\": \"response\",\n \"request_seq\": request_seq,\n \"success\": success,\n \"command\": command,\n }\n if success:\n if body is not None:\n payload[\"body\"] = body\n elif message:\n payload[\"message\"] = message\n self._write(payload)\n\n def _send_event(self, event: str, body: dict | None = None) -> None:\n payload: dict = {\n \"seq\": self._next_seq(),\n \"type\": \"event\",\n \"event\": event,\n }\n if body is not None:\n payload[\"body\"] = body\n self._write(payload)\n\n def _send_jsonrpc_error(self, msg_id, code: int,\n message: str) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"id\": msg_id,\n \"error\": {\"code\": code, \"message\": message}})\n\n def _send_output(self, text: str, category: str = \"stdout\") -> None:\n if not text.endswith(\"\\n\"):\n text += \"\\n\"\n self._send_event(\"output\",\n {\"category\": category, \"output\": text})\n\n # ------------------------------------------------------------ main loop\n def serve(self) -> int:\n _log(\"the debug adapter opens (stdio)\")\n while True:\n message = self._read_message()\n if message is None:\n _log(\"stdin closed; ascending\")\n return 0\n if not message:\n continue # malformed frame: already logged, keep serving\n self._dispatch(message)\n\n def _dispatch(self, message: dict) -> None:\n command = message.get(\"command\") or message.get(\"method\")\n seq = message.get(\"seq\", message.get(\"id\"))\n if not command:\n _log(\"message with no command; ignoring\")\n return\n handler = self._handlers.get(command)\n if handler is None:\n _log(f\"unknown command: {command!r}\")\n if seq is not None:\n self._send_jsonrpc_error(seq, -32601,\n f\"Method not found: {command}\")\n return\n args = message.get(\"arguments\") or message.get(\"params\") or {}\n try:\n result = handler(seq, command, args)\n except Exception as exc: # never let a handler kill the server\n _log(f\"handler for {command} failed: {exc}\")\n if seq is not None:\n self._send_response(seq, command, success=False,\n message=str(exc))\n return\n if result is _HANDLED or seq is None:\n return\n self._send_response(seq, command, success=True, body=result)\n\n # ------------------------------------------------------ session helpers\n def _require_session(self) -> DebugSession:\n if self._session is None:\n raise RuntimeError(\"no program is launched\")\n return self._session\n\n def _frames_innermost_first(self) -> list:\n session = self._session\n if session is None:\n return []\n return list(reversed(session.frames))\n\n def _frame_by_id(self, frame_id: int):\n frames = self._frames_innermost_first()\n if 0 <= frame_id < len(frames):\n return frames[frame_id]\n return None\n\n def _alloc_var_ref(self, entry: tuple) -> int:\n ref = self._next_var_ref\n self._next_var_ref += 1\n self._var_refs[ref] = entry\n return ref\n\n @staticmethod\n def _children_of(value) -> list[tuple[str, object]]:\n if isinstance(value, list):\n return [(str(i), item) for i, item in enumerate(value)]\n if isinstance(value, dict):\n return [(str(key), item) for key, item in value.items()]\n return []\n\n def _variable(self, name: str, value) -> dict:\n session = self._require_session()\n ref = 0\n if isinstance(value, (list, dict)):\n ref = self._alloc_var_ref((\"value\", value))\n return {\n \"name\": str(name),\n \"value\": session.render_value(value),\n \"type\": session.type_name(value),\n \"variablesReference\": ref,\n }\n\n # -------------------------------------------------------------- handlers\n def _on_initialize(self, seq, command, args: dict): # noqa: ARG002\n _log(\"initialize received\")\n result = {\"capabilities\": dict(_CAPABILITIES)}\n # Respond first so the client sees a clean handshake ordering.\n self._send_response(seq, command, success=True, body=result)\n self._send_event(\"initialized\")\n return _HANDLED\n\n def _on_launch(self, seq, command, args: dict):\n if self._session is not None:\n raise RuntimeError(\"a program is already launched\")\n program = args.get(\"program\")\n if not program:\n raise RuntimeError(\"launch requires a 'program' path\")\n stop_on_entry = args.get(\"stopOnEntry\", True)\n _log(f\"launch: {program} (stopOnEntry={stop_on_entry})\")\n\n from godcode.cli import _make_interpreter\n\n interpreter = _make_interpreter(None)\n session = DebugSession()\n for path, lines in self._pending_breakpoints.items():\n for line in sorted(lines):\n session.add_breakpoint(path, line)\n self._pending_breakpoints.clear()\n\n original_emit = interpreter.emit\n\n def _emit(line: str, _orig=original_emit) -> None:\n _orig(line) # printed, as `godcode run` does\n self._send_output(str(line), category=\"stdout\")\n\n interpreter.emit = _emit\n session.on_pause = self._on_pause\n session.attach(interpreter)\n session.stop_on_entry = bool(stop_on_entry)\n self._session = session\n\n # Answer before the worker starts, so the client never sees a\n # stopped event ahead of the launch response.\n self._send_response(seq, command, success=True, body={})\n worker = threading.Thread(\n target=self._run_program,\n args=(session, str(program)),\n daemon=True,\n name=\"godcode-dap-worker\",\n )\n self._worker = worker\n worker.start()\n return _HANDLED\n\n def _run_program(self, session: DebugSession, program: str) -> None:\n try:\n session.run_file(program)\n except GodCodeError as err:\n _log(f\"program error: {err}\")\n self._send_output(str(err), category=\"stderr\")\n self._send_event(\"terminated\")\n return\n except Exception as err: # noqa: BLE001 - never die silently\n _log(f\"worker failed: {err}\")\n self._send_output(f\"{type(err).__name__}: {err}\",\n category=\"stderr\")\n self._send_event(\"terminated\")\n return\n _log(\"program finished\")\n self._send_event(\"terminated\")\n self._send_event(\"exited\", {\"exitCode\": 0})\n\n def _on_pause(self, pause_info: dict) -> None:\n reason = pause_info.get(\"reason\", \"pause\")\n line = pause_info.get(\"line\")\n source = pause_info.get(\"source\")\n _log(f\"paused: {reason} at {source}:{line}\")\n # The session blocks inside _pause until a request handler calls\n # session.resume(); this handler only announces the stop.\n self._send_event(\"stopped\", {\n \"reason\": reason,\n \"threadId\": 1,\n \"allThreadsStopped\": True,\n })\n\n def _on_configuration_done(self, seq, command, # noqa: ARG002\n args: dict): # noqa: ARG002\n _log(\"configuration done\")\n return {}\n\n def _on_set_breakpoints(self, seq, command, args: dict): # noqa: ARG002\n source = args.get(\"source\") or {}\n path = source.get(\"path\", \"\")\n lines: list[int] = []\n for bp in args.get(\"breakpoints\") or []:\n line = (bp or {}).get(\"line\")\n if isinstance(line, int):\n lines.append(line)\n if self._session is not None:\n self._session.clear_breakpoints(path)\n for line in lines:\n self._session.add_breakpoint(path, line)\n else:\n # Arrived before launch; applied when the session is created.\n self._pending_breakpoints[path] = set(lines)\n norm = DebugSession._norm(path) if path else \"\"\n _log(f\"breakpoints for {norm or path}: {lines}\")\n return {\"breakpoints\": [\n {\"verified\": True, \"line\": n,\n \"source\": {\"name\": os.path.basename(norm) if norm else \"\",\n \"path\": norm}}\n for n in lines\n ]}\n\n def _on_threads(self, seq, command, args: dict): # noqa: ARG002\n return {\"threads\": [{\"id\": 1, \"name\": \"creation\"}]}\n\n def _on_stack_trace(self, seq, command, args: dict): # noqa: ARG002\n out = []\n for i, frame in enumerate(self._frames_innermost_first()):\n src = frame.source or \"\"\n out.append({\n \"id\": i,\n \"name\": frame.name,\n \"line\": frame.line or 1,\n \"column\": 1,\n \"source\": {\n \"name\": os.path.basename(src) if src else \"scroll\",\n \"path\": src,\n },\n })\n return {\"stackFrames\": out, \"totalFrames\": len(out)}\n\n def _on_scopes(self, seq, command, args: dict): # noqa: ARG002\n frame_id = args.get(\"frameId\", 0)\n ref = self._alloc_var_ref((\"frame_locals\", frame_id))\n return {\"scopes\": [\n {\"name\": \"Locals\", \"variablesReference\": ref,\n \"expensive\": False}\n ]}\n\n def _on_variables(self, seq, command, args: dict): # noqa: ARG002\n entry = self._var_refs.get(args.get(\"variablesReference\", 0))\n pairs: list[tuple[str, object]] = []\n if entry is not None:\n if entry[0] == \"frame_locals\":\n frame = self._frame_by_id(entry[1])\n if frame is not None:\n pairs = self._require_session().frame_locals(frame)\n elif entry[0] == \"value\":\n pairs = self._children_of(entry[1])\n return {\"variables\": [self._variable(name, value)\n for name, value in pairs[:50]]}\n\n def _on_evaluate(self, seq, command, args: dict): # noqa: ARG002\n session = self._require_session()\n expr = str(args.get(\"expression\", \"\")).strip()\n frame = self._frame_by_id(args.get(\"frameId\", 0))\n name = expr if _IDENT_RE.match(expr) else None\n if name is not None:\n found, value = session.lookup(name, frame)\n if found:\n return {\n \"result\": session.render_value(value),\n \"type\": session.type_name(value),\n \"variablesReference\": 0,\n }\n return {\"result\": f\"no '{expr}' is bound here.\",\n \"variablesReference\": 0}\n\n def _on_continue(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"continue\")\n return {\"allThreadsContinued\": True}\n\n def _on_next(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"step_over\")\n return {\"allThreadsContinued\": True}\n\n def _on_step_in(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"step_in\")\n return {\"allThreadsContinued\": True}\n\n def _on_step_out(self, seq, command, args: dict): # noqa: ARG002\n self._require_session().resume(\"step_out\")\n return {\"allThreadsContinued\": True}\n\n def _on_disconnect(self, seq, command, args: dict): # noqa: ARG002\n self._send_response(seq, command, success=True, body={})\n _log(\"disconnect; ascending\")\n os._exit(0)\n\n\ndef serve() -> int:\n \"\"\"Entry point for ``godcode dap``.\"\"\"\n return DebugAdapter().serve()\n","godcode/debug_cli.py":"\"\"\"Interactive CLI driver for the God Code debugger.\n\nImplements ``godcode debug ``: the scroll runs under a\n:class:`godcode.debugger.DebugSession`, and every pause opens a small\ngdb-style console on stdin/stdout. The interpreter is built exactly the\nway ``godcode run`` builds it, so the debug run can never drift from a\nplain run.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom pathlib import Path\n\nPROMPT = \"(god) \"\n\n\nclass _QuitDebug(Exception):\n \"\"\"Raised to leave the debugger. Caught by cmd_debug.\"\"\"\n\n\nclass _PauseLoop:\n \"\"\"Answers ``DebugSession.on_pause`` with an interactive console.\n\n Runs on the interpreter's own thread: every command either answers\n inline (break, print, locals, stack, help) or ends the pause with\n ``session.resume(action)``. Quitting raises :class:`_QuitDebug` after\n releasing the session's resume event, because the session waits on\n that event even when ``on_pause`` raises.\n \"\"\"\n\n _RESUME_COMMANDS = {\n \"continue\": \"continue\",\n \"c\": \"continue\",\n \"run\": \"continue\",\n \"next\": \"step_over\",\n \"n\": \"step_over\",\n \"step\": \"step_in\",\n \"si\": \"step_in\",\n \"out\": \"step_out\",\n }\n\n def __init__(self, session) -> None:\n self.session = session\n self._last_resume = \"continue\"\n\n # ------------------------------------------------------------ entry point\n def handle(self, pause_info: dict) -> None:\n self._show_pause(pause_info)\n while True:\n try:\n raw = input(PROMPT)\n except EOFError:\n self._quit()\n except KeyboardInterrupt:\n print()\n self._quit()\n text = raw.strip()\n if not text:\n # gdb-style: an empty line repeats the last resume command.\n self._do_resume(self._last_resume)\n return\n if self._dispatch(text, pause_info):\n return\n\n # ---------------------------------------------------------------- display\n def _show_pause(self, pause_info: dict) -> None:\n reason = pause_info.get(\"reason\", \"step\")\n line = pause_info.get(\"line\")\n source = pause_info.get(\"source\") or \"\"\n name = Path(source).name if source else \"\"\n print(f\"paused at {name}:{line} ({reason})\")\n lines = self.session.source_lines(source) if source else []\n if isinstance(line, int) and 1 <= line <= len(lines):\n first = max(1, line - 1)\n last = min(len(lines), line + 1)\n for num in range(first, last + 1):\n marker = \"=>\" if num == line else \" \"\n print(f\"{marker} {num:>4} | {lines[num - 1]}\")\n\n # --------------------------------------------------------------- commands\n def _dispatch(self, text: str, pause_info: dict) -> bool:\n \"\"\"Run one command. Returns True when the pause is over.\"\"\"\n word, _, rest = text.partition(\" \")\n word = word.lower()\n arg = rest.strip()\n\n resume = self._RESUME_COMMANDS.get(word)\n if resume is not None:\n if arg:\n print(f\"'{word}' takes no arguments.\")\n return False\n self._do_resume(resume)\n return True\n\n if word in (\"break\", \"b\"):\n self._cmd_break(arg)\n elif word in (\"print\", \"p\"):\n self._cmd_print(arg)\n elif word == \"locals\":\n self._cmd_locals(pause_info)\n elif word in (\"stack\", \"bt\"):\n self._cmd_stack()\n elif word == \"help\":\n self._cmd_help()\n elif word in (\"quit\", \"q\"):\n self._quit()\n else:\n print(f\"Unknown command: '{word}'. Type 'help' for the list.\")\n return False\n\n def _do_resume(self, action: str) -> None:\n self._last_resume = action\n self.session.resume(action)\n\n def _quit(self) -> None:\n # Release the session's wait first: it blocks on the resume event\n # even when on_pause raises, and we must not hang it.\n self.session.resume(\"continue\")\n raise _QuitDebug()\n\n # -- break ---------------------------------------------------------\n def _cmd_break(self, arg: str) -> None:\n session = self.session\n source = session.current_source\n name = Path(source).name if source else \"\"\n if not arg:\n lines = sorted(session.breakpoints_for(source))\n if not lines:\n print(\"No breakpoints set.\")\n else:\n listed = \", \".join(f\"{name}:{num}\" for num in lines)\n print(f\"Breakpoints: {listed}\")\n return\n try:\n lineno = int(arg.split()[0])\n if lineno < 1:\n raise ValueError\n except ValueError:\n print(\"Usage: break . Give a line number, like 'break 3'.\")\n return\n session.add_breakpoint(source, lineno)\n print(f\"Breakpoint set at {name}:{lineno}.\")\n\n # -- print ---------------------------------------------------------\n def _cmd_print(self, arg: str) -> None:\n if not arg:\n print(\"Usage: print .\")\n return\n name = arg.split()[0]\n found, value = self.session.lookup(name)\n if not found:\n print(f\"'{name}' is not bound here.\")\n else:\n print(f\"{name} = {self.session.render_value(value)}\")\n\n # -- locals --------------------------------------------------------\n def _cmd_locals(self, pause_info: dict) -> None:\n session = self.session\n frame = pause_info.get(\"frame\")\n if frame is None and session.frames:\n frame = session.frames[-1]\n pairs = session.frame_locals(frame) if frame is not None else []\n if not pairs:\n print(\"No names are bound in this frame.\")\n return\n for name, value in pairs:\n rendered = session.render_value(value)\n typename = session.type_name(value)\n print(f\"{name} = {rendered} ({typename})\")\n\n # -- stack ---------------------------------------------------------\n def _cmd_stack(self) -> None:\n frames = self.session.frames\n if not frames:\n print(\"The stack is empty.\")\n return\n for i, frame in enumerate(reversed(frames)):\n marker = \" (current)\" if i == 0 else \"\"\n print(f\"#{i} {frame.name} at {self._frame_loc(frame)}{marker}\")\n\n @staticmethod\n def _frame_loc(frame) -> str:\n source = getattr(frame, \"source\", \"\") or \"\"\n name = Path(source).name if source else \"\"\n line = frame.line\n return f\"{name}:{line}\" if isinstance(line, int) else name\n\n # -- help ----------------------------------------------------------\n def _cmd_help(self) -> None:\n print(\"Commands:\")\n print(\" break (b) set a breakpoint; 'break' alone lists them\")\n print(\" continue (c), run resume the scroll\")\n print(\" next (n) step over the next statement\")\n print(\" step (si) step into the next call\")\n print(\" out step out of the current rite\")\n print(\" print (p) show the value of a bound name\")\n print(\" locals show every name visible in this frame\")\n print(\" stack (bt) show the call stack, innermost first\")\n print(\" help this list\")\n print(\" quit (q) leave the debugger; the scroll does not finish\")\n print(\"An empty line repeats the last resume command. Ctrl-D quits.\")\n\n\n# ---------------------------------------------------------------------------\n# debug\n# ---------------------------------------------------------------------------\ndef cmd_debug(args) -> int:\n from godcode.cli import _make_interpreter\n from godcode.debugger import DebugSession\n from godcode.errors import GodCodeError, format_error\n\n try:\n source = Path(args.file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n print(f\"godcode: cannot read '{args.file}': {exc.strerror or exc}\",\n file=sys.stderr)\n return 1\n\n interp = _make_interpreter(log_path=None)\n session = DebugSession()\n loop = _PauseLoop(session)\n session.on_pause = loop.handle\n session.stop_on_entry = True\n for lineno in getattr(args, \"breaks\", None) or []:\n session.add_breakpoint(args.file, lineno)\n session.attach(interp)\n try:\n session.run_file(args.file)\n except _QuitDebug:\n print(\"The debugger ascends. The scroll rests unfinished.\")\n return 0\n except GodCodeError as err:\n print(format_error(source, err), file=sys.stderr)\n return 1\n print(\"The scroll has finished its course. Amen.\")\n return 0\n","godcode/debugger.py":"\"\"\"Interactive debugging for God Code (v5.0).\n\nA :class:`DebugSession` plugs into the interpreter through the small hook\nsurface on ``Interpreter`` (``interpreter.debugger``):\n\n* ``before_stmt(stmt, env)`` — called before every statement executes.\n* ``enter_rite(rite, env)`` / ``exit_rite(rite)`` — around rite bodies.\n* ``enter_file(path)`` / ``exit_file()`` — around imported scrolls.\n\nWhen a pause condition is met (breakpoint, step, or stop-on-entry) the\nsession calls ``on_pause(pause_info)`` and blocks until the driver calls\n``resume(action)``. The CLI driver answers inline; the DAP driver answers\nfrom its message loop while the program runs on a worker thread.\n\nHook contract for driver authors::\n\n session = DebugSession()\n session.on_pause = my_handler # must call session.resume(action)\n session.add_breakpoint(\"/path/scroll.god\", 12)\n session.attach(interpreter) # sets interpreter.debugger\n session.stop_on_entry = True # pause at the first statement\n session.run_file(\"/path/scroll.god\") # lex, parse, run, manage sources\n\nResume actions: ``\"continue\"``, ``\"step_in\"``, ``\"step_over\"``,\n``\"step_out\"``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport threading\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nRESUME_ACTIONS = (\"continue\", \"step_in\", \"step_over\", \"step_out\")\n\n_PAUSE_BREAKPOINT = \"breakpoint\"\n_PAUSE_STEP = \"step\"\n_PAUSE_ENTRY = \"entry\"\n\n\n@dataclass\nclass DebugFrame:\n \"\"\"One frame of the paused call stack.\"\"\"\n\n name: str # rite name, or \"\" for the top level\n env: Any = None # godcode.environment.Environment\n stmt: Any = None # statement about to execute (or None)\n source: str = \"\"\n depth: int = 0\n\n @property\n def line(self) -> int | None:\n return getattr(self.stmt, \"line\", None)\n\n\nclass DebugSession:\n \"\"\"Drives a paused/stepped run of a God Code program.\"\"\"\n\n def __init__(self) -> None:\n self.breakpoints: dict[str, set[int]] = {}\n self.frames: list[DebugFrame] = []\n self.on_pause: Callable[[dict], None] | None = None\n self.stop_on_entry = False\n self.interpreter = None\n # stepping state\n self._step_mode = \"run\" # run | step_in | step_over | step_out\n self._step_depth = 0\n self._pause_once = False\n # sources\n self._source_stack: list[str] = []\n # pause machinery\n self._resume_event = threading.Event()\n self._resume_event.set()\n self.resume_action = \"continue\"\n self.pause_info: dict | None = None\n self.pause_count = 0\n self.finished = False\n self.error: Any = None\n\n # ------------------------------------------------------------ breakpoints\n\n @staticmethod\n def _norm(source: str) -> str:\n try:\n return str(Path(source).resolve())\n except OSError:\n return str(source)\n\n def add_breakpoint(self, source: str, line: int) -> None:\n self.breakpoints.setdefault(self._norm(source), set()).add(int(line))\n\n def remove_breakpoint(self, source: str, line: int) -> None:\n self.breakpoints.get(self._norm(source), set()).discard(int(line))\n\n def clear_breakpoints(self, source: str | None = None) -> None:\n if source is None:\n self.breakpoints.clear()\n else:\n self.breakpoints.pop(self._norm(source), None)\n\n def breakpoints_for(self, source: str) -> set[int]:\n return set(self.breakpoints.get(self._norm(source), set()))\n\n # ----------------------------------------------------------------- sources\n\n @property\n def current_source(self) -> str:\n return self._source_stack[-1] if self._source_stack else \"\"\n\n def push_source(self, source: str) -> None:\n self._source_stack.append(self._norm(source))\n\n def pop_source(self) -> None:\n if self._source_stack:\n self._source_stack.pop()\n\n # ------------------------------------------------------------------ attach\n\n def attach(self, interpreter) -> \"DebugSession\":\n \"\"\"Plug this session into an interpreter's hook surface.\"\"\"\n self.interpreter = interpreter\n interpreter.debugger = self\n return self\n\n def detach(self) -> None:\n if self.interpreter is not None:\n self.interpreter.debugger = None\n self.interpreter = None\n\n # --------------------------------------------------------------------- run\n\n def run_file(self, path: str | Path):\n \"\"\"Lex, parse, and run a scroll under this session.\n\n Returns the interpreter. Runtime errors propagate to the caller;\n ``self.error`` records them and ``self.finished`` is set either way.\n \"\"\"\n from godcode.tongues import parse_source\n\n if self.interpreter is None:\n raise RuntimeError(\"DebugSession has no interpreter. Call attach() first.\")\n resolved = str(Path(path).resolve())\n source = Path(path).read_text(encoding=\"utf-8\")\n program = parse_source(source)\n if self.stop_on_entry:\n self._pause_once = True\n self.push_source(resolved)\n try:\n self.interpreter.run(program, source_name=resolved)\n except Exception as err: # noqa: BLE001 - recorded for the driver\n self.error = err\n raise\n finally:\n self.pop_source()\n self.finished = True\n return self.interpreter\n\n # ---------------------------------------------------------- interpreter hooks\n\n @property\n def depth(self) -> int:\n return len(self.frames)\n\n def _current_frame(self, env) -> DebugFrame:\n if not self.frames:\n self.frames.append(\n DebugFrame(name=\"\", env=env,\n source=self.current_source, depth=1)\n )\n frame = self.frames[-1]\n frame.env = env\n return frame\n\n def before_stmt(self, stmt, env) -> None:\n frame = self._current_frame(env)\n frame.stmt = stmt\n reason = self._pause_reason(stmt)\n if reason is not None:\n self._pause(reason, stmt, frame)\n\n def enter_rite(self, rite, env) -> None:\n self.frames.append(\n DebugFrame(name=getattr(rite, \"name\", \"\"), env=env,\n source=self.current_source,\n depth=len(self.frames) + 1)\n )\n\n def exit_rite(self, rite) -> None:\n if self.frames:\n self.frames.pop()\n # step_out lands on the next statement back in the caller.\n if self._step_mode == \"step_out\" and len(self.frames) < self._step_depth:\n self._step_mode = \"step_over\"\n self._step_depth = len(self.frames)\n self._pause_once = True\n\n def enter_file(self, path: str) -> None:\n self.push_source(path)\n\n def exit_file(self) -> None:\n self.pop_source()\n\n # ------------------------------------------------------------------ pausing\n\n def _pause_reason(self, stmt) -> str | None:\n if self._pause_once:\n self._pause_once = False\n return _PAUSE_ENTRY if self.pause_count == 0 else _PAUSE_STEP\n if self._step_mode == \"step_in\":\n return _PAUSE_STEP\n if self._step_mode == \"step_over\" and len(self.frames) <= self._step_depth:\n return _PAUSE_STEP\n if self._step_mode == \"run\":\n line = getattr(stmt, \"line\", None)\n if line is not None and line in self.breakpoints.get(self.current_source, ()):\n return _PAUSE_BREAKPOINT\n return None\n\n def _pause(self, reason: str, stmt, frame: DebugFrame) -> None:\n self.pause_count += 1\n self.pause_info = {\n \"reason\": reason,\n \"stmt\": stmt,\n \"frame\": frame,\n \"frames\": list(self.frames),\n \"source\": self.current_source,\n \"line\": getattr(stmt, \"line\", None),\n \"pause_count\": self.pause_count,\n }\n self._resume_event.clear()\n try:\n if self.on_pause is not None:\n self.on_pause(self.pause_info)\n else: # no driver: behave like \"continue\" so runs never hang\n self.resume(\"continue\")\n finally:\n self._resume_event.wait()\n self._apply_resume()\n\n def resume(self, action: str) -> None:\n \"\"\"Answer a pause. Safe to call from any thread.\"\"\"\n if action not in RESUME_ACTIONS:\n raise ValueError(f\"unknown resume action: {action!r}\")\n self.resume_action = action\n self._resume_event.set()\n\n def _apply_resume(self) -> None:\n action = self.resume_action\n if action == \"continue\":\n self._step_mode = \"run\"\n elif action == \"step_in\":\n self._step_mode = \"step_in\"\n elif action == \"step_over\":\n self._step_mode = \"step_over\"\n self._step_depth = len(self.frames)\n elif action == \"step_out\":\n self._step_mode = \"step_out\"\n self._step_depth = len(self.frames)\n\n # --------------------------------------------------------------- inspection\n\n def render_value(self, value) -> str:\n if self.interpreter is not None:\n return self.interpreter.stringify(value)\n return str(value)\n\n def type_name(self, value) -> str:\n if self.interpreter is not None:\n return self.interpreter.type_name(value)\n return type(value).__name__\n\n def frame_locals(self, frame: DebugFrame) -> list[tuple[str, Any]]:\n \"\"\"(name, value) pairs visible in a frame, innermost first.\"\"\"\n if frame.env is None:\n return []\n try:\n return list(frame.env.items())\n except Exception: # noqa: BLE001 - defensive; never break a pause\n return []\n\n def lookup(self, name: str, frame: DebugFrame | None = None):\n \"\"\"Resolve a name in a frame's environment. Returns (found, value).\"\"\"\n frame = frame or (self.frames[-1] if self.frames else None)\n if frame is None or frame.env is None:\n return False, None\n env = frame.env\n while env is not None:\n bindings = getattr(env, \"_bindings\", {})\n if name in bindings:\n return True, bindings[name]\n env = getattr(env, \"parent\", None)\n return False, None\n\n def source_lines(self, source: str | None = None) -> list[str]:\n \"\"\"Source lines of a file for context display (1-based indexing).\"\"\"\n path = source or self.current_source\n try:\n return Path(path).read_text(encoding=\"utf-8\").splitlines()\n except OSError:\n return []\n","godcode/environment.py":"\"\"\"Lexically scoped environments for God Code.\n\nScope rule: names resolve outward through parent environments. An unbound\nname does not raise — it resolves to a Symbol of that name, because in God\nCode every unnamed thing is still a named spirit (this is what makes\n`DECLARE seeker AS worthy` / `IF seeker IS worthy` work with no prior\nbinding of `worthy`).\n\nDECLARE always defines in the *current* environment; it never rebinds an\nouter scope. Use set_existing() to reshape a name that must already exist.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Iterator\n\nfrom godcode.errors import GodRuntimeError, with_suggestion\nfrom godcode.values import Symbol\n\n\nclass Environment:\n def __init__(self, parent: \"Environment | None\" = None):\n self.parent = parent\n self._bindings: dict[str, object] = {}\n\n def define(self, name: str, value: object) -> None:\n \"\"\"Bind name in this environment, shadowing any outer binding.\"\"\"\n self._bindings[name] = value\n\n def get(self, name: str) -> object:\n \"\"\"Walk outward for name; return Symbol(name) if nowhere bound.\"\"\"\n env: Environment | None = self\n while env is not None:\n if name in env._bindings:\n return env._bindings[name]\n env = env.parent\n return Symbol(name)\n\n def is_bound(self, name: str) -> bool:\n \"\"\"True if name is bound in this environment or any ancestor.\"\"\"\n env: Environment | None = self\n while env is not None:\n if name in env._bindings:\n return True\n env = env.parent\n return False\n\n def set_existing(self, name: str, value: object) -> None:\n \"\"\"Reshape an already-bound name where it lives; error if unbound.\"\"\"\n env: Environment | None = self\n while env is not None:\n if name in env._bindings:\n env._bindings[name] = value\n return\n env = env.parent\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no '{name}' to reshape. It was never spoken into being.\",\n name,\n self.names(),\n )\n )\n\n def names(self) -> list[str]:\n \"\"\"All visible names, innermost scope first, without duplicates.\"\"\"\n seen: list[str] = []\n env: Environment | None = self\n while env is not None:\n for key in env._bindings:\n if key not in seen:\n seen.append(key)\n env = env.parent\n return seen\n\n def items(self) -> Iterator[tuple[str, object]]:\n \"\"\"(name, value) pairs for every visible name, innermost first.\"\"\"\n for name in self.names():\n yield name, self.get(name)\n","godcode/errors.py":"\"\"\"Error hierarchy for God Code v2.0.\n\nAll errors carry line (and where known, column) numbers so the faithful\ncan find where the heavens objected. Messages are divine-flavored but\ngenuinely helpful -- never mocking.\n\nControl-flow signals (ReturnSignal / AscendSignal) are plain Exceptions,\n*not* GodCodeError subclasses, so a broad ``except GodCodeError`` in the\ninterpreter can never accidentally swallow a return or an ascension.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport difflib\n\n\nclass GodCodeError(Exception):\n \"\"\"Base class for every God Code failure. ``line``/``col`` are 1-based.\"\"\"\n\n def __init__(self, msg: str, line: int | None = None, col: int | None = None):\n super().__init__(msg)\n self.msg = msg\n self.line = line\n self.col = col\n\n def __str__(self) -> str:\n if self.line is None or f\"line {self.line}\" in self.msg:\n return self.msg\n loc = f\" (line {self.line}\"\n if self.col is not None:\n loc += f\", col {self.col}\"\n return self.msg + loc + \")\"\n\n\nclass LexerError(GodCodeError):\n \"\"\"The source could not be turned into tokens.\"\"\"\n\n\nclass ParseError(GodCodeError):\n \"\"\"The tokens did not form a holy grammar.\"\"\"\n\n\nclass GodRuntimeError(GodCodeError):\n \"\"\"The creation failed while it was being brought to life.\n\n Named to avoid clashing with the builtin RuntimeError.\n \"\"\"\n\n\nclass SandboxViolation(GodCodeError):\n \"\"\"A power the sandbox withholds.\n\n Raised when a creation running under ``godcode.sandbox`` reaches for\n something its policy does not grant: a forbidden scroll, a denied\n rite (such as ASK when stdin is closed), a spent step budget, or an\n expired time grant. Carries a line number like every other\n GodCodeError, so the faithful can see exactly where the heavens\n objected.\n \"\"\"\n\n\nclass ReturnSignal(Exception):\n \"\"\"Carries a rite's return value up to the rite-call boundary.\"\"\"\n\n def __init__(self, value=None):\n super().__init__(value)\n self.value = value\n\n\nclass AscendSignal(Exception):\n \"\"\"Raised by ASCEND; ends the creation in peace.\"\"\"\n\n\nclass BreakSignal(Exception):\n \"\"\"Raised by BREAK; carries the loop's end up to the enclosing loop.\n\n Caught only by the interpreter's loop runners (_exec_for/_exec_while),\n so BREAK always releases the *innermost* loop. Never crosses a rite\n boundary: the parser binds every BREAK to a lexically enclosing loop,\n and _call_rite turns any stray signal into a plain error.\n \"\"\"\n\n\nclass ContinueSignal(Exception):\n \"\"\"Raised by CONTINUE; skips to the next turn of the enclosing loop.\n\n Same handling contract as BreakSignal: the innermost loop catches it,\n rite boundaries are never crossed.\n \"\"\"\n\n\ndef suggest_similar(name, candidates, *, n: int = 1, cutoff: float = 0.6):\n \"\"\"Return the closest candidate to *name*, or None when nothing is close.\n\n Matching is case-insensitive; the returned candidate keeps its own\n casing. Used so the heavens can answer a misspelled name with a\n gentle \\\"Did you mean ...?\\\" instead of a bare rejection.\n \"\"\"\n wanted = str(name).lower()\n lowered = {}\n for candidate in candidates:\n lowered.setdefault(str(candidate).lower(), str(candidate))\n if wanted in lowered:\n return None # an exact name needs no suggestion\n matches = difflib.get_close_matches(wanted, list(lowered), n=n, cutoff=cutoff)\n return lowered[matches[0]] if matches else None\n\n\ndef with_suggestion(message: str, name, candidates) -> str:\n \"\"\"Append a gentle \\\"Did you mean 'X'?\\\" to *message* when one fits.\"\"\"\n suggestion = suggest_similar(name, candidates)\n if suggestion is None:\n return message\n return f\"{message} Did you mean '{suggestion}'?\"\n\n\ndef format_error(source: str, err: GodCodeError) -> str:\n \"\"\"Render an error for a human: the message, then the offending line.\n\n The offending source line is shown with a gutter, and a caret marks the\n column when one is known. Quietly degrades to the bare message when the\n line or column cannot be shown.\n \"\"\"\n lines = [str(err)]\n line_no = getattr(err, \"line\", None)\n if isinstance(line_no, int) and line_no >= 1:\n src_lines = source.splitlines()\n if line_no <= len(src_lines):\n text = src_lines[line_no - 1]\n gutter = f\" {line_no} | \"\n lines.append(gutter + text)\n col = getattr(err, \"col\", None)\n if isinstance(col, int) and 1 <= col <= len(text) + 1:\n lines.append(\" \" * len(gutter) + \" \" * (col - 1) + \"^\")\n return \"\\n\".join(lines)\n\n\ndef format_call_trace(trace: list[dict]) -> list[str]:\n \"\"\"Render a rite call stack for humans, beneath the gentle error.\n\n One ``Called by`` line per call, oldest first, with\n ``(most recent call last)`` beneath them. An empty trace gives no lines:\n an error raised at the top level (no rite calls) shows no trace section.\n \"\"\"\n if not trace:\n return []\n lines: list[str] = []\n for frame in trace:\n rite = frame.get(\"rite\", \"\")\n line = frame.get(\"line\")\n if isinstance(line, int):\n lines.append(f\"Called by {rite} at line {line}\")\n else:\n lines.append(f\"Called by {rite}\")\n lines.append(\"(most recent call last)\")\n return lines\n","godcode/explain.py":"\"\"\"`godcode explain` -- say what a scroll does, without running it.\n\nStatic facts for humans and agents: the tongue, the rites and their\ndeclared intents, the names it declares, the lines it reveals, the\nseals it keeps, the verbs it summons, the questions it lays before the\nSpirit, the scrolls it brings in, and the powers it declares. Nothing\nexecutes; the walk is read-only over the parsed AST, so explaining a\nscroll is always safe.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport dataclasses\nfrom pathlib import Path\n\n\n# ---------------------------------------------------------------------------\n# walking\n# ---------------------------------------------------------------------------\ndef _iter_child(value):\n if dataclasses.is_dataclass(value) and not isinstance(value, type):\n yield from _iter_nodes(value)\n elif isinstance(value, (list, tuple)):\n for item in value:\n yield from _iter_child(item)\n\n\ndef _iter_nodes(node):\n \"\"\"Yield an AST node and every AST node nested inside it, at any depth.\n\n Statements may sit inside a creation block, an IF, a loop, a TRY, or\n a rite body; call expressions may sit inside any expression. The\n generic walk finds them all without enumerating every node kind.\n \"\"\"\n yield node\n if dataclasses.is_dataclass(node) and not isinstance(node, type):\n for field in dataclasses.fields(node):\n yield from _iter_child(getattr(node, field.name))\n\n\n# ---------------------------------------------------------------------------\n# facts\n# ---------------------------------------------------------------------------\ndef explain_facts(source: str, base_dir: str | Path | None) -> dict:\n \"\"\"Collect the static facts of a scroll.\n\n Raises the same GodCodeError ``parse_source`` raises on a broken\n scroll. ``base_dir`` resolves the manifest's relative paths, as in\n `godcode permissions`.\n \"\"\"\n from godcode.ast import (\n CallExpr,\n Declare,\n DeclareIntent,\n DefineRite,\n Import,\n Literal,\n Reveal,\n SealStmt,\n )\n from godcode.permissions import collect_manifest\n from godcode.tongues import _CODE_ALIASES, detect_tongue, parse_source, resolve\n\n program = parse_source(source)\n raw_tongue = detect_tongue(source)\n tongue_code = _CODE_ALIASES.get(raw_tongue, raw_tongue) if raw_tongue else \"en\"\n tongue_name = resolve(raw_tongue)[\"name\"]\n\n rites: list[dict] = []\n intents: list[dict] = []\n declarations: list[dict] = []\n reveals: list[dict] = []\n seals: list[dict] = []\n summons: list[dict] = []\n consults: list[dict] = []\n imports: list[dict] = []\n intent_by_rite: dict[str, str] = {}\n\n for node in _iter_nodes(program):\n if isinstance(node, DeclareIntent):\n intents.append(\n {\"rite\": node.rite, \"text\": node.text, \"line\": node.line}\n )\n intent_by_rite.setdefault(node.rite, node.text)\n elif isinstance(node, DefineRite):\n rites.append(\n {\n \"name\": node.name,\n \"params\": list(node.params),\n \"line\": node.line,\n \"intent\": intent_by_rite.get(node.name),\n }\n )\n elif isinstance(node, Declare):\n declarations.append({\"name\": node.name, \"line\": node.line})\n elif isinstance(node, Reveal):\n reveals.append({\"line\": node.line})\n elif isinstance(node, SealStmt):\n seals.append({\"line\": node.line, \"kind\": \"SEAL\"})\n elif isinstance(node, CallExpr):\n if node.callee == \"ANCHOR\":\n seals.append({\"line\": node.line, \"kind\": \"ANCHOR\"})\n elif node.callee == \"CONSULT\":\n consults.append({\"line\": node.line})\n elif node.callee == \"SUMMON\":\n verb = node.args[0] if node.args else None\n summons.append(\n {\n \"verb\": verb.value if isinstance(verb, Literal) else None,\n \"line\": node.line,\n }\n )\n elif isinstance(node, Import):\n imports.append({\"path\": node.path, \"line\": node.line})\n\n manifest = collect_manifest(program.statements, base_dir)\n\n # Intents may be declared after their rites; attach them now that\n # every DECLARE INTENT has been seen.\n for rite in rites:\n if rite[\"intent\"] is None:\n rite[\"intent\"] = intent_by_rite.get(rite[\"name\"])\n\n return {\n \"tongue\": {\"code\": tongue_code, \"name\": tongue_name},\n \"rites\": rites,\n \"intents\": intents,\n \"declarations\": declarations,\n \"permissions\": manifest.to_json(),\n \"reveals\": reveals,\n \"seals\": seals,\n \"summons\": summons,\n \"consults\": consults,\n \"imports\": imports,\n }\n\n\ndef explain_payload(file: str, ok: bool, diagnostics: list[dict],\n facts: dict | None = None) -> dict:\n \"\"\"The `godcode explain --json` envelope: the check/run envelope style.\"\"\"\n payload = {\n \"tool\": \"godcode\",\n \"command\": \"explain\",\n \"file\": file,\n \"ok\": ok,\n \"diagnostics\": diagnostics,\n }\n if facts:\n payload.update(facts)\n return payload\n\n\n# ---------------------------------------------------------------------------\n# human words\n# ---------------------------------------------------------------------------\ndef _count(n: int, one: str, many: str) -> str:\n return f\"{n} {one}\" if n == 1 else f\"{n} {many}\"\n\n\ndef human_summary(filename: str, facts: dict) -> str:\n \"\"\"The scroll in plain words, for `godcode explain` without --json.\"\"\"\n from godcode.permissions import PermissionManifest\n\n lines = [f\"The scroll {filename}, in plain words:\"]\n\n tongue = facts[\"tongue\"]\n if tongue[\"code\"] != \"en\":\n lines.append(f\"It speaks {tongue['name']}.\")\n\n rites = facts[\"rites\"]\n if not rites:\n lines.append(\"It defines no rites.\")\n elif len(rites) == 1:\n rite = rites[0]\n params = \", \".join(rite[\"params\"]) or \"no names\"\n lines.append(\n f\"It defines 1 rite: {rite['name']} (line {rite['line']}), \"\n f\"taking {_count(len(rite['params']), 'name', 'names')}\"\n + (f\" ({params}).\" if rite[\"params\"] else \".\")\n )\n if rite[\"intent\"]:\n lines.append(f' Its declared purpose: \"{rite[\"intent\"]}\".')\n else:\n lines.append(f\"It defines {_count(len(rites), 'rite', 'rites')}:\")\n for rite in rites:\n lines.append(\n f\" - {rite['name']} (line {rite['line']}), \"\n f\"taking {_count(len(rite['params']), 'name', 'names')}.\"\n )\n if rite[\"intent\"]:\n lines.append(f' Its declared purpose: \"{rite[\"intent\"]}\".')\n\n declarations = facts[\"declarations\"]\n if not declarations:\n lines.append(\"It declares no names.\")\n else:\n names = \", \".join(f\"{d['name']} (line {d['line']})\" for d in declarations)\n lines.append(f\"It declares {_count(len(declarations), 'name', 'names')}: {names}.\")\n\n reveals = facts[\"reveals\"]\n if not reveals:\n lines.append(\"It reveals nothing.\")\n else:\n at = \", \".join(f\"line {r['line']}\" for r in reveals)\n lines.append(f\"It reveals {_count(len(reveals), 'line', 'lines')}: {at}.\")\n\n seals = facts[\"seals\"]\n kept = [s for s in seals if s[\"kind\"] == \"SEAL\"]\n anchored = [s for s in seals if s[\"kind\"] == \"ANCHOR\"]\n if not seals:\n lines.append(\"It seals nothing.\")\n else:\n if kept:\n at = \", \".join(f\"line {s['line']}\" for s in kept)\n lines.append(f\"It seals {_count(len(kept), 'covenant', 'covenants')}: {at}.\")\n if anchored:\n at = \", \".join(f\"line {s['line']}\" for s in anchored)\n lines.append(f\"It anchors {_count(len(anchored), 'seal', 'seals')} on a chain: {at}.\")\n\n consults = facts[\"consults\"]\n if not consults:\n lines.append(\"It asks the Spirit nothing.\")\n else:\n at = \", \".join(f\"line {c['line']}\" for c in consults)\n lines.append(f\"It asks the Spirit {_count(len(consults), 'question', 'questions')}: {at}.\")\n\n summons = facts[\"summons\"]\n if not summons:\n lines.append(\"It summons nothing.\")\n else:\n verbs = \", \".join(\n f\"{s['verb'] or 'an unnamed verb'} (line {s['line']})\" for s in summons\n )\n lines.append(f\"It summons {_count(len(summons), 'verb', 'verbs')}: {verbs}.\")\n\n imports = facts[\"imports\"]\n if not imports:\n lines.append(\"It brings in nothing.\")\n else:\n paths = \", \".join(f\"{i['path']} (line {i['line']})\" for i in imports)\n lines.append(f\"It brings in {_count(len(imports), 'scroll', 'scrolls')}: {paths}.\")\n\n perms = facts[\"permissions\"]\n manifest = PermissionManifest()\n manifest.read_paths = list(perms.get(\"read\", []))\n manifest.write_paths = list(perms.get(\"write\", []))\n manifest.hosts = list(perms.get(\"network\", []))\n manifest.stdin = bool(perms.get(\"stdin\", False))\n manifest.summons = list(perms.get(\"summon\", []))\n described = manifest.describe()\n if not described:\n lines.append(\n \"It declares no permissions, so it touches nothing of the outer world.\"\n )\n else:\n lines.append(f\"It declares {_count(len(described), 'permission', 'permissions')}:\")\n for grant in described:\n lines.append(f\" - it {grant}\")\n\n return \"\\n\".join(lines)\n","godcode/interpreter.py":"\"\"\"Tree-walking interpreter for God Code v2.0.\n\nWalks the AST produced by godcode.parser, evaluating statements in\nlexically scoped environments. Divine-flavored messages on the surface,\nreal semantics underneath: lexical scoping, rite calls with RETURN,\na 100,000-iteration guard on WHILE, and line-numbered errors.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport random\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nfrom typing import Any, Callable, Optional\n\nfrom godcode.ast import (\n Anoint,\n Ascend,\n BinaryOp,\n Bless,\n Break,\n Breathe,\n CallExpr,\n Continue,\n CreationBlock,\n Declare,\n DeclareIntent,\n DeclarePermission,\n DefineRite,\n ExprStmt,\n ForLoop,\n Identifier,\n IfStmt,\n Import,\n Index,\n InterpolatedString,\n ListLiteral,\n Literal,\n Program,\n Prophesy,\n Reflect,\n Return,\n Reveal,\n SealStmt,\n Testify,\n TryStmt,\n UnaryOp,\n WhileLoop,\n)\nfrom godcode.environment import Environment\nfrom godcode.errors import (\n AscendSignal,\n BreakSignal,\n ContinueSignal,\n GodCodeError,\n GodRuntimeError,\n ReturnSignal,\n with_suggestion,\n)\nfrom godcode.tongues import parse_source\nfrom godcode import plugins\nfrom godcode import chain as chain_module\nfrom godcode.values import Contract, RiteFunction, Symbol\n\n_WHILE_ITERATION_CAP = 100_000\n\n\nclass Interpreter:\n \"\"\"Walks the God Code AST and brings it to life.\"\"\"\n\n def __init__(\n self,\n spirit=None,\n ledger=None,\n log_path: str | None = \"logs/godcode.log\",\n interactive: bool = False,\n chain_adapters: dict | None = None,\n ):\n self.spirit = spirit\n self.ledger = ledger\n self.log_path = log_path\n self.interactive = interactive\n self.output: list[str] = [] # every REVEAL line, in order\n self.emit: Callable[[str], None] = print # REVEAL output sink; override to capture\n self.last_value: Any = None # value of the last expression statement (embedding API)\n self.env = Environment() # root environment\n self.source_dir = Path.cwd() # for IMPORT resolution\n self._imported: set[str] = set() # resolved scroll paths already run\n self._import_stack: list[str] = [] # scrolls currently being run\n self._last_source: str = \"\"\n self._log_handle: Any = None\n # --- v5.2: runtime call stack ---\n # A lightweight list of {\"rite\": name, \"line\": call-site line},\n # pushed in _call_rite and popped as rites return (or raise). It\n # powers the \"Called by ...\" trace for uncaught errors and is\n # separate from the debugger's own frame list (which only exists\n # while a DebugSession is attached).\n # --- permission manifests ---\n # The scroll's declared powers, collected in run() before execution\n # and widened by union as imported scrolls declare their own. The\n # sandbox guard (when installed) enforces it against every rite.\n from godcode.permissions import PermissionManifest\n self.manifest: PermissionManifest = PermissionManifest()\n # --- end permission manifests ---\n self.call_stack: list[dict] = []\n # --- end v5.2 ---\n self._plugin_verbs: dict[str, Callable[..., Any]] = {} # namespaced verbs from plugins\n self._plugin_verb_info: dict[str, dict] = {} # name -> {\"plugin\", \"trusted\", \"func\"}\n self.loaded_plugins: list[str] = [] # plugin names whose register() ran cleanly\n # --- debugger hook (v5.0) ---\n # Set to a godcode.debugger.DebugSession to trace execution. None\n # keeps the fast path: _exec_block checks this once per statement.\n self.debugger = None\n # --- end debugger hook ---\n # --- v4.0: intent layer + chain adapters ---\n self.intents: dict[str, str] = {} # rite name -> declared intent text\n self.intent_checks: list[dict] = [] # per-invocation alignment records\n self.chain_adapters = (\n chain_adapters\n if chain_adapters is not None\n else chain_module.default_adapters()\n )\n # --- end v4.0 ---\n self._builtins: dict[str, Callable[..., Any]] = {\n \"LEN\": self._builtin_len,\n \"STR\": self._builtin_str,\n \"NUM\": self._builtin_num,\n \"TYPE\": self._builtin_type,\n \"RANDOM\": self._builtin_random,\n \"RANGE\": self._builtin_range,\n \"PUSH\": self._builtin_push,\n \"UPPER\": self._builtin_upper,\n \"LOWER\": self._builtin_lower,\n \"SPLIT\": self._builtin_split,\n \"JOIN\": self._builtin_join,\n \"ASK\": self._builtin_ask,\n \"BEHOLD\": self._builtin_behold,\n \"REVERSE\": self._builtin_reverse,\n \"SUMMON\": self._builtin_summon,\n \"ANCHOR\": self._builtin_anchor, # v4.0\n \"CONSULT\": self._builtin_consult, # v4.0\n }\n # Pillar 3 — plugins auto-load at startup (the same path `godcode run`\n # and the REPL take). GODCODE_NO_PLUGINS=1 disables this.\n if os.environ.get(plugins.DISABLE_ENV_VAR) != \"1\":\n self.loaded_plugins = plugins.load_plugins(self)\n # v5.1: the stdlib pillars register their own builtins here so the\n # interpreter core stays small. Each module's register() is idempotent.\n from godcode import stdlib_commons, stdlib_times, stdlib_vault, stdlib_hashes\n\n stdlib_vault.register(self)\n stdlib_times.register(self)\n stdlib_hashes.register(self)\n stdlib_commons.register(self)\n\n # ------------------------------------------------- plugin verb registry\n\n def register_plugin_verb(\n self,\n name: str,\n func: Callable[..., Any],\n *,\n plugin: str | None = None,\n ) -> str:\n \"\"\"Register a plugin verb callable from God Code via SUMMON.\n\n *name* is namespaced by convention (``\"clockwork.now\"``); *func* is a\n plain Python callable ``func(*args)`` — values are converted\n God Code <-> Python automatically (see godcode.plugins). The verb is\n marked ``trusted=True``: plugin code is trusted host code and SUMMON\n calls bypass sandbox policy by design; the marker lets a future\n sandbox pillar consult it.\n \"\"\"\n if not isinstance(name, str) or not name:\n raise ValueError(\"a plugin verb needs a non-empty string name\")\n if not callable(func):\n raise ValueError(f\"plugin verb '{name}' is not callable\")\n adapter = plugins.make_verb_adapter(name, func)\n self._builtins[name] = adapter # exact key — namespaced names keep their case\n self._plugin_verbs[name] = adapter\n self._plugin_verb_info[name] = {\"plugin\": plugin, \"trusted\": True, \"func\": func}\n return name\n\n @property\n def plugin_verb_info(self) -> dict[str, dict]:\n \"\"\"Read-only view of plugin verb metadata (name -> plugin/trusted/func).\"\"\"\n return dict(self._plugin_verb_info)\n\n # ------------------------------------------------------------------ run\n\n def run(self, program, source_name: str = \"\") -> None:\n \"\"\"Execute a parsed Program. ASCEND ends the run in peace.\"\"\"\n self._imported = set()\n self._import_stack = []\n self.call_stack = [] # fresh trace for every run\n if self._looks_like_file(source_name):\n self.source_dir = Path(source_name).resolve().parent\n # --- permission manifests ---\n # Gather the scroll's declared powers before anything runs, then\n # bind the guard so every rite is measured against them.\n from godcode.permissions import PermissionManifest, collect_manifest\n self.manifest = collect_manifest(\n self._statements_of(program), self.source_dir)\n self._bind_manifest_guard()\n # --- end permission manifests ---\n self._open_log()\n try:\n self._log(f\"SESSION BEGIN {source_name} {self._now()}\")\n try:\n self._exec_block(self._statements_of(program), self.env)\n except AscendSignal:\n message = \"🕊 Creation ascended in peace.\"\n print(message)\n self._log(\"ASCEND :: the creation ascended in peace\")\n self._log(f\"SESSION END {source_name}\")\n finally:\n self._close_log()\n\n def run_source(self, source: str, source_name: str = \"\") -> None:\n \"\"\"Lex, parse, and run God Code source text.\"\"\"\n self._last_source = source\n program = parse_source(source)\n self.run(program, source_name=source_name)\n\n @staticmethod\n def _statements_of(program):\n statements = getattr(program, \"statements\", None)\n if statements is None:\n raise GodRuntimeError(\"What was given to run is not a creation.\")\n return statements\n\n @staticmethod\n def _looks_like_file(source_name: str) -> bool:\n try:\n return Path(source_name).is_file()\n except (OSError, ValueError):\n return False\n\n # --- permission manifests ---\n\n def _bind_manifest_guard(self) -> None:\n \"\"\"Install the guard under the open host policy when a manifest\n is declared and no guard is installed yet (the --sandbox path\n installs its own strict guard, which then also sees the manifest).\n \"\"\"\n if not self.manifest:\n return\n if getattr(self, \"_sandbox_guard\", None) is not None:\n return\n from godcode.sandbox import SandboxPolicy, apply_policy\n apply_policy(self, SandboxPolicy.open())\n\n # --- end permission manifests ---\n\n # ------------------------------------------------------------- statements\n\n def _exec_block(self, statements: list, env: Environment) -> None:\n for stmt in statements:\n if self.debugger is not None:\n self.debugger.before_stmt(stmt, env)\n self._log_statement(stmt)\n try:\n self._exec_stmt(stmt, env)\n except (ReturnSignal, AscendSignal, BreakSignal, ContinueSignal):\n raise # control-flow signals pass through untouched\n except GodCodeError as err:\n self._attach_line(err, getattr(stmt, \"line\", None))\n # --- v5.2: snapshot the call stack for uncaught-error\n # traces. This innermost handler fires before any _call_rite\n # finally unwinds, so the stack is still whole. First sight\n # wins: an error re-raised from a CATCH keeps the stack of\n # where it first rose.\n if getattr(err, \"call_trace\", None) is None:\n err.call_trace = self.call_trace()\n # --- end v5.2 ---\n self._log(f\"ERROR :: line {getattr(err, 'line', '?')} :: {err}\")\n raise\n\n @staticmethod\n def _attach_line(err: GodCodeError, line) -> None:\n try:\n if getattr(err, \"line\", None) is None and line is not None:\n err.line = line\n except (AttributeError, TypeError):\n pass\n\n def _exec_stmt(self, stmt, env: Environment) -> None:\n if isinstance(stmt, CreationBlock):\n self._exec_block(stmt.statements, env)\n elif isinstance(stmt, Declare):\n env.define(stmt.name, self._eval_expr(stmt.value, env))\n elif isinstance(stmt, DeclareIntent):\n self._exec_declare_intent(stmt)\n elif isinstance(stmt, DeclarePermission):\n pass # the manifest was gathered before the run; nothing to do\n elif isinstance(stmt, Breathe):\n self._exec_breathe(stmt, env)\n elif isinstance(stmt, Reveal):\n line = self.stringify(self._eval_expr(stmt.expr, env))\n self.emit(line)\n self.output.append(line)\n elif isinstance(stmt, Prophesy):\n self._exec_prophesy(stmt)\n elif isinstance(stmt, Ascend):\n raise AscendSignal()\n elif isinstance(stmt, Reflect):\n self._exec_reflect(env)\n elif isinstance(stmt, Bless):\n self._exec_consecrate(stmt, env, kind=\"bless\")\n elif isinstance(stmt, Anoint):\n self._exec_consecrate(stmt, env, kind=\"anoint\")\n elif isinstance(stmt, SealStmt):\n self._exec_seal(stmt, env)\n elif isinstance(stmt, Testify):\n self._exec_testify(stmt, env)\n elif isinstance(stmt, IfStmt):\n branch = stmt.then_body if self._truthy(self._eval_expr(stmt.cond, env)) else stmt.else_body\n self._exec_block(branch, env)\n elif isinstance(stmt, ForLoop):\n self._exec_for(stmt, env)\n elif isinstance(stmt, WhileLoop):\n self._exec_while(stmt, env)\n elif isinstance(stmt, Break):\n raise BreakSignal()\n elif isinstance(stmt, Continue):\n raise ContinueSignal()\n elif isinstance(stmt, TryStmt):\n self._exec_try(stmt, env)\n elif isinstance(stmt, DefineRite):\n env.define(stmt.name, RiteFunction(stmt.name, stmt.params, stmt.body, env))\n elif isinstance(stmt, Return):\n raise ReturnSignal(self._eval_expr(stmt.expr, env) if stmt.expr is not None else None)\n elif isinstance(stmt, Import):\n self._exec_import(stmt, env)\n elif isinstance(stmt, ExprStmt):\n # The value is kept for the embedding API (RunResult.return_value).\n self.last_value = self._eval_expr(stmt.expr, env)\n else:\n raise GodRuntimeError(\n f\"The heavens do not recognize this utterance: {type(stmt).__name__}.\",\n getattr(stmt, \"line\", None),\n )\n\n # ------------------------------------------------------- statement helpers\n\n def _exec_breathe(self, stmt: Breathe, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n if not env.is_bound(stmt.name):\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no '{stmt.name}' to breathe into. \"\n \"It was never spoken into being.\",\n stmt.name,\n env.names(),\n ),\n line,\n )\n target = env.get(stmt.name)\n if isinstance(target, Contract):\n target.alive = True\n print(f\"[BREATHE] Life breathed into {stmt.name} 🕊\")\n\n def _exec_prophesy(self, stmt: Prophesy) -> None:\n text = stmt.text or \"\"\n if self.spirit is None:\n print(f\"[PROPHESY] The Spirit is silent. No oracle is bound. ({text!r})\")\n return\n payload = text if text else self._last_source\n utterance = self.spirit.prophesy(payload)\n print(utterance)\n\n def _exec_reflect(self, env: Environment) -> dict:\n table = {name: self.stringify(value) for name, value in env.items()}\n for name, rendered in table.items():\n print(f\"{name} = {rendered}\")\n return table\n\n def _exec_consecrate(self, stmt, env: Environment, kind: str) -> None:\n line = getattr(stmt, \"line\", None)\n name = stmt.name\n verb = \"bless\" if kind == \"bless\" else \"anoint\"\n if not env.is_bound(name):\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no '{name}' to {verb}. It was never spoken into being.\",\n name,\n env.names(),\n ),\n line,\n )\n target = env.get(name)\n if isinstance(target, Contract):\n if kind == \"bless\":\n target.blessed = True\n else:\n target.anointed = True\n mark = \"✨\" if kind == \"bless\" else \"🕊\"\n print(f\"[{kind.upper()}] {name} is {verb}ed {mark}\")\n\n def _exec_seal(self, stmt: SealStmt, env: Environment) -> None:\n value = self._eval_expr(stmt.expr, env)\n record: dict[str, Any] = {\n \"sealed\": self.stringify(value),\n \"type\": self.type_name(value),\n \"by\": \"godcode\",\n }\n if isinstance(value, Contract):\n record.update(\n {\n \"name\": value.name,\n \"alive\": value.alive,\n \"blessed\": value.blessed,\n \"anointed\": value.anointed,\n }\n )\n if self.ledger is None:\n print(\"[SEAL] ⚠ No covenant ledger is bound. The seal is spoken but not recorded.\")\n self._log(\"SEAL :: no ledger bound; seal spoken but not recorded\")\n return\n block = self.ledger.seal(record)\n digest = str(block.get(\"hash\", \"\"))[:8]\n print(f\"[SEAL] Covenant sealed · block {block.get('index')} · {digest} 🔒\")\n self._log(f\"SEAL :: block {block.get('index')} recorded\")\n\n def _exec_testify(self, stmt: Testify, env: Environment) -> None:\n if self._truthy(self._eval_expr(stmt.expr, env)):\n print(\"[TESTIFY] It is true. ✝\")\n else:\n raise GodRuntimeError(\n \"The testimony has failed. What was spoken does not hold true.\",\n getattr(stmt, \"line\", None),\n )\n\n # ------------------------------------------------- v4.0: intent layer\n\n def _exec_declare_intent(self, stmt: DeclareIntent) -> None:\n \"\"\"Register a natural-language intent on a named rite.\"\"\"\n self.intents[stmt.rite] = stmt.text\n if self.spirit is not None:\n self.spirit.declare_intent(stmt.rite, stmt.text)\n print(f'[INTENT] {stmt.rite} now carries the intent: \"{stmt.text}\" 🕊')\n self._log(f\"INTENT DECLARE :: {stmt.rite}\")\n\n def _discern_intent(self, rite: RiteFunction, declared: str) -> None:\n \"\"\"Discern a rite's actual intent and counsel on divergence.\n\n Classifies the rite's own words with the Spirit Engine and\n compares against the declared intent. A gentle [INTENT] notice\n when they align, a [WARNING] when they drift. The run is never\n failed over divergence: the Spirit counsels, it does not condemn.\n \"\"\"\n from godcode.cli import CanonicalFormatter # lazy: cli imports us lazily\n\n body_text = CanonicalFormatter().format(Program(statements=rite.body))\n discerned = self.spirit.classify(body_text)\n aligned = self.spirit.intents_aligned(declared, discerned)\n self.intent_checks.append(\n {\n \"rite\": rite.name,\n \"declared\": declared,\n \"discerned\": discerned[\"intent\"],\n \"confidence\": discerned[\"confidence\"],\n \"aligned\": aligned,\n }\n )\n if aligned:\n print(f'[INTENT] {rite.name} walks in its declared intent: \"{declared}\" 🕊')\n else:\n print(\n f'[WARNING] {rite.name} drifts from its declared intent. '\n f'Declared: \"{declared}\". '\n f'Discerned: \"{discerned[\"intent\"]}\". '\n \"The Spirit counsels; it does not condemn.\"\n )\n self._log(f\"INTENT CHECK :: {rite.name} aligned={aligned}\")\n\n def _exec_for(self, stmt: ForLoop, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n iterable = self._eval_expr(stmt.iterable, env)\n if isinstance(iterable, Symbol):\n raise GodRuntimeError(\n f\"FOR needs a list or a word to walk through, not the bare spirit '{iterable}'.\",\n line,\n )\n if isinstance(iterable, str):\n items = list(iterable)\n elif isinstance(iterable, list):\n items = list(iterable)\n else:\n raise GodRuntimeError(\n f\"FOR cannot walk through {self.type_name(iterable)}. Only lists and words.\",\n line,\n )\n child = Environment(parent=env) # one child env for the whole loop\n for item in items:\n child.define(stmt.var, item)\n try:\n self._exec_block(stmt.body, child)\n except ContinueSignal:\n continue # next turn of this loop\n except BreakSignal:\n break # the loop is released at once\n # A BreakSignal is caught only here, so in nested loops it releases\n # the innermost loop alone.\n\n def _exec_while(self, stmt: WhileLoop, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n count = 0\n # The body runs in the current environment so DECLARE can rebind the\n # names the condition watches (there is no separate assignment rite).\n while self._truthy(self._eval_expr(stmt.cond, env)):\n count += 1\n if count > _WHILE_ITERATION_CAP:\n raise GodRuntimeError(\n \"The cycle is endless. 100,000 turns and still no rest. \"\n \"The loop is released.\",\n line,\n )\n try:\n self._exec_block(stmt.body, env)\n except ContinueSignal:\n continue # the condition is weighed again for the next turn\n except BreakSignal:\n break # the cycle ends at once\n\n def _exec_try(self, stmt: TryStmt, env: Environment) -> None:\n # Only GodRuntimeError is caught: parse/lexer errors fail before a\n # run ever starts, and ReturnSignal / AscendSignal are plain\n # Exceptions (not GodCodeError subclasses), so a RETURN inside TRY\n # still returns from its rite and ASCEND still ends the run in peace.\n # Errors raised inside the CATCH body are outside this try, so they\n # propagate outward normally; nested TRYs handle their own errors.\n try:\n self._exec_block(stmt.try_body, env)\n except GodRuntimeError as err:\n # Bind the plain message (err.msg, without the location suffix\n # str(err) would append) so the CATCH can speak of it.\n env.define(stmt.error_name, err.msg)\n self._exec_block(stmt.catch_body, env)\n\n def _exec_import(self, stmt: Import, env: Environment) -> None:\n line = getattr(stmt, \"line\", None)\n path = self._resolve_import(stmt.path, line)\n key = str(path)\n if key in self._imported:\n return # already breathed in; skip\n if key in self._import_stack:\n raise GodRuntimeError(\n f\"The scroll '{stmt.path}' calls upon itself. A circle with no end.\",\n line,\n )\n self._imported.add(key)\n self._import_stack.append(key)\n previous_dir = self.source_dir\n previous_source = self._last_source\n self.source_dir = path.parent\n if self.debugger is not None:\n self.debugger.enter_file(str(path))\n try:\n source = path.read_text(encoding=\"utf-8\")\n self._last_source = source\n program = parse_source(source)\n self._log(f\"IMPORT :: {path}\")\n # Permission manifests compose by union: an imported scroll may\n # grant powers the importing scroll did not declare.\n from godcode.permissions import collect_manifest\n self.manifest = self.manifest.merge(\n collect_manifest(self._statements_of(program), self.source_dir)\n )\n self._bind_manifest_guard()\n self._exec_block(self._statements_of(program), env)\n finally:\n if self.debugger is not None:\n self.debugger.exit_file()\n self._import_stack.pop()\n self.source_dir = previous_dir\n self._last_source = previous_source\n\n def _resolve_import(self, import_path: str, line) -> Path:\n raw = Path(import_path)\n scrolls_dir = Path(__file__).parent / \"scrolls\"\n candidates = [\n self.source_dir / raw,\n Path.cwd() / raw,\n scrolls_dir / raw,\n ]\n if not raw.suffix:\n candidates.extend(\n [\n self.source_dir / f\"{import_path}.god\",\n Path.cwd() / f\"{import_path}.god\",\n scrolls_dir / f\"{import_path}.god\",\n ]\n )\n for candidate in candidates:\n try:\n if candidate.is_file():\n return candidate.resolve()\n except OSError:\n continue\n # --- v3: scroll registry --- installed registry scrolls\n # (project-local .godcode/scrolls, then user-global ~/.godcode/scrolls)\n # resolve bare names via their manifest entry file. Stdlib keeps its\n # precedence above, so stdlib behavior is unchanged.\n installed = self._resolve_installed_scroll(import_path)\n if installed is not None:\n return installed\n # --- end v3: scroll registry ---\n raise GodRuntimeError(\n f\"The scroll '{import_path}' could not be found. Not beside the \"\n \"creation, not in this place, not among the scrolls.\",\n line,\n )\n\n def _resolve_installed_scroll(self, import_path: str) -> Path | None:\n \"\"\"Resolve a bare scroll name against installed registry scrolls.\"\"\"\n if \"/\" in import_path or \"\\\\\" in import_path:\n return None # only bare names; never paths\n name = import_path[:-4] if import_path.endswith(\".god\") else import_path\n try:\n from godcode.registry import ScrollRegistry\n except ImportError:\n return None\n try:\n return ScrollRegistry().resolve_entry(name)\n except Exception:\n return None\n\n # ------------------------------------------------------------- expressions\n\n def _eval_expr(self, expr, env: Environment):\n line = getattr(expr, \"line\", None)\n if isinstance(expr, Literal):\n return expr.value\n if isinstance(expr, InterpolatedString):\n return \"\".join(\n part if isinstance(part, str)\n else self.stringify(self._eval_expr(part, env))\n for part in expr.parts\n )\n if isinstance(expr, Identifier):\n return env.get(expr.name)\n if isinstance(expr, ListLiteral):\n return [self._eval_expr(item, env) for item in expr.items]\n if isinstance(expr, Index):\n return self._eval_index(expr, env)\n if isinstance(expr, UnaryOp):\n return self._eval_unary(expr, env)\n if isinstance(expr, BinaryOp):\n return self._eval_binary(expr, env)\n if isinstance(expr, CallExpr):\n args = [self._eval_expr(arg, env) for arg in expr.args]\n return self._call(expr.callee, args, env, line)\n raise GodRuntimeError(\n f\"The heavens do not recognize this expression: {type(expr).__name__}.\",\n line,\n )\n\n def _eval_index(self, expr: Index, env: Environment):\n line = getattr(expr, \"line\", None)\n obj = self._eval_expr(expr.obj, env)\n index = self._eval_expr(expr.index, env)\n # --- v4.0: maps are indexed by word ---\n if isinstance(obj, dict):\n if not isinstance(index, str):\n raise GodRuntimeError(\n f\"Only words may point into a map. Not {self.type_name(index)}.\",\n line,\n )\n key = str(index)\n if key not in obj:\n known = \", \".join(obj) or \"it holds nothing\"\n raise GodRuntimeError(\n with_suggestion(\n f\"The map holds no '{key}'. Its keys are: {known}.\",\n key,\n list(obj),\n ),\n line,\n )\n return obj[key]\n # --- end v4.0 ---\n if not self._is_int(index):\n raise GodRuntimeError(\n f\"Only whole numbers may point into {self.type_name(obj)}. Not {self.type_name(index)}.\",\n line,\n )\n if isinstance(obj, Symbol):\n raise GodRuntimeError(\n f\"Cannot point into the bare spirit '{obj}'. Bind it to a list or word first.\",\n line,\n )\n if isinstance(obj, (list, str)):\n try:\n return obj[index]\n except IndexError:\n raise GodRuntimeError(\n f\"Index {index} reaches beyond what is there \"\n f\"(it holds {len(obj)}).\",\n line,\n ) from None\n raise GodRuntimeError(\n f\"Cannot point into {self.type_name(obj)}. Only lists and words may be indexed.\",\n line,\n )\n\n def _eval_unary(self, expr: UnaryOp, env: Environment):\n line = getattr(expr, \"line\", None)\n operand = self._eval_expr(expr.operand, env)\n if expr.op == \"not\":\n return not self._truthy(operand)\n if expr.op == \"-\":\n if self._is_number(operand):\n return -operand\n raise GodRuntimeError(\n f\"Cannot negate {self.type_name(operand)}. Only numbers know the void's mirror.\",\n line,\n )\n raise GodRuntimeError(f\"Unknown sign '{expr.op}'.\", line)\n\n def _eval_binary(self, expr: BinaryOp, env: Environment):\n line = getattr(expr, \"line\", None)\n left = self._eval_expr(expr.left, env)\n right = self._eval_expr(expr.right, env)\n op = expr.op\n if op == \"==\":\n return self._equals(left, right)\n if op == \"!=\":\n return not self._equals(left, right)\n if op in (\"<\", \">\", \"<=\", \">=\"):\n return self._compare(op, left, right, line)\n if op == \"+\":\n return self._add(left, right, line)\n if op in (\"-\", \"*\", \"/\", \"%\"):\n return self._arithmetic(op, left, right, line)\n if op == \"and\":\n return left if not self._truthy(left) else right\n if op == \"or\":\n return left if self._truthy(left) else right\n raise GodRuntimeError(f\"Unknown joining '{op}'.\", line)\n\n # ------------------------------------------------------- value operations\n\n @staticmethod\n def _is_int(value) -> bool:\n return isinstance(value, int) and not isinstance(value, bool)\n\n @classmethod\n def _is_number(cls, value) -> bool:\n return isinstance(value, (int, float)) and not isinstance(value, bool)\n\n def _equals(self, left, right) -> bool:\n # Contract vs Contract: by name. Symbol vs str: by text (str subclass\n # equality already does this). Numbers: cross-type. Lists: elementwise.\n if isinstance(left, Contract) or isinstance(right, Contract):\n return (\n isinstance(left, Contract)\n and isinstance(right, Contract)\n and left.name == right.name\n )\n try:\n return bool(left == right)\n except Exception: # pragma: no cover - defensive\n return False\n\n def _compare(self, op: str, left, right, line) -> bool:\n if self._is_number(left) and self._is_number(right):\n if op == \"<\":\n return left < right\n if op == \">\":\n return left > right\n if op == \"<=\":\n return left <= right\n return left >= right\n raise GodRuntimeError(\n f\"Cannot weigh {self.type_name(left)} against {self.type_name(right)}. \"\n \"Only numbers may be measured.\",\n line,\n )\n\n def _add(self, left, right, line):\n if self._is_number(left) and self._is_number(right):\n return left + right\n if isinstance(left, str) and isinstance(right, str):\n return str(left) + str(right) # plain str, even for Symbols\n if isinstance(left, list) and isinstance(right, list):\n return left + right\n raise GodRuntimeError(\n f\"Cannot join {self.type_name(left)} and {self.type_name(right)}. \"\n \"They are of different kingdoms.\",\n line,\n )\n\n def _arithmetic(self, op: str, left, right, line):\n if op == \"%\":\n if not (self._is_int(left) and self._is_int(right)):\n raise GodRuntimeError(\n f\"The remainder rite needs whole numbers, not \"\n f\"{self.type_name(left)} and {self.type_name(right)}.\",\n line,\n )\n elif not (self._is_number(left) and self._is_number(right)):\n raise GodRuntimeError(\n f\"Cannot reckon {self.type_name(left)} and {self.type_name(right)}. \"\n \"Only numbers may be reckoned.\",\n line,\n )\n if op in (\"/\", \"%\") and right == 0:\n raise GodRuntimeError(\n \"Division by nothing is not permitted. Even the heavens \"\n \"cannot split the void.\",\n line,\n )\n if op == \"-\":\n return left - right\n if op == \"*\":\n return left * right\n if op == \"/\":\n return left / right # always float, as the waters divide\n return left % right\n\n @staticmethod\n def _truthy(value) -> bool:\n # False / None / 0 / \"\" / [] / {} are empty; Symbols are always truthy.\n if value is None:\n return False\n if isinstance(value, bool):\n return value\n if isinstance(value, Symbol):\n return True\n if isinstance(value, (int, float)):\n return value != 0\n if isinstance(value, str):\n return len(value) > 0\n if isinstance(value, (list, dict)):\n return len(value) > 0\n return True # Contracts, rites, and all other living things\n\n # ----------------------------------------------------------------- rites\n\n def _call(self, name: str, args: list, env: Environment, line):\n if name == \"contract\":\n if len(args) == 1 and isinstance(args[0], (str, Symbol)):\n return Contract(str(args[0]))\n raise GodRuntimeError(\n \"The contract rite needs exactly one name. A single word to seal.\",\n line,\n )\n target = env.get(name) if env.is_bound(name) else None\n if isinstance(target, RiteFunction):\n return self._call_rite(target, args, line)\n # Exact match first so namespaced plugin verbs (\"clockwork.now\") keep\n # their case; core verbs still resolve case-insensitively via UPPER.\n builtin = self._builtins.get(name)\n if builtin is None:\n builtin = self._builtins.get(name.upper())\n if builtin is not None:\n return builtin(args, line)\n if target is not None:\n raise GodRuntimeError(\n f\"'{name}' is {self.type_name(target)}, not a rite. It cannot be invoked.\",\n line,\n )\n rite_names = [\n rite_name\n for rite_name in env.names()\n if isinstance(env.get(rite_name), RiteFunction)\n ]\n raise GodRuntimeError(\n with_suggestion(\n f\"There is no rite named '{name}'. The heavens do not know it.\",\n name,\n rite_names + list(self._builtins),\n ),\n line,\n )\n\n def _call_rite(self, rite: RiteFunction, args: list, line):\n if len(args) != len(rite.params):\n want, got = len(rite.params), len(args)\n raise GodRuntimeError(\n f\"Rite '{rite.name}' asks for {want} offering{'s' if want != 1 else ''}, \"\n f\"but {got} {'was' if got == 1 else 'were'} brought.\",\n line,\n )\n # --- v4.0: intent layer — discern the rite's actual intent when it\n # carries a declared one. Never fails the run; counsel, don't punish.\n declared = self.intents.get(rite.name)\n if declared is not None and self.spirit is not None:\n self._discern_intent(rite, declared)\n # --- end v4.0 ---\n call_env = Environment(parent=rite.closure_env)\n for param, value in zip(rite.params, args):\n call_env.define(param, value)\n rendered = \", \".join(self.stringify(a) for a in args)\n self._log(f\"RITE CALL :: {rite.name}({rendered})\")\n # --- v5.2: runtime call stack for uncaught-error traces ---\n self.call_stack.append({\"rite\": rite.name, \"line\": line})\n # --- end v5.2 ---\n if self.debugger is not None:\n self.debugger.enter_rite(rite, call_env)\n try:\n try:\n self._exec_block(rite.body, call_env)\n except ReturnSignal as ret:\n return ret.value\n except (BreakSignal, ContinueSignal) as sig:\n # The parser binds every BREAK/CONTINUE to a lexically\n # enclosing loop, so this is unreachable from parsed source.\n # Programmatic ASTs reach it: loop signals never cross a\n # rite boundary, they end here with a plain error.\n word = \"BREAK\" if isinstance(sig, BreakSignal) else \"CONTINUE\"\n raise GodRuntimeError(\n f\"{word} cannot cross the threshold of a rite. It may \"\n f\"only release a loop within rite '{rite.name}' itself.\",\n line,\n ) from None\n return None\n finally:\n # --- v5.2 ---\n self.call_stack.pop()\n # --- end v5.2 ---\n if self.debugger is not None:\n self.debugger.exit_rite(rite)\n\n def call_trace(self) -> list[dict]:\n \"\"\"A snapshot of the rite call stack for uncaught-error reports.\n\n Oldest call first (the most recent call is last). Each entry is\n ``{\"rite\": name, \"line\": call-site line}``.\n \"\"\"\n return [dict(frame) for frame in self.call_stack]\n\n # --------------------------------------------------------------- builtins\n\n @staticmethod\n def _arity(name: str, args: list, want, line) -> None:\n ok = len(args) == want if isinstance(want, int) else len(args) in want\n if not ok:\n expected = want if isinstance(want, int) else \" or \".join(map(str, want))\n raise GodRuntimeError(\n f\"{name} asks for {expected} offering(s), but {len(args)} came.\",\n line,\n )\n\n def _builtin_len(self, args, line):\n self._arity(\"LEN\", args, 1, line)\n value = args[0]\n if isinstance(value, (str, list)):\n return len(value)\n raise GodRuntimeError(\n f\"LEN cannot measure {self.type_name(value)}. Only words and lists have length.\",\n line,\n )\n\n def _builtin_str(self, args, line):\n self._arity(\"STR\", args, 1, line)\n value = args[0]\n if isinstance(value, str):\n return str(value)\n return self.stringify(value)\n\n def _builtin_num(self, args, line):\n self._arity(\"NUM\", args, 1, line)\n value = args[0]\n if self._is_number(value):\n return value\n if isinstance(value, str):\n text = value.strip()\n try:\n return int(text)\n except ValueError:\n pass\n try:\n return float(text)\n except ValueError:\n pass\n raise GodRuntimeError(\n f\"NUM cannot number the word '{value}'. It holds no number.\",\n line,\n )\n raise GodRuntimeError(\n f\"NUM cannot number {self.type_name(value)}.\",\n line,\n )\n\n def _builtin_type(self, args, line):\n self._arity(\"TYPE\", args, 1, line)\n return self.type_name(args[0])\n\n def _builtin_random(self, args, line):\n self._arity(\"RANDOM\", args, 1, line)\n bound = args[0]\n if not self._is_int(bound) or bound <= 0:\n raise GodRuntimeError(\n \"RANDOM needs a positive whole number to cast lots within.\",\n line,\n )\n return random.randrange(bound)\n\n def _builtin_range(self, args, line):\n self._arity(\"RANGE\", args, (1, 2), line)\n for value in args:\n if not self._is_int(value):\n raise GodRuntimeError(\n \"RANGE walks only in whole numbers.\",\n line,\n )\n if len(args) == 1:\n if args[0] < 0:\n raise GodRuntimeError(\"RANGE cannot walk a negative span.\", line)\n return list(range(args[0]))\n return list(range(args[0], args[1]))\n\n def _builtin_push(self, args, line):\n self._arity(\"PUSH\", args, 2, line)\n items, value = args\n if not isinstance(items, list):\n raise GodRuntimeError(\n f\"PUSH needs a list to build upon, not {self.type_name(items)}.\",\n line,\n )\n return items + [value] # a new list; the old one is untouched\n\n def _builtin_upper(self, args, line):\n self._arity(\"UPPER\", args, 1, line)\n return self._upper_lower(args[0], str.upper, \"UPPER\", line)\n\n def _builtin_lower(self, args, line):\n self._arity(\"LOWER\", args, 1, line)\n return self._upper_lower(args[0], str.lower, \"LOWER\", line)\n\n def _upper_lower(self, value, func, name, line):\n if not isinstance(value, str):\n raise GodRuntimeError(\n f\"{name} speaks only to words, not {self.type_name(value)}.\",\n line,\n )\n return func(str(value))\n\n def _builtin_split(self, args, line):\n self._arity(\"SPLIT\", args, 2, line)\n text, sep = args\n if not isinstance(text, str) or not isinstance(sep, str):\n raise GodRuntimeError(\"SPLIT needs two words. The text and the divider.\", line)\n return text.split(str(sep))\n\n def _builtin_join(self, args, line):\n self._arity(\"JOIN\", args, 2, line)\n items, sep = args\n if not isinstance(items, list) or not isinstance(sep, str):\n raise GodRuntimeError(\n \"JOIN needs a list and a word to bind it with.\", line\n )\n return str(sep).join(self.stringify(item) for item in items)\n\n def _builtin_ask(self, args, line):\n self._arity(\"ASK\", args, (0, 1), line)\n prompt = self.stringify(args[0]) if args else \"\"\n try:\n answer = input(prompt)\n except EOFError:\n return \"\"\n return answer\n\n def _builtin_behold(self, args, line):\n self._arity(\"BEHOLD\", args, 0, line)\n return datetime.now(timezone.utc).isoformat()\n\n def _builtin_reverse(self, args, line):\n self._arity(\"REVERSE\", args, 1, line)\n value = args[0]\n if isinstance(value, str):\n return str(value)[::-1]\n if isinstance(value, list):\n return value[::-1]\n raise GodRuntimeError(\n f\"REVERSE can only turn back words and lists, not {self.type_name(value)}.\",\n line,\n )\n\n def _builtin_summon(self, args, line):\n # Pillar 3 FFI: SUMMON(\"plugin.verb\", arg1, ...) calls a\n # plugin-registered verb with converted arguments. The name is a\n # string literal so no grammar change was needed; namespaced names\n # (\"clockwork.now\") keep plugin verbs from colliding with core rites.\n if not args:\n raise GodRuntimeError(\n 'SUMMON needs a verb to call upon. SUMMON(\"name.verb\", ...).',\n line,\n )\n target = args[0]\n if not isinstance(target, str):\n raise GodRuntimeError(\n \"SUMMON needs the verb's name as a word, \"\n f\"not {self.type_name(target)}.\",\n line,\n )\n verb = self._plugin_verbs.get(target)\n if verb is None:\n known = \", \".join(sorted(self._plugin_verbs)) or \"none are present\"\n raise GodRuntimeError(\n f\"SUMMON knows no verb '{target}'. The summoned are: {known}.\",\n line,\n )\n return verb(args[1:], line)\n\n # ------------------------------------------------- v4.0: chain + oracle\n\n def _builtin_anchor(self, args, line):\n \"\"\"ANCHOR(expr [, chain_name]) -- anchor a value's hash on a chain.\n\n Returns the receipt: a map {chain, anchor_hash, height, timestamp,\n payload_hash}. The default chain is \"simulated\" (a local\n tamper-evident JSONL chain); real chain adapters register by name.\n \"\"\"\n import hashlib\n\n self._arity(\"ANCHOR\", args, (1, 2), line)\n value = args[0]\n chain_name = chain_module.DEFAULT_CHAIN_NAME\n if len(args) == 2:\n name_arg = args[1]\n if not isinstance(name_arg, str):\n raise GodRuntimeError(\n \"ANCHOR needs the chain's name as a word, \"\n f\"not {self.type_name(name_arg)}.\",\n line,\n )\n chain_name = str(name_arg)\n adapter = self.chain_adapters.get(chain_name)\n if adapter is None:\n known = \", \".join(sorted(self.chain_adapters)) or \"none are bound\"\n raise GodRuntimeError(\n f\"The chain '{chain_name}' is unknown to the heavens. \"\n f\"The known chains are: {known}.\",\n line,\n )\n payload_hash = hashlib.sha256(\n self.stringify(value).encode(\"utf-8\")\n ).hexdigest()\n receipt = adapter.anchor(payload_hash)\n digest = str(receipt.get(\"anchor_hash\", \"\"))[:8]\n print(\n f\"[ANCHOR] Anchored on {adapter.name} · height {receipt.get('height')} \"\n f\"· {digest} ⚓\"\n )\n self._log(f\"ANCHOR :: {adapter.name} height {receipt.get('height')}\")\n return receipt\n\n def _builtin_consult(self, args, line):\n \"\"\"CONSULT(\"question...\") -- ask the local Spirit oracle for counsel.\n\n Returns 2-3 sentences in the voice of the Spirit Engine's prophesy.\n No external calls: the oracle is the local engine, or a gentle\n silence when none is bound.\n \"\"\"\n self._arity(\"CONSULT\", args, 1, line)\n question = args[0]\n if not isinstance(question, str):\n raise GodRuntimeError(\n \"CONSULT needs a question as a word, \"\n f\"not {self.type_name(question)}.\",\n line,\n )\n if self.spirit is None:\n return \"The Spirit is silent on this question. Breathe, and ask again.\"\n return self.spirit.counsel(str(question))\n\n # ------------------------------------------------------- display & typing\n\n def stringify(self, value) -> str:\n \"\"\"Render a God Code value as it appears in REVEAL.\"\"\"\n if value is None:\n return \"void\"\n if isinstance(value, bool):\n return \"true\" if value else \"false\"\n if isinstance(value, Symbol):\n return str(value)\n if isinstance(value, Contract):\n return str(value)\n if isinstance(value, RiteFunction):\n return f\"rite {value.name}\"\n if isinstance(value, list):\n return \"[\" + \", \".join(self.stringify(item) for item in value) + \"]\"\n if isinstance(value, dict):\n # v4.0: maps (e.g. anchor receipts) reveal as {key: value, ...}.\n inner = \", \".join(\n f\"{key}: {self.stringify(item)}\" for key, item in value.items()\n )\n return \"{\" + inner + \"}\"\n if isinstance(value, float) and value.is_integer():\n return str(int(value))\n if isinstance(value, float) and abs(value - round(value)) < 1e-9:\n # Near-integers (e.g. Newton's method settling on 12.00000001)\n # are revealed cleanly; full precision lives on in the value.\n return str(int(round(value)))\n return str(value)\n\n def type_name(self, value) -> str:\n \"\"\"The TYPE() name for a value: number/string/symbol/list/map/contract/rite/boolean/void.\"\"\"\n if isinstance(value, bool):\n return \"boolean\"\n if value is None:\n return \"void\"\n if isinstance(value, Symbol):\n return \"symbol\"\n if isinstance(value, str):\n return \"string\"\n if isinstance(value, (int, float)):\n return \"number\"\n if isinstance(value, list):\n return \"list\"\n if isinstance(value, dict):\n return \"map\" # v4.0\n if isinstance(value, Contract):\n return \"contract\"\n if isinstance(value, RiteFunction):\n return \"rite\"\n return type(value).__name__.lower()\n\n # ------------------------------------------------------------ audit log\n\n @staticmethod\n def _now() -> str:\n return datetime.now(timezone.utc).isoformat()\n\n def _open_log(self) -> None:\n if not self.log_path:\n return\n try:\n path = Path(self.log_path)\n if path.parent != Path(\".\"):\n path.parent.mkdir(parents=True, exist_ok=True)\n self._log_handle = path.open(\"a\", encoding=\"utf-8\")\n except OSError:\n self._log_handle = None\n\n def _close_log(self) -> None:\n handle, self._log_handle = self._log_handle, None\n if handle is not None:\n try:\n handle.close()\n except OSError:\n pass\n\n def _log(self, message: str) -> None:\n if self._log_handle is None:\n return\n try:\n self._log_handle.write(f\"[{self._now()}] {message}\\n\")\n self._log_handle.flush()\n except OSError:\n pass\n\n def _log_statement(self, stmt) -> None:\n kind = type(stmt).__name__\n line = getattr(stmt, \"line\", \"?\")\n summary = self._summarize(stmt)\n self._log(f\"{line} :: {kind} :: {summary}\")\n\n @staticmethod\n def _summarize(stmt) -> str:\n name = getattr(stmt, \"name\", \"\")\n extra = \"\"\n if isinstance(stmt, Declare):\n extra = f\" {stmt.name}\"\n elif isinstance(stmt, DeclareIntent):\n extra = f\" {stmt.rite}\"\n elif isinstance(stmt, (Breathe, Bless, Anoint)):\n extra = f\" {stmt.name}\"\n elif isinstance(stmt, DefineRite):\n extra = f\" {stmt.name}\"\n elif isinstance(stmt, ForLoop):\n extra = f\" {stmt.var}\"\n elif isinstance(stmt, Import):\n extra = f\" {stmt.path}\"\n elif isinstance(stmt, Prophesy):\n text = (stmt.text or \"\")[:40]\n extra = f\" {text!r}\" if text else \"\"\n return f\"{type(stmt).__name__.upper()}{extra}\"\n","godcode/ledger.py":"\"\"\"CovenantLedger -- an append-only, hash-chained record of sealed covenants. 🔒\n\nEach sealed record becomes a block in a JSONL chain file. A block's hash is\nthe sha256 of the canonical JSON of {index, timestamp, record, prev_hash};\nthe genesis block's prev_hash is \"GENESIS\". verify() recomputes every link.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom datetime import datetime, timezone\nfrom pathlib import Path\n\nGENESIS_PREV_HASH = \"GENESIS\"\n\n\ndef _canonical(payload: dict) -> bytes:\n \"\"\"Canonical JSON bytes used for hashing (stable key order, no whitespace).\"\"\"\n return json.dumps(payload, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False).encode(\"utf-8\")\n\n\ndef _block_hash(index: int, timestamp: str, record: dict, prev_hash: str) -> str:\n return hashlib.sha256(\n _canonical(\n {\"index\": index, \"timestamp\": timestamp, \"record\": record, \"prev_hash\": prev_hash}\n )\n ).hexdigest()\n\n\nclass CovenantLedger:\n \"\"\"Append-only covenant chain persisted as JSONL.\"\"\"\n\n def __init__(self, path: str | Path = \"covenant.chain\") -> None:\n self.path = Path(path)\n if str(self.path.parent) not in (\"\", \".\"):\n self.path.parent.mkdir(parents=True, exist_ok=True)\n\n def seal(self, record: dict) -> dict:\n \"\"\"Append a record as a new block; return the block dict.\"\"\"\n blocks = self.read_all()\n index = len(blocks)\n prev_hash = blocks[-1][\"hash\"] if blocks else GENESIS_PREV_HASH\n timestamp = datetime.now(timezone.utc).isoformat()\n block = {\n \"index\": index,\n \"timestamp\": timestamp,\n \"record\": record,\n \"prev_hash\": prev_hash,\n \"hash\": _block_hash(index, timestamp, record, prev_hash),\n }\n with open(self.path, \"a\", encoding=\"utf-8\") as f:\n f.write(json.dumps(block, ensure_ascii=False) + \"\\n\")\n return block\n\n def read_all(self) -> list[dict]:\n \"\"\"Return every block in chain order (empty list if no chain file yet).\"\"\"\n if not self.path.exists():\n return []\n blocks: list[dict] = []\n with open(self.path, encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n if line:\n blocks.append(json.loads(line))\n return blocks\n\n def verify(self) -> tuple[bool, str]:\n \"\"\"Recompute the chain. (True, 'N covenants intact 🔒') or (False, 'chain broken at block K').\"\"\"\n blocks = self.read_all()\n prev_hash = GENESIS_PREV_HASH\n for expected, block in enumerate(blocks):\n index = block.get(\"index\")\n payload_ok = (\n index == expected\n and block.get(\"prev_hash\") == prev_hash\n and _block_hash(\n block.get(\"index\"),\n block.get(\"timestamp\"),\n block.get(\"record\"),\n block.get(\"prev_hash\"),\n )\n == block.get(\"hash\")\n )\n if not payload_ok:\n return False, f\"chain broken at block {index} 🔗💔\"\n prev_hash = block[\"hash\"]\n return True, f\"{len(blocks)} covenants intact 🔒\"\n","godcode/lexer.py":"\"\"\"Lexer for God Code v2.0.\n\n``Lexer(source).lex()`` turns source text into a list of Tokens with\n1-based line/column positions, NEWLINE tokens for each physical line\nbreak, and a final EOF token. ``#`` starts a comment to end of line.\nKeywords are matched case-insensitively (canonical value = UPPER);\nidentifiers preserve their casing.\n\nA scroll may choose another tongue with a pragma comment, e.g.\n``# tongue: tn`` for Setswana (see ``godcode.tongues``). Tongue words map\nonto the same keyword tokens, so the parser never changes; ``Lexer.tongue``\nreports the resolved tongue code (``\"en\"`` when none was chosen).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom .errors import LexerError\nfrom .tokens import Token, TokenType\nfrom .tongues import detect_tongue, resolve as resolve_tongue\n\n# Every alphabetic TokenType name that is not a literal/structural/operator\n# token is a keyword. New keyword TokenTypes are picked up automatically.\n_NON_KEYWORD_NAMES = {\n \"NUMBER\", \"STRING\", \"IDENT\", \"NEWLINE\", \"EOF\",\n \"PLUS\", \"MINUS\", \"STAR\", \"SLASH\", \"PERCENT\",\n \"EQ\", \"NEQ\", \"LT\", \"GT\", \"LTE\", \"GTE\",\n \"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\", \"COMMA\",\n}\nKEYWORDS: dict[str, TokenType] = {\n tt.name: tt for tt in TokenType if tt.name not in _NON_KEYWORD_NAMES\n}\n\n_ESCAPES = {'\"': '\"', \"\\\\\": \"\\\\\", \"n\": \"\\n\", \"t\": \"\\t\"}\n\n_SINGLE_CHAR_TOKENS = {\n \"+\": TokenType.PLUS,\n \"-\": TokenType.MINUS,\n \"*\": TokenType.STAR,\n \"/\": TokenType.SLASH,\n \"%\": TokenType.PERCENT,\n \"=\": TokenType.EQ,\n \"<\": TokenType.LT,\n \">\": TokenType.GT,\n \"(\": TokenType.LPAREN,\n \")\": TokenType.RPAREN,\n \"[\": TokenType.LBRACKET,\n \"]\": TokenType.RBRACKET,\n \",\": TokenType.COMMA,\n}\n\n_MULTI_CHAR_TOKENS = {\n \"!=\": TokenType.NEQ,\n \"<=\": TokenType.LTE,\n \">=\": TokenType.GTE,\n \"==\": TokenType.EQ, # both = and == spell equality\n}\n\n\nclass Lexer:\n def __init__(self, source: str, tongue: str | None = None):\n self.source = source\n # An explicit tongue wins; otherwise the source's own pragma speaks.\n code = tongue if tongue is not None else detect_tongue(source)\n table = resolve_tongue(code)\n self.tongue: str = \"en\" if code is None else code\n self._aliases: dict[str, TokenType] = {\n word: KEYWORDS[canon] for word, canon in table[\"aliases\"].items()\n }\n self._compounds: dict[tuple[str, str], TokenType] = {\n pair: KEYWORDS[canon] for pair, canon in table[\"compounds\"].items()\n }\n\n def lex(self) -> list[Token]:\n src = self.source\n n = len(src)\n tokens: list[Token] = []\n i = 0\n line = 1\n col = 1\n # The previous word token, for two-word closers (FEDISA FA -> ENDIF).\n prev_word = \"\"\n prev_line = 0\n prev_col = 0\n\n def here() -> tuple[int, int]:\n return line, col\n\n while i < n:\n c = src[i]\n\n # whitespace (but not newlines)\n if c == \" \" or c == \"\\t\":\n i += 1\n col += 1\n continue\n\n # line breaks: collapse \\r\\n, tolerate lone \\r\n if c == \"\\r\" or c == \"\\n\":\n ln, cl = here()\n if c == \"\\r\" and i + 1 < n and src[i + 1] == \"\\n\":\n i += 2\n else:\n i += 1\n tokens.append(Token(TokenType.NEWLINE, \"\\n\", ln, cl))\n line += 1\n col = 1\n continue\n\n # comments run to end of line (the newline itself is still lexed)\n if c == \"#\":\n while i < n and src[i] != \"\\n\" and src[i] != \"\\r\":\n i += 1\n continue\n\n # strings\n if c == '\"':\n tok, i, col = self._lex_string(src, i, line, col)\n tokens.append(tok)\n continue\n\n # numbers\n if c.isdigit():\n tok, i, col = self._lex_number(src, i, line, col)\n tokens.append(tok)\n continue\n\n # words: keywords (case-insensitive), tongue words, or identifiers\n if c.isalpha() or c == \"_\":\n start = i\n ln, cl = here()\n while i < n and (src[i].isalnum() or src[i] == \"_\"):\n i += 1\n word = src[start:i]\n col += i - start\n upper = word.upper()\n closer = self._compounds.get((prev_word, upper))\n if (closer is not None and prev_line == ln and tokens\n and (tokens[-1].line, tokens[-1].col) == (prev_line, prev_col)):\n # A two-word phrase on one line, the words side by side:\n # FEDISA FA -> ENDIF, FINISH IF -> ENDIF, Ọ BỤRỤ -> IF.\n # Either word may be a keyword, a tongue word, or a name.\n tokens.pop()\n tokens.append(Token(closer, closer.name, prev_line, prev_col))\n elif upper in KEYWORDS:\n tokens.append(Token(KEYWORDS[upper], upper, ln, cl))\n elif upper in self._aliases:\n tt = self._aliases[upper]\n tokens.append(Token(tt, tt.name, ln, cl))\n else:\n tokens.append(Token(TokenType.IDENT, word, ln, cl))\n prev_word, prev_line, prev_col = upper, ln, cl\n continue\n\n # operators: multi-char first, then single-char\n two = src[i : i + 2]\n if two in _MULTI_CHAR_TOKENS:\n ln, cl = here()\n tokens.append(Token(_MULTI_CHAR_TOKENS[two], two, ln, cl))\n i += 2\n col += 2\n continue\n if c in _SINGLE_CHAR_TOKENS:\n ln, cl = here()\n tokens.append(Token(_SINGLE_CHAR_TOKENS[c], c, ln, cl))\n i += 1\n col += 1\n continue\n\n raise LexerError(\n f\"The heavens do not recognize the character {c!r}; \"\n \"it has no place in the holy tongue\",\n line=line,\n col=col,\n )\n\n tokens.append(Token(TokenType.EOF, \"\", line, col))\n return tokens\n\n # -- helpers -----------------------------------------------------------\n\n @staticmethod\n def _lex_string(src: str, i: int, line: int, col: int):\n \"\"\"Lex a string starting at the opening quote. Returns (token, i, col).\"\"\"\n n = len(src)\n open_line, open_col = line, col\n i += 1 # opening quote\n col += 1\n buf: list[str] = []\n while i < n and src[i] != '\"':\n ch = src[i]\n if ch == \"\\n\" or ch == \"\\r\":\n raise LexerError(\n \"The utterance was never finished: string runs past the \"\n \"end of the line without a closing quote\",\n line=open_line,\n col=open_col,\n )\n if ch == \"\\\\\":\n if i + 1 >= n:\n break\n esc = src[i + 1]\n if esc not in _ESCAPES:\n raise LexerError(\n f\"Unknown escape '\\\\{esc}'; the holy escapes are \"\n '\\\\\\\\ \\\\\" \\\\n \\\\t',\n line=line,\n col=col,\n )\n buf.append(_ESCAPES[esc])\n i += 2\n col += 2\n else:\n buf.append(ch)\n i += 1\n col += 1\n if i >= n:\n raise LexerError(\n \"The utterance was never finished: unterminated string\",\n line=open_line,\n col=open_col,\n )\n i += 1 # closing quote\n col += 1\n return Token(TokenType.STRING, \"\".join(buf), open_line, open_col), i, col\n\n @staticmethod\n def _lex_number(src: str, i: int, line: int, col: int):\n \"\"\"Lex an int or float starting at a digit. Returns (token, i, col).\"\"\"\n n = len(src)\n start = i\n while i < n and src[i].isdigit():\n i += 1\n is_float = False\n if i < n and src[i] == \".\":\n if i + 1 < n and src[i + 1].isdigit():\n is_float = True\n i += 1\n while i < n and src[i].isdigit():\n i += 1\n else:\n raise LexerError(\n f\"Malformed number {src[start:i+1]!r}; a decimal point \"\n \"must be followed by digits\",\n line=line,\n col=col,\n )\n text = src[start:i]\n value: int | float = float(text) if is_float else int(text)\n tok = Token(TokenType.NUMBER, value, line, col)\n return tok, i, col + (i - start)\n","godcode/linter.py":"\"\"\"Static lint pass over the God Code AST (rules GC001-GC006).\n\n``lint_source(source, source_name)`` lexes, parses, and walks a scroll,\nreturning a list of ``Finding`` records. The scope model mirrors the\ninterpreter's real behavior:\n\n- IF and WHILE bodies run in the *current* environment (no new scope).\n- FOR bodies run in one child environment; the loop variable lives there.\n- DEFINE RITE bodies run in a child environment whose parent is the\n closure environment (lexical scope at the point of definition); the\n rite name is bound in the enclosing scope, params in the child.\n- DECLARE binds in the current environment, shadowing any outer binding.\n\nRules (stable ids, plain language):\n- GC001 unused variable: a name DECLAREd (or a FOR loop variable) that is\n never referenced anywhere else. A reference inside a nested rite body\n counts as used, since closures capture; a loop variable used in its\n body counts as used.\n- GC002 undefined name: an Identifier or rite call naming something never\n declared, defined, imported, or provided by a builtin.\n- GC003 shadowing: a DECLARE, rite param, or FOR loop variable that reuses\n a name already visible from an outer scope.\n- GC004 empty block: IF/FOR/WHILE/DEFINE RITE with zero statements in a\n body (both the IF and ELSE bodies are checked).\n- GC005 unreachable code: any statement after RETURN, BREAK, or CONTINUE\n in the same block.\n- GC006 re-DECLARE: the same name DECLAREd twice in the same scope. A\n re-DECLARE whose value uses the old value (the update idiom, e.g.\n DECLARE count AS count + 1) is not flagged, since that is the language's\n only way to update a variable.\n\nUnknown AST node types are traversed generically and never raise.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\nfrom . import ast as A\nfrom .tongues import parse_source\n\n\n# ---------------------------------------------------------------------------\n# public records\n# ---------------------------------------------------------------------------\n\n@dataclass\nclass Finding:\n line: int\n col: int\n rule: str\n message: str\n\n\n# ---------------------------------------------------------------------------\n# scope model\n# ---------------------------------------------------------------------------\n\n# Declaration kinds.\n_DECLARE = \"declare\" # DECLARE name AS ...\n_RITE = \"rite\" # DEFINE RITE name(...)\n_PARAM = \"param\" # rite parameter\n_LOOP = \"loop\" # FOR loop variable\n\n# GC001 tracks these kinds (DECLAREd names and loop variables).\n_GC001_KINDS = (_DECLARE, _LOOP)\n\n\n@dataclass\nclass _Decl:\n name: str\n kind: str\n line: int\n col: int\n used: bool = False\n\n\n@dataclass\nclass _Ref:\n \"\"\"A use of a name. kind \"read\" may raise GC002; kind \"intent\" only\n marks a declaration as used (DECLARE INTENT names a rite's purpose\n without requiring the rite to exist).\"\"\"\n name: str\n line: int\n col: int\n kind: str # \"read\" | \"intent\"\n\n\nclass _Scope:\n def __init__(self, parent: \"_Scope | None\" = None):\n self.parent = parent\n self.decls: dict[str, list[_Decl]] = {}\n self.children: list[_Scope] = []\n\n\ndef _interpreter():\n \"\"\"Build an Interpreter the way the engine builds it, with plugins off\n so the builtin names are deterministic. This is the same source the\n task names for reading ``_builtins`` without duplicating the list.\"\"\"\n from . import plugins\n from .interpreter import Interpreter\n\n os.environ.setdefault(plugins.DISABLE_ENV_VAR, \"1\")\n return Interpreter(spirit=None, ledger=None)\n\n\ndef _builtin_names() -> set[str]:\n \"\"\"Exact builtin names (all UPPER) plus the special ``contract`` name\n the interpreter handles before builtin lookup.\"\"\"\n interp = _interpreter()\n names = set(interp._builtins.keys())\n names.add(\"contract\")\n return names\n\n\n# ---------------------------------------------------------------------------\n# the pass\n# ---------------------------------------------------------------------------\n\nclass _Linter:\n def __init__(self, source_name: str):\n self.source_name = source_name\n self.findings: list[Finding] = []\n self.root = _Scope()\n self.refs: list[tuple[_Scope, _Ref]] = []\n self.builtins = _builtin_names()\n self.interp = _interpreter()\n self.imported_names: set[str] = set()\n self.imports_unknown = False\n self._import_seen: set[str] = set()\n # source_dir mirrors Interpreter.run: the linted file's own dir.\n try:\n if Path(source_name).is_file():\n self.source_dir = Path(source_name).resolve().parent\n else:\n self.source_dir = Path.cwd()\n except (OSError, ValueError):\n self.source_dir = Path.cwd()\n # Import resolution mirrors Interpreter.run: relative to the\n # linted scroll's own directory.\n self.interp.source_dir = self.source_dir\n\n # -- scope helpers ---------------------------------------------------\n\n def _visible_in_outer(self, scope: _Scope, name: str) -> bool:\n env = scope.parent\n while env is not None:\n if name in env.decls:\n return True\n env = env.parent\n return False\n\n def _declare(self, scope: _Scope, name: str, kind: str,\n line: int, col: int, value=None) -> _Decl:\n decl = _Decl(name=name, kind=kind, line=line, col=col)\n bucket = scope.decls.setdefault(name, [])\n if kind == _DECLARE and any(d.kind == _DECLARE for d in bucket):\n # The update idiom (DECLARE x AS ) is the only\n # way to change a variable, so it is not a re-declaration.\n if value is None or not self._expr_mentions(value, name):\n self._finding(line, col, \"GC006\",\n f\"'{name}' is declared more than once in the same scope\")\n elif kind in (_DECLARE, _PARAM, _LOOP) and self._visible_in_outer(scope, name):\n self._finding(line, col, \"GC003\",\n f\"'{name}' shadows a name already visible from an outer scope\")\n bucket.append(decl)\n return decl\n\n def _ref(self, scope: _Scope, name: str, line: int, col: int,\n kind: str = \"read\") -> None:\n self.refs.append((scope, _Ref(name=name, line=line, col=col, kind=kind)))\n\n def _finding(self, line: int, col: int, rule: str, message: str) -> None:\n self.findings.append(Finding(line=line, col=col, rule=rule,\n message=message))\n\n # -- driver ----------------------------------------------------------\n\n def lint(self, program) -> list[Finding]:\n self._walk_block(program.statements, self.root)\n self._resolve_imports(program)\n self._resolve_refs()\n self._check_unused(self.root)\n self.findings.sort(key=lambda f: (f.line, f.col, f.rule))\n return self.findings\n\n # -- statement walking -----------------------------------------------\n\n def _walk_block(self, stmts: list, scope: _Scope) -> None:\n terminated_by = None # the word that ended this block's flow\n for stmt in stmts:\n if terminated_by is not None:\n self._finding(getattr(stmt, \"line\", 1), getattr(stmt, \"col\", 1),\n \"GC005\",\n f\"unreachable code after {terminated_by}\")\n kind = type(stmt).__name__\n if kind in (\"Return\", \"Break\", \"Continue\"):\n terminated_by = {\"Return\": \"RETURN\", \"Break\": \"BREAK\",\n \"Continue\": \"CONTINUE\"}[kind]\n self._walk_stmt(stmt, scope)\n\n def _walk_stmt(self, stmt, scope: _Scope) -> None:\n kind = type(stmt).__name__\n meth = getattr(self, \"_stmt_\" + kind, None)\n if meth is not None:\n meth(stmt, scope)\n return\n # Unknown node: walk any statement lists and expressions it holds,\n # in the current scope. Never raise.\n self._walk_unknown(stmt, scope)\n\n def _walk_unknown(self, node, scope: _Scope) -> None:\n try:\n fields = vars(node)\n except TypeError:\n return\n for value in fields.values():\n if isinstance(value, str):\n continue\n if isinstance(value, list):\n for item in value:\n if self._looks_like_stmt(item):\n self._walk_stmt(item, scope)\n elif self._looks_like_expr(item):\n self._walk_expr(item, scope)\n elif isinstance(item, list):\n for sub in item:\n if self._looks_like_stmt(sub):\n self._walk_stmt(sub, scope)\n elif self._looks_like_expr(sub):\n self._walk_expr(sub, scope)\n elif self._looks_like_stmt(value):\n self._walk_stmt(value, scope)\n elif self._looks_like_expr(value):\n self._walk_expr(value, scope)\n\n @staticmethod\n def _looks_like_stmt(node) -> bool:\n return hasattr(node, \"line\") and hasattr(node, \"col\") and not isinstance(\n node, (str, bytes, int, float, bool, type(None)))\n\n @staticmethod\n def _looks_like_expr(node) -> bool:\n return _Linter._looks_like_stmt(node)\n\n # -- known statements ------------------------------------------------\n\n def _stmt_Program(self, node, scope: _Scope) -> None:\n self._walk_block(node.statements, scope)\n\n def _stmt_CreationBlock(self, node, scope: _Scope) -> None:\n # The creation block runs in the same environment: no new scope.\n self._walk_block(node.statements, scope)\n\n def _stmt_Declare(self, node, scope: _Scope) -> None:\n # The value is breathed in the enclosing scope, before the name\n # itself is bound (mirrors env.define(name, eval(value, env))).\n self._walk_expr(node.value, scope)\n self._declare(scope, node.name, _DECLARE, node.line, node.col,\n value=node.value)\n\n def _expr_mentions(self, expr, name: str) -> bool:\n \"\"\"True when the expression reads the given name anywhere inside.\"\"\"\n if expr is None or isinstance(expr, str):\n return False\n kind = type(expr).__name__\n if kind == \"Identifier\":\n return expr.name == name\n if kind == \"CallExpr\":\n return expr.callee == name or any(\n self._expr_mentions(a, name) for a in expr.args)\n if kind == \"BinaryOp\":\n return (self._expr_mentions(expr.left, name)\n or self._expr_mentions(expr.right, name))\n if kind == \"UnaryOp\":\n return self._expr_mentions(expr.operand, name)\n if kind == \"InterpolatedString\":\n return any(not isinstance(p, str) and self._expr_mentions(p, name)\n for p in expr.parts)\n if kind == \"ListLiteral\":\n return any(self._expr_mentions(i, name) for i in expr.items)\n if kind == \"Index\":\n return (self._expr_mentions(expr.obj, name)\n or self._expr_mentions(expr.index, name))\n # Unknown node types: walk their fields generically.\n try:\n fields = vars(expr)\n except TypeError:\n return False\n for v in fields.values():\n if isinstance(v, list):\n if any(self._expr_mentions(i, name) for i in v):\n return True\n elif self._expr_mentions(v, name):\n return True\n return False\n\n def _stmt_DeclareIntent(self, node, scope: _Scope) -> None:\n # Names a rite's purpose; marks the rite used but never flags GC002.\n self._ref(scope, node.rite, node.line, node.col, kind=\"intent\")\n\n def _stmt_DeclarePermission(self, node, scope: _Scope) -> None: # noqa: ARG002\n # A permission manifest declares powers, not names; nothing to lint.\n pass\n\n def _stmt_Breathe(self, node, scope: _Scope) -> None:\n self._ref(scope, node.name, node.line, node.col)\n\n def _stmt_Reveal(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_Prophesy(self, node, scope: _Scope) -> None: # noqa: ARG002\n return\n\n def _stmt_Ascend(self, node, scope: _Scope) -> None: # noqa: ARG002\n return\n\n def _stmt_Reflect(self, node, scope: _Scope) -> None: # noqa: ARG002\n return\n\n def _stmt_Bless(self, node, scope: _Scope) -> None:\n self._ref(scope, node.name, node.line, node.col)\n\n def _stmt_Anoint(self, node, scope: _Scope) -> None:\n self._ref(scope, node.name, node.line, node.col)\n\n def _stmt_SealStmt(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_Testify(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_IfStmt(self, node, scope: _Scope) -> None:\n self._walk_expr(node.cond, scope)\n # IF bodies run in the current environment: no new scope.\n if not node.then_body:\n self._finding(node.line, node.col, \"GC004\", \"empty IF body\")\n self._walk_block(node.then_body, scope)\n if node.has_else and not node.else_body:\n self._finding(node.line, node.col, \"GC004\", \"empty ELSE body\")\n self._walk_block(node.else_body, scope)\n\n def _stmt_ForLoop(self, node, scope: _Scope) -> None:\n # The iterable is breathed in the enclosing scope; the body runs in\n # one child environment holding the loop variable.\n self._walk_expr(node.iterable, scope)\n child = _Scope(parent=scope)\n scope.children.append(child)\n self._declare(child, node.var, _LOOP, node.line, node.col)\n if not node.body:\n self._finding(node.line, node.col, \"GC004\", \"empty FOR body\")\n self._walk_block(node.body, child)\n\n def _stmt_WhileLoop(self, node, scope: _Scope) -> None:\n self._walk_expr(node.cond, scope)\n # The body runs in the current environment: no new scope.\n if not node.body:\n self._finding(node.line, node.col, \"GC004\", \"empty WHILE body\")\n self._walk_block(node.body, scope)\n\n def _stmt_TryStmt(self, node, scope: _Scope) -> None:\n # TRY/CATCH bodies run in the current environment: no new scope.\n # The CATCH's error name is an implicit binding, marked used so a\n # CATCH that never reads it is not flagged as an unused variable.\n if not node.try_body:\n self._finding(node.line, node.col, \"GC004\", \"empty TRY body\")\n self._walk_block(node.try_body, scope)\n decl = self._declare(scope, node.error_name, _DECLARE,\n node.line, node.col)\n decl.used = True\n if not node.catch_body:\n self._finding(node.line, node.col, \"GC004\", \"empty CATCH body\")\n self._walk_block(node.catch_body, scope)\n\n def _stmt_DefineRite(self, node, scope: _Scope) -> None:\n # The rite name is bound in the enclosing scope (so rites may call\n # themselves); the body runs in a child environment whose parent is\n # the lexical closure, holding the params.\n self._declare(scope, node.name, _RITE, node.line, node.col)\n child = _Scope(parent=scope)\n scope.children.append(child)\n for param in node.params:\n self._declare(child, param, _PARAM, node.line, node.col)\n if not node.body:\n self._finding(node.line, node.col, \"GC004\",\n f\"empty rite body for '{node.name}'\")\n self._walk_block(node.body, child)\n\n def _stmt_Return(self, node, scope: _Scope) -> None:\n if node.expr is not None:\n self._walk_expr(node.expr, scope)\n\n def _stmt_Break(self, node, scope: _Scope) -> None: # noqa: ARG002\n # No names are read or bound; control passes to the enclosing loop.\n return\n\n def _stmt_Continue(self, node, scope: _Scope) -> None: # noqa: ARG002\n # No names are read or bound; control passes to the enclosing loop.\n return\n\n def _stmt_Import(self, node, scope: _Scope) -> None: # noqa: ARG002\n # Imports are resolved after the walk (see _resolve_imports).\n return\n\n def _stmt_ExprStmt(self, node, scope: _Scope) -> None:\n self._walk_expr(node.expr, scope)\n\n # -- expression walking ----------------------------------------------\n\n def _walk_expr(self, expr, scope: _Scope) -> None:\n if expr is None:\n return\n kind = type(expr).__name__\n if kind == \"Identifier\":\n self._ref(scope, expr.name, expr.line, expr.col)\n elif kind == \"CallExpr\":\n self._ref(scope, expr.callee, expr.line, expr.col)\n for arg in expr.args:\n self._walk_expr(arg, scope)\n elif kind == \"BinaryOp\":\n self._walk_expr(expr.left, scope)\n self._walk_expr(expr.right, scope)\n elif kind == \"UnaryOp\":\n self._walk_expr(expr.operand, scope)\n elif kind == \"Literal\":\n return\n elif kind == \"InterpolatedString\":\n for part in expr.parts:\n if isinstance(part, str):\n continue\n self._walk_expr(part, scope)\n elif kind == \"ListLiteral\":\n for item in expr.items:\n self._walk_expr(item, scope)\n elif kind == \"Index\":\n self._walk_expr(expr.obj, scope)\n self._walk_expr(expr.index, scope)\n else:\n # Unknown expression: walk any nested nodes generically.\n self._walk_unknown(expr, scope)\n\n # -- imports ----------------------------------------------------------\n\n def _collect_imports(self, node) -> list:\n \"\"\"Every Import statement in the tree, in source order.\"\"\"\n found: list = []\n\n def visit(n):\n if n is None or isinstance(n, str):\n return\n if type(n).__name__ == \"Import\":\n found.append(n)\n return\n try:\n fields = vars(n)\n except TypeError:\n return\n for value in fields.values():\n if isinstance(value, list):\n for item in value:\n visit(item)\n else:\n visit(value)\n\n visit(node)\n return found\n\n def _resolve_imports(self, program) -> None:\n for stmt in self._collect_imports(program):\n path = self._resolve_one_import(stmt.path)\n if path is None:\n # Cannot resolve: skip GC002 for names rather than guessing.\n self.imports_unknown = True\n continue\n self._harvest_import(path)\n\n def _resolve_one_import(self, import_path: str) -> \"Path | None\":\n \"\"\"Resolve the way Interpreter._resolve_import does.\"\"\"\n try:\n return self.interp._resolve_import(import_path, None)\n except Exception:\n return None\n\n def _harvest_import(self, path: Path) -> None:\n \"\"\"Harvest top-level (importer-visible) rite and DECLAREd names from\n an imported scroll: names bound in its root scope, since the\n interpreter runs imports in the importer's own environment.\"\"\"\n key = str(path)\n if key in self._import_seen:\n return\n self._import_seen.add(key)\n try:\n source = path.read_text(encoding=\"utf-8\")\n program = parse_source(source)\n except Exception:\n self.imports_unknown = True\n return\n saved_root = self.root\n saved_refs = self.refs\n saved_findings = self.findings\n try:\n self.root = _Scope()\n self.refs = []\n self.findings = []\n self._walk_block(program.statements, self.root)\n for name, bucket in self.root.decls.items():\n if any(d.kind in (_DECLARE, _RITE) for d in bucket):\n self.imported_names.add(name)\n # Recurse into the import's own imports, guarded by _import_seen.\n self._resolve_imports(program)\n finally:\n self.root = saved_root\n self.refs = saved_refs\n self.findings = saved_findings\n\n # -- reference resolution ---------------------------------------------\n\n def _resolve_refs(self) -> None:\n for scope, ref in self.refs:\n bucket = self._resolve(scope, ref.name)\n if bucket is not None:\n # Mark every declaration in the bucket used: a re-declared\n # name's value reads the older binding (DECLARE x AS x + 1),\n # so all of them take part in the program's life.\n for decl in bucket:\n decl.used = True\n continue\n if ref.kind != \"read\":\n continue\n if ref.name in self.imported_names:\n continue\n if ref.name.upper() in self.builtins or ref.name in self.builtins:\n continue\n if self.imports_unknown:\n continue\n self._finding(ref.line, ref.col, \"GC002\",\n f\"undefined name '{ref.name}'\")\n\n @staticmethod\n def _resolve(scope: _Scope, name: str) -> \"list | None\":\n env: \"_Scope | None\" = scope\n while env is not None:\n bucket = env.decls.get(name)\n if bucket:\n # The runtime's env.define overwrites, so the last\n # declaration in the innermost scope is the live one.\n return bucket\n env = env.parent\n return None\n\n # -- GC001 -------------------------------------------------------------\n\n def _check_unused(self, scope: _Scope) -> None:\n for bucket in scope.decls.values():\n for decl in bucket:\n if decl.kind in _GC001_KINDS and not decl.used:\n self._finding(decl.line, decl.col, \"GC001\",\n f\"unused variable '{decl.name}'\")\n for child in scope.children:\n self._check_unused(child)\n\n\n# ---------------------------------------------------------------------------\n# public entry point\n# ---------------------------------------------------------------------------\n\ndef lint_source(source: str, source_name: str = \"\") -> list[Finding]:\n \"\"\"Lex, parse, and lint a God Code scroll.\n\n Raises the usual lexer/parser errors on bad source, so callers can\n report them the way ``godcode check`` does.\n \"\"\"\n program = parse_source(source)\n return _Linter(source_name).lint(program)\n\n\n__all__ = [\"Finding\", \"lint_source\"]\n","godcode/lsp.py":"\"\"\"Language server for God Code (v3.0, Pillar 4).\n\nA minimal Language Server Protocol implementation over stdio, hand-rolled\non top of the stdlib. No third-party dependencies. JSON-RPC 2.0 messages\nare framed with ``Content-Length`` headers, per the LSP base protocol.\n\nLifecycle::\n\n godcode lsp # start serving on stdin/stdout\n\nDiagnostics are produced by the real lexer/parser pipeline (the same\nlogic ``godcode check`` uses): opening or changing a ``.god`` scroll\nre-parses it and publishes the divine errors as LSP diagnostics.\n\nProtocol notes:\n * All logging goes to stderr. stdout is the protocol channel. Nothing\n else may ever be written there.\n * Unknown methods answer with JSON-RPC error -32601 (\"Method not found\").\n * Malformed frames are skipped; the server keeps serving.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport re\nimport sys\n\nfrom godcode import __version__ as ENGINE_VERSION\n\n# ---------------------------------------------------------------------------\n# Divine documentation table (hover + completion)\n# ---------------------------------------------------------------------------\n\nLSP_DOCS: dict[str, str] = {\n # -- block sentinels -------------------------------------------------\n \"BEGIN CREATION\": (\n \"**BEGIN CREATION**\\n\\n\"\n \"Speak, and let there be a program. Every scroll opens its works \"\n \"with `BEGIN CREATION` and closes them with `END CREATION`.\\n\\n\"\n \"```godcode\\nBEGIN CREATION\\n REVEAL(\\\"Let there be light\\\")\\n\"\n \" ASCEND\\nEND CREATION\\n```\"\n ),\n \"END CREATION\": (\n \"**END CREATION**\\n\\n\"\n \"The seal upon the scroll. It closes what `BEGIN CREATION` opened. \"\n \"No works may follow it.\\n\\n\"\n \"```godcode\\nEND CREATION\\n```\"\n ),\n \"DEFINE RITE\": (\n \"**DEFINE RITE**\\n\\n\"\n \"Establish a rite. A named ceremony of statements that may be \"\n \"invoked again and again. Closed with `END RITE`; a rite may \"\n \"`RETURN` a value to its caller.\\n\\n\"\n \"```godcode\\nDEFINE RITE bless(name)\\n\"\n \" REVEAL(\\\"Blessed be \\\" + name)\\nEND RITE\\n```\"\n ),\n \"END RITE\": (\n \"**END RITE**\\n\\n\"\n \"The closing of a rite begun with `DEFINE RITE`. All ceremonies \"\n \"must be sealed.\\n\\n\"\n \"```godcode\\nEND RITE\\n```\"\n ),\n \"BREATHE LIFE INTO\": (\n \"**BREATHE LIFE INTO**\\n\\n\"\n \"Awaken a declared vessel so it may be used. A name must be \"\n \"`DECLARE`d before the breath is given.\\n\\n\"\n \"```godcode\\nDECLARE vessel AS 0\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n # -- keywords --------------------------------------------------------\n \"BEGIN\": (\n \"**BEGIN**\\n\\n\"\n \"The opening word of creation. Always paired with `CREATION`. \"\n \"See `BEGIN CREATION`.\\n\\n```godcode\\nBEGIN CREATION\\n```\"\n ),\n \"CREATION\": (\n \"**CREATION**\\n\\n\"\n \"The body of all works. Paired with `BEGIN` to open a scroll and \"\n \"with `END` to close it. See `BEGIN CREATION`.\\n\\n\"\n \"```godcode\\nBEGIN CREATION\\n ASCEND\\nEND CREATION\\n```\"\n ),\n \"DECLARE\": (\n \"**DECLARE**\\n\\n\"\n \"Bring a name into being and bind it to a value. \"\n \"Every vessel must be declared before the breath is given.\\n\\n\"\n \"```godcode\\nDECLARE tribes AS 12\\n```\"\n ),\n \"AS\": (\n \"**AS**\\n\\n\"\n \"The binding word. It joins a declared name to its value, as \"\n \"in `DECLARE x AS 1`.\\n\\n```godcode\\nDECLARE x AS 1\\n```\"\n ),\n \"IF\": (\n \"**IF**\\n\\n\"\n \"Weigh a condition; if it holds true, the words between `THEN` \"\n \"and `ENDIF` come to pass.\\n\\n\"\n \"```godcode\\nIF faith > fear THEN\\n REVEAL(\\\"walk on\\\")\\nENDIF\\n```\"\n ),\n \"THEN\": (\n \"**THEN**\\n\\n\"\n \"Marks the start of the true branch after an `IF` condition. \"\n \"Closed by `ENDIF` (or `ELSE`).\\n\\n```godcode\\nIF x THEN\\n REVEAL(x)\\n\"\n \"ENDIF\\n```\"\n ),\n \"ELSE\": (\n \"**ELSE**\\n\\n\"\n \"The other path. When the `IF` condition proves false, these \"\n \"words come to pass instead.\\n\\n\"\n \"```godcode\\nIF x THEN\\n REVEAL(\\\"yes\\\")\\nELSE\\n\"\n \" REVEAL(\\\"no\\\")\\nENDIF\\n```\"\n ),\n \"ENDIF\": (\n \"**ENDIF**\\n\\n\"\n \"The seal upon an `IF` weighing. Every `IF` must be closed.\\n\\n\"\n \"```godcode\\nENDIF\\n```\"\n ),\n \"FOR\": (\n \"**FOR**\\n\\n\"\n \"Walk through every member of a list or range, naming each one \"\n \"in turn, until `ENDFOR`.\\n\\n\"\n \"```godcode\\nFOR tribe IN RANGE(12)\\n REVEAL(tribe)\\nENDFOR\\n```\"\n ),\n \"IN\": (\n \"**IN**\\n\\n\"\n \"The walking word. `FOR name IN list` binds each member in turn.\\n\\n\"\n \"```godcode\\nFOR star IN heavens\\n REVEAL(star)\\nENDFOR\\n```\"\n ),\n \"ENDFOR\": (\n \"**ENDFOR**\\n\\n\"\n \"The seal upon a `FOR` walk. Every journey must end.\\n\\n\"\n \"```godcode\\nENDFOR\\n```\"\n ),\n \"WHILE\": (\n \"**WHILE**\\n\\n\"\n \"Repeat the works between `DO` and `ENDWHILE` for as long as the \"\n \"condition holds true.\\n\\n\"\n \"```godcode\\nWHILE night < dawn DO\\n REVEAL(\\\"watch\\\")\\nENDWHILE\\n```\"\n ),\n \"DO\": (\n \"**DO**\\n\\n\"\n \"Marks the start of the repeated works in a `WHILE` loop.\\n\\n\"\n \"```godcode\\nWHILE x DO\\n REVEAL(x)\\nENDWHILE\\n```\"\n ),\n \"ENDWHILE\": (\n \"**ENDWHILE**\\n\\n\"\n \"The seal upon a `WHILE` vigil.\\n\\n```godcode\\nENDWHILE\\n```\"\n ),\n \"BREAK\": (\n \"**BREAK**\\n\\n\"\n \"Release the innermost enclosing `FOR` or `WHILE` loop at once. \"\n \"It can only be spoken within a loop.\\n\\n\"\n \"```godcode\\nFOR star IN heavens\\n IF star IS dim THEN\\n BREAK\\n ENDIF\\nENDFOR\\n```\"\n ),\n \"CONTINUE\": (\n \"**CONTINUE**\\n\\n\"\n \"Skip to the next turn of the innermost enclosing `FOR` or \"\n \"`WHILE` loop. It can only be spoken within a loop.\\n\\n\"\n \"```godcode\\nFOR n IN RANGE(10)\\n IF n % 2 IS 0 THEN\\n CONTINUE\\n ENDIF\\n REVEAL(n)\\nENDFOR\\n```\"\n ),\n \"TRY\": (\n \"**TRY**\\n\\n\"\n \"Open a sheltered work: if a runtime error rises inside, the \"\n \"`CATCH` block runs with the message bound to `ERROR` (or a name \"\n \"of your choosing). `RETURN` and `ASCEND` are never \"\n \"caught.\\n\\n```godcode\\nTRY\\n REVEAL(fragile_work())\\nCATCH\\n\"\n \" REVEAL(\\\"caught: {ERROR}\\\")\\nENDTRY\\n```\"\n ),\n \"CATCH\": (\n \"**CATCH**\\n\\n\"\n \"The refuge of a `TRY` block. Alone it binds the error's message \"\n \"to `ERROR`; `CATCH name` binds it to `name` instead.\\n\\n\"\n \"```godcode\\nCATCH trouble\\n REVEAL(trouble)\\n```\"\n ),\n \"ENDTRY\": (\n \"**ENDTRY**\\n\\n\"\n \"The seal upon a `TRY` … `CATCH` shelter.\\n\\n```godcode\\nENDTRY\\n```\"\n ),\n \"DEFINE\": (\n \"**DEFINE**\\n\\n\"\n \"The first word of a rite's establishment. Always paired with \"\n \"`RITE`. See `DEFINE RITE`.\\n\\n```godcode\\nDEFINE RITE bless()\\n\"\n \"END RITE\\n```\"\n ),\n \"RITE\": (\n \"**RITE**\\n\\n\"\n \"A named ceremony of statements. Paired with `DEFINE` to open \"\n \"and `END` to close. See `DEFINE RITE`.\\n\\n\"\n \"```godcode\\nDEFINE RITE bless()\\nEND RITE\\n```\"\n ),\n \"INVOKE\": (\n \"**INVOKE**\\n\\n\"\n \"Call a rite by name, offering it arguments in the ancient manner.\\n\\n\"\n \"```godcode\\nINVOKE bless(\\\"the meek\\\")\\n```\"\n ),\n \"RETURN\": (\n \"**RETURN**\\n\\n\"\n \"Offer a value back from a rite to the one who invoked it. \"\n \"A rite without `RETURN` yields the void.\\n\\n\"\n \"```godcode\\nRETURN manna * 2\\n```\"\n ),\n \"IMPORT\": (\n \"**IMPORT**\\n\\n\"\n \"Bring another scroll into this creation, that its works may \"\n \"serve here.\\n\\n```godcode\\nIMPORT \\\"psalms.god\\\"\\n```\"\n ),\n \"REVEAL\": (\n \"**REVEAL**\\n\\n\"\n \"Speak a value aloud. The scroll's voice, printing to the world \"\n \"beyond.\\n\\n```godcode\\nREVEAL(\\\"The heavens declare\\\")\\n```\"\n ),\n \"BREATHE\": (\n \"**BREATHE**\\n\\n\"\n \"The first word of awakening. Always `BREATHE LIFE INTO name`. \"\n \"See `BREATHE LIFE INTO`.\\n\\n\"\n \"```godcode\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n \"LIFE\": (\n \"**LIFE**\\n\\n\"\n \"The middle word of `BREATHE LIFE INTO`. The breath itself.\\n\\n\"\n \"```godcode\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n \"INTO\": (\n \"**INTO**\\n\\n\"\n \"The directing word of `BREATHE LIFE INTO name`.\\n\\n\"\n \"```godcode\\nBREATHE LIFE INTO vessel\\n```\"\n ),\n \"PROPHESY\": (\n \"**PROPHESY**\\n\\n\"\n \"Utter a fixed word into the scroll. A literal prophecy of text.\\n\\n\"\n \"```godcode\\nPROPHESY \\\"and it was good\\\"\\n```\"\n ),\n \"ASCEND\": (\n \"**ASCEND**\\n\\n\"\n \"End the run in peace. Nothing after `ASCEND` shall come to pass.\\n\\n\"\n \"```godcode\\nASCEND\\n```\"\n ),\n \"SEAL\": (\n \"**SEAL**\\n\\n\"\n \"Set a value under seal. It is recorded in the covenant ledger \"\n \"and may not be altered thereafter.\\n\\n```godcode\\nSEAL covenant\\n```\"\n ),\n # --- v4.0 ---\n \"ANCHOR\": (\n \"**ANCHOR**\\n\\n\"\n \"Anchor a value's hash on a chain: `ANCHOR(expr)` returns a receipt \"\n \"map `{chain, anchor_hash, height, timestamp, payload_hash}`. \"\n \"The default chain is `simulated` (a local tamper-evident chain); \"\n \"a second argument names another registered chain.\\n\\n\"\n \"```godcode\\nDECLARE seal AS ANCHOR(covenant)\\n```\"\n ),\n \"CONSULT\": (\n \"**CONSULT**\\n\\n\"\n \"Ask the local Spirit oracle a question; it answers with two to \"\n \"three sentences of counsel. No external calls.\\n\\n\"\n \"```godcode\\nREVEAL(CONSULT(\\\"How should I structure this covenant?\\\"))\\n```\"\n ),\n \"INTENT\": (\n \"**INTENT**\\n\\n\"\n \"The naming word of `DECLARE INTENT \\\"words...\\\" ON rite_name`. \"\n \"it registers a natural-language intent on a rite. When the rite \"\n \"is invoked, the Spirit discerns whether its words still walk in \"\n \"the declared intent, and counsels gently on drift.\\n\\n\"\n \"```godcode\\nDECLARE INTENT \\\"bring peace\\\" ON evening_blessing\\n```\"\n ),\n # --- end v4.0 ---\n \"TESTIFY\": (\n \"**TESTIFY**\\n\\n\"\n \"Bear witness to a value. Affirm it before the heavens.\\n\\n\"\n \"```godcode\\nTESTIFY manna > 0\\n```\"\n ),\n \"BLESS\": (\n \"**BLESS**\\n\\n\"\n \"Confer blessing upon a name, marking it favored.\\n\\n\"\n \"```godcode\\nBLESS the_meek\\n```\"\n ),\n \"ANOINT\": (\n \"**ANOINT**\\n\\n\"\n \"Anoint a name for a holy purpose, setting it apart.\\n\\n\"\n \"```godcode\\nANOINT the_chosen\\n```\"\n ),\n \"REFLECT\": (\n \"**REFLECT**\\n\\n\"\n \"Pause and contemplate. A still point in the works.\\n\\n\"\n \"```godcode\\nREFLECT\\n```\"\n ),\n \"AND\": (\n \"**AND**\\n\\n\"\n \"Join two truths; the whole holds only if both hold.\\n\\n\"\n \"```godcode\\nIF faith AND works THEN\\n```\"\n ),\n \"OR\": (\n \"**OR**\\n\\n\"\n \"Offer two truths; the whole holds if either holds.\\n\\n\"\n \"```godcode\\nIF mercy OR grace THEN\\n```\"\n ),\n \"NOT\": (\n \"**NOT**\\n\\n\"\n \"Turn a truth upon its head.\\n\\n```godcode\\nIF NOT fear THEN\\n```\"\n ),\n \"TRUE\": (\n \"**TRUE**\\n\\n\"\n \"The eternal yes.\\n\\n```godcode\\nDECLARE amen AS true\\n```\"\n ),\n \"FALSE\": (\n \"**FALSE**\\n\\n\"\n \"The eternal no.\\n\\n```godcode\\nDECLARE doubt AS false\\n```\"\n ),\n \"VOID\": (\n \"**VOID**\\n\\n\"\n \"The absence of all things. What a rite yields when it returns \"\n \"nothing.\\n\\n```godcode\\nDECLARE emptiness AS void\\n```\"\n ),\n \"IS\": (\n \"**IS**\\n\\n\"\n \"The weighing word. Reserved for divine comparisons.\\n\\n\"\n \"```godcode\\n# reserved\\n```\"\n ),\n \"END\": (\n \"**END**\\n\\n\"\n \"The closing word. Paired with `CREATION` or `RITE` to seal a \"\n \"block.\\n\\n```godcode\\nEND CREATION\\n```\"\n ),\n # -- built-ins -------------------------------------------------------\n \"LEN\": (\n \"**LEN**(value)\\n\\n\"\n \"Measure the length of a string or a list, and the number shall \"\n \"be revealed.\\n\\n```godcode\\nREVEAL(LEN(\\\"firmament\\\"))\\n```\"\n ),\n \"STR\": (\n \"**STR**(value)\\n\\n\"\n \"Turn anything into its spoken form. A string.\\n\\n\"\n \"```godcode\\nREVEAL(STR(40) + \\\" days\\\")\\n```\"\n ),\n \"NUM\": (\n \"**NUM**(value)\\n\\n\"\n \"Turn a string into a number, that it may be weighed and counted.\\n\\n\"\n \"```godcode\\nDECLARE years AS NUM(\\\"40\\\")\\n```\"\n ),\n \"TYPE\": (\n \"**TYPE**(value)\\n\\n\"\n \"Discern the kind of a thing. Its type, named aloud.\\n\\n\"\n \"```godcode\\nREVEAL(TYPE(manna))\\n```\"\n ),\n \"RANDOM\": (\n \"**RANDOM**(bound)\\n\\n\"\n \"Cast lots. Draw a whole number from 0 up to (but not including) \"\n \"`bound`.\\n\\n```godcode\\nDECLARE lot AS RANDOM(12)\\n```\"\n ),\n \"RANGE\": (\n \"**RANGE**(stop) / **RANGE**(start, stop)\\n\\n\"\n \"Number the days. Produce the sequence of whole numbers from \"\n \"0 (or `start`) up to `stop`.\\n\\n```godcode\\n\"\n \"FOR day IN RANGE(7)\\n REVEAL(day)\\nENDFOR\\n```\"\n ),\n \"PUSH\": (\n \"**PUSH**(list, value)\\n\\n\"\n \"Add to the multitude. Append `value` to the end of `list`.\\n\\n\"\n \"```godcode\\nPUSH(tribes, \\\"Benjamin\\\")\\n```\"\n ),\n \"UPPER\": (\n \"**UPPER**(text)\\n\\n\"\n \"Lift every letter to the heavens. Uppercase the string.\\n\\n\"\n \"```godcode\\nREVEAL(UPPER(\\\"hosanna\\\"))\\n```\"\n ),\n \"LOWER\": (\n \"**LOWER**(text)\\n\\n\"\n \"Humble every letter. Lowercase the string.\\n\\n\"\n \"```godcode\\nREVEAL(LOWER(\\\"HOSANNA\\\"))\\n```\"\n ),\n \"SPLIT\": (\n \"**SPLIT**(text, separator)\\n\\n\"\n \"Divide the word. Split `text` into a list at each `separator`.\\n\\n\"\n \"```godcode\\nDECLARE words AS SPLIT(\\\"loaves fishes\\\", \\\" \\\")\\n```\"\n ),\n \"JOIN\": (\n \"**JOIN**(list, separator)\\n\\n\"\n \"Gather the scattered. Join a list of strings with `separator`.\\n\\n\"\n \"```godcode\\nREVEAL(JOIN(words, \\\" \\\"))\\n```\"\n ),\n \"ASK\": (\n \"**ASK**([prompt])\\n\\n\"\n \"Seek counsel. Read a line from the one who runs the scroll.\\n\\n\"\n \"```godcode\\nDECLARE name AS ASK(\\\"What is your name? \\\")\\n```\"\n ),\n \"BEHOLD\": (\n \"**BEHOLD**()\\n\\n\"\n \"Mark the present hour. The current time, in the heavens' own \"\n \"notation.\\n\\n```godcode\\nREVEAL(BEHOLD())\\n```\"\n ),\n \"REVERSE\": (\n \"**REVERSE**(value)\\n\\n\"\n \"Turn it back upon itself. Reverse a string or a list.\\n\\n\"\n \"```godcode\\nREVEAL(REVERSE(\\\"stressed\\\"))\\n```\"\n ),\n \"SHA256\": (\n \"**SHA256**(value)\\n\\n\"\n \"Take a word's fingerprint. The SHA-256 digest as 64 hex \"\n \"characters. The same word always gives the same fingerprint.\\n\\n\"\n \"```godcode\\nREVEAL(SHA256(\\\"manna\\\"))\\n```\"\n ),\n \"HMAC\": (\n \"**HMAC**(key, message)\\n\\n\"\n \"Seal a message under a key. The HMAC-SHA-256 signature as 64 \"\n \"hex characters. Only a keeper of the key can make or verify \"\n \"the seal.\\n\\n\"\n \"```godcode\\nDECLARE sig AS HMAC(\\\"secret\\\", \\\"the covenant stands\\\")\\n```\"\n ),\n \"BASE64_ENCODE\": (\n \"**BASE64_ENCODE**(value)\\n\\n\"\n \"Veil a word in base64. The veiled text as a plain word.\\n\\n\"\n \"```godcode\\nREVEAL(BASE64_ENCODE(\\\"grace\\\"))\\n```\"\n ),\n \"BASE64_DECODE\": (\n \"**BASE64_DECODE**(text)\\n\\n\"\n \"Lift a base64 veil. The plain word behind it. A gentle error \"\n \"if the veil is ill-formed.\\n\\n\"\n \"```godcode\\nREVEAL(BASE64_DECODE(BASE64_ENCODE(\\\"grace\\\")))\\n```\"\n ),\n \"TRIM\": (\n \"**TRIM**(value)\\n\\n\"\n \"Lift away leading and trailing whitespace. The trimmed word.\\n\\n\"\n \"```godcode\\nREVEAL(TRIM(\\\" grace \\\"))\\n```\"\n ),\n \"REPLACE\": (\n \"**REPLACE**(word, old, new)\\n\\n\"\n \"Turn every occurrence of `old` into `new`. The renewed word.\\n\\n\"\n \"```godcode\\nREVEAL(REPLACE(\\\"manna, manna\\\", \\\"manna\\\", \\\"bread\\\"))\\n```\"\n ),\n \"STARTS_WITH\": (\n \"**STARTS_WITH**(word, part)\\n\\n\"\n \"Ask whether the word opens with the part. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(STARTS_WITH(\\\"dawn\\\", \\\"da\\\"))\\n```\"\n ),\n \"ENDS_WITH\": (\n \"**ENDS_WITH**(word, part)\\n\\n\"\n \"Ask whether the word closes with the part. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(ENDS_WITH(\\\"dawn\\\", \\\"wn\\\"))\\n```\"\n ),\n \"SUBSTRING\": (\n \"**SUBSTRING**(word, start [, end])\\n\\n\"\n \"Cut a slice from the word, counting from 0. Edges past the \"\n \"word are gathered in.\\n\\n\"\n \"```godcode\\nREVEAL(SUBSTRING(\\\"blessing\\\", 2, 6))\\n```\"\n ),\n \"CONTAINS\": (\n \"**CONTAINS**(word, part) / **CONTAINS**(list, value)\\n\\n\"\n \"Ask whether the word holds the part, or the list holds the \"\n \"value. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(CONTAINS(\\\"blessing\\\", \\\"sing\\\"))\\n```\"\n ),\n \"COUNT\": (\n \"**COUNT**(word, part)\\n\\n\"\n \"Count how many times the part appears in the word.\\n\\n\"\n \"```godcode\\nREVEAL(COUNT(\\\"banana\\\", \\\"an\\\"))\\n```\"\n ),\n \"REPEAT\": (\n \"**REPEAT**(word, times)\\n\\n\"\n \"Sing the word `times` times over. Zero gives an empty word.\\n\\n\"\n \"```godcode\\nREVEAL(REPEAT(\\\"Pula! \\\", 3))\\n```\"\n ),\n \"SORT\": (\n \"**SORT**(list)\\n\\n\"\n \"Order the gathering: numbers, words, or truths, least first. \"\n \"Returns a new list; the old one is untouched. Mixed kinds are \"\n \"gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(SORT([3, 1, 2]))\\n```\"\n ),\n \"MIN_OF\": (\n \"**MIN_OF**(list)\\n\\n\"\n \"The least member of the gathering. An empty gathering is \"\n \"gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(MIN_OF([3, 1, 2]))\\n```\"\n ),\n \"MAX_OF\": (\n \"**MAX_OF**(list)\\n\\n\"\n \"The greatest member of the gathering. An empty gathering is \"\n \"gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(MAX_OF([3, 1, 2]))\\n```\"\n ),\n \"SUM_OF\": (\n \"**SUM_OF**(list)\\n\\n\"\n \"Add the numbers together. An empty list sums to 0.\\n\\n\"\n \"```godcode\\nREVEAL(SUM_OF([1, 2, 3]))\\n```\"\n ),\n \"FIRST\": (\n \"**FIRST**(list)\\n\\n\"\n \"The member at the head of the gathering. An empty gathering \"\n \"is gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(FIRST([\\\"a\\\", \\\"b\\\"]))\\n```\"\n ),\n \"LAST\": (\n \"**LAST**(list)\\n\\n\"\n \"The member at the end of the gathering. An empty gathering \"\n \"is gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(LAST([\\\"a\\\", \\\"b\\\"]))\\n```\"\n ),\n \"UNIQUE\": (\n \"**UNIQUE**(list)\\n\\n\"\n \"The gathering with repeats removed, order kept.\\n\\n\"\n \"```godcode\\nREVEAL(UNIQUE([1, 2, 2, 3]))\\n```\"\n ),\n \"INDEX_OF\": (\n \"**INDEX_OF**(list, value)\\n\\n\"\n \"The position of the value, counting from 0, or -1 when it is \"\n \"absent.\\n\\n\"\n \"```godcode\\nREVEAL(INDEX_OF([\\\"a\\\", \\\"b\\\"], \\\"b\\\"))\\n```\"\n ),\n \"KEYS\": (\n \"**KEYS**(map)\\n\\n\"\n \"The map's keys, as a list.\\n\\n\"\n \"```godcode\\nREVEAL(KEYS(JSON_PARSE(\\\"{{\\\\\\\"a\\\\\\\": 1}}\\\")))\\n```\"\n ),\n \"VALUES\": (\n \"**VALUES**(map)\\n\\n\"\n \"The map's values, as a list.\\n\\n\"\n \"```godcode\\nREVEAL(VALUES(JSON_PARSE(\\\"{{\\\\\\\"a\\\\\\\": 1}}\\\")))\\n```\"\n ),\n \"HAS_KEY\": (\n \"**HAS_KEY**(map, key)\\n\\n\"\n \"Ask whether the map holds the key. True or false.\\n\\n\"\n \"```godcode\\nREVEAL(HAS_KEY(m, \\\"tribes\\\"))\\n```\"\n ),\n \"MERGE\": (\n \"**MERGE**(map1, map2)\\n\\n\"\n \"Weave two maps into a new one. Where both hold a key, the \"\n \"second map's value wins.\\n\\n\"\n \"```godcode\\nREVEAL(MERGE(m1, m2))\\n```\"\n ),\n \"ABS\": (\n \"**ABS**(number)\\n\\n\"\n \"The number's distance from zero, always positive.\\n\\n\"\n \"```godcode\\nREVEAL(ABS(-4))\\n```\"\n ),\n \"ROUND\": (\n \"**ROUND**(number [, places])\\n\\n\"\n \"Round half away from zero. `ROUND(2.5)` gives 3; give places \"\n \"to keep decimals.\\n\\n\"\n \"```godcode\\nREVEAL(ROUND(3.14159, 2))\\n```\"\n ),\n \"FLOOR\": (\n \"**FLOOR**(number)\\n\\n\"\n \"The whole number below.\\n\\n\"\n \"```godcode\\nREVEAL(FLOOR(3.9))\\n```\"\n ),\n \"CEIL\": (\n \"**CEIL**(number)\\n\\n\"\n \"The whole number above.\\n\\n\"\n \"```godcode\\nREVEAL(CEIL(3.1))\\n```\"\n ),\n \"SQRT\": (\n \"**SQRT**(number)\\n\\n\"\n \"The square root. A negative number is gently refused.\\n\\n\"\n \"```godcode\\nREVEAL(SQRT(144))\\n```\"\n ),\n \"POW\": (\n \"**POW**(base, exponent)\\n\\n\"\n \"Raise the base to the exponent.\\n\\n\"\n \"```godcode\\nREVEAL(POW(2, 10))\\n```\"\n ),\n}\n\n# Phrases matched as whole units on hover (case-insensitive).\n_PHRASES = (\"BEGIN CREATION\", \"END CREATION\", \"DEFINE RITE\", \"END RITE\",\n \"BREATHE LIFE INTO\")\n\n# Snippet-style completions: (label, insertText, detail).\n_SNIPPETS: tuple[tuple[str, str, str], ...] = (\n (\"BEGIN CREATION … END CREATION\",\n \"BEGIN CREATION\\n\\t$0\\nEND CREATION\",\n \"Open a new scroll\"),\n (\"DECLARE … AS …\", \"DECLARE ${1:name} AS ${2:value}$0\",\n \"Declare a vessel\"),\n (\"IF … THEN … ENDIF\",\n \"IF ${1:condition} THEN\\n\\t$0\\nENDIF\",\n \"Weigh a condition\"),\n (\"FOR … IN … ENDFOR\",\n \"FOR ${1:item} IN ${2:list}\\n\\t$0\\nENDFOR\",\n \"Walk a multitude\"),\n (\"WHILE … DO … ENDWHILE\",\n \"WHILE ${1:condition} DO\\n\\t$0\\nENDWHILE\",\n \"Keep a vigil\"),\n (\"TRY … CATCH … ENDTRY\",\n \"TRY\\n\\t${1:works}\\nCATCH\\n\\t${2:refuge}$0\\nENDTRY\",\n \"Shelter a fragile work\"),\n (\"DEFINE RITE … END RITE\",\n \"DEFINE RITE ${1:name}(${2:params})\\n\\t$0\\nEND RITE\",\n \"Establish a rite\"),\n (\"INVOKE …\", \"INVOKE ${1:name}(${2:args})$0\", \"Call a rite\"),\n)\n\n_WORD_RE = re.compile(r\"[^\\W\\d]\\w*\") # Unicode letters: dotted Igbo words hover too\n\n\n# ---------------------------------------------------------------------------\n# Diagnostics — the real parser, same as `godcode check`\n# ---------------------------------------------------------------------------\n\ndef check_source(text: str) -> list[dict]:\n \"\"\"Parse *text* and return LSP diagnostics (empty when pure).\"\"\"\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n try:\n parse_source(text)\n except GodCodeError as err:\n line = max((err.line or 1) - 1, 0) # LSP lines are 0-based\n lines = text.splitlines()\n line_len = len(lines[line]) if line < len(lines) else 0\n start_char = max((err.col or 1) - 1, 0)\n start_char = min(start_char, max(line_len - 1, 0))\n end_char = min(start_char + 1, line_len)\n return [{\n \"range\": {\n \"start\": {\"line\": line, \"character\": start_char},\n \"end\": {\"line\": line, \"character\": end_char},\n },\n \"severity\": 1, # Error\n \"source\": \"godcode\",\n \"message\": str(err),\n }]\n return []\n\n\n# ---------------------------------------------------------------------------\n# Hover\n# ---------------------------------------------------------------------------\n\ndef _phrase_at(line_text: str, char: int) -> str | None:\n upper = line_text.upper()\n for phrase in _PHRASES:\n start = 0\n while True:\n idx = upper.find(phrase, start)\n if idx < 0:\n break\n if idx <= char <= idx + len(phrase):\n return phrase\n start = idx + 1\n return None\n\n\ndef hover_word(line_text: str, char: int) -> str | None:\n \"\"\"Return the doc-table key under the cursor, or None.\"\"\"\n phrase = _phrase_at(line_text, char)\n if phrase is not None:\n return phrase\n for match in _WORD_RE.finditer(line_text):\n if match.start() <= char <= match.end():\n return match.group(0).upper()\n return None\n\n\ndef hover_markdown(word: str | None) -> str | None:\n if word is None:\n return None\n return LSP_DOCS.get(word)\n\n\n# ---------------------------------------------------------------------------\n# Tongues — the editor speaks the scroll's language\n# ---------------------------------------------------------------------------\n\ndef tongue_of(text: str) -> str | None:\n \"\"\"The tongue a document is written in, from its ``# tongue:`` pragma.\"\"\"\n from godcode.tongues import detect_tongue\n return detect_tongue(text)\n\n\ndef tongue_table(code: str | None) -> dict:\n \"\"\"The tongue table for *code*, or an empty table for English/unknown.\"\"\"\n if code in (None, \"en\"):\n return {}\n try:\n from godcode.tongues import resolve\n table = resolve(code)\n except Exception: # unknown tongue: English completions carry on\n return {}\n return table\n\n\ndef tongue_keyword_items(code: str) -> list[dict]:\n \"\"\"Completion items for a tongue's keywords, e.g. ``SENOLA (REVEAL)``.\"\"\"\n table = tongue_table(code)\n aliases = table.get(\"aliases\", {})\n name = table.get(\"name\", code)\n items = []\n for word in sorted(aliases):\n canonical = aliases[word]\n items.append({\n \"label\": f\"{word} ({canonical})\",\n \"kind\": 14, # Keyword\n \"detail\": f\"God Code keyword in {name}\",\n \"insertText\": word,\n })\n compounds = table.get(\"compounds\", {})\n for (first, second), canonical in sorted(compounds.items()):\n items.append({\n \"label\": f\"{first} {second} ({canonical})\",\n \"kind\": 14, # Keyword\n \"detail\": f\"God Code keyword in {name}\",\n \"insertText\": f\"{first} {second}\",\n })\n return items\n\n\ndef tongue_snippet_items(table: dict) -> list[dict]:\n \"\"\"Block snippets in the tongue, offered when the tongue is active.\n\n The snippet set travels with the tongue's own table in\n ``godcode.tongues``, so a new tongue brings its snippets with it.\n \"\"\"\n name = table.get(\"name\", \"\")\n return [{\n \"label\": label,\n \"kind\": 15, # Snippet\n \"detail\": f\"{detail} ({name})\",\n \"insertText\": insert,\n \"insertTextFormat\": 2, # Snippet\n } for label, insert, detail in table.get(\"snippets\", ())]\n\n\n_TONGUE_PHRASES = {\n (\"BEGIN\", \"CREATION\"): \"BEGIN CREATION\",\n (\"END\", \"CREATION\"): \"END CREATION\",\n (\"END\", \"RITE\"): \"END RITE\",\n (\"DEFINE\", \"RITE\"): \"DEFINE RITE\",\n}\n\n\ndef tongue_hover_key(line_text: str, char: int, code: str) -> str | None:\n \"\"\"The canonical English doc key under the cursor for a tongue word.\n\n Two-word closers (``FEDISA FA``) map to their doc key, openers like\n ``SIMOLOLA TLHOLEGO`` (Setswana) or ``QALA INDALO`` (isiZulu) map to\n ``BEGIN CREATION``, and single words map\n through the tongue's alias table. Returns None when the cursor is not\n on a tongue word.\n \"\"\"\n table = tongue_table(code)\n aliases = table.get(\"aliases\", {})\n compounds = table.get(\"compounds\", {})\n for match in _WORD_RE.finditer(line_text):\n if not (match.start() <= char <= match.end()):\n continue\n word = match.group(0).upper()\n if word not in aliases:\n return None\n canonical = aliases[word]\n rest = line_text[match.end():].lstrip()\n second = _WORD_RE.match(rest)\n if second is not None:\n upper2 = second.group(0).upper()\n key = (word, upper2)\n if key in compounds:\n return compounds[key]\n canonical2 = aliases.get(upper2)\n phrase = _TONGUE_PHRASES.get((canonical, canonical2))\n if phrase is not None:\n return phrase\n return canonical\n return None\n\n\n# ---------------------------------------------------------------------------\n# Completion\n# ---------------------------------------------------------------------------\n\n_COMPLETION_KEYWORDS = sorted(LSP_DOCS)\n_BUILTINS = (\"LEN\", \"STR\", \"NUM\", \"TYPE\", \"RANDOM\", \"RANGE\", \"PUSH\",\n \"UPPER\", \"LOWER\", \"SPLIT\", \"JOIN\", \"ASK\", \"BEHOLD\", \"REVERSE\",\n \"ANCHOR\", \"CONSULT\", \"SHA256\", \"HMAC\", \"BASE64_ENCODE\",\n \"BASE64_DECODE\", \"TRIM\", \"REPLACE\", \"STARTS_WITH\", \"ENDS_WITH\",\n \"SUBSTRING\", \"CONTAINS\", \"COUNT\", \"REPEAT\", \"SORT\", \"MIN_OF\",\n \"MAX_OF\",\n \"SUM_OF\", \"FIRST\", \"LAST\", \"UNIQUE\", \"INDEX_OF\", \"KEYS\",\n \"VALUES\", \"HAS_KEY\", \"MERGE\", \"ABS\", \"ROUND\", \"FLOOR\", \"CEIL\",\n \"SQRT\", \"POW\")\n\n\ndef completion_items(text: str = \"\") -> list[dict]:\n \"\"\"Keyword, built-in, and snippet completions.\n\n When *text* carries a ``# tongue:`` pragma, the tongue's keywords\n (e.g. ``SENOLA (REVEAL)``) and the tongue's snippets join the English\n ones, so a writer crossing over has both hands full.\n \"\"\"\n items: list[dict] = []\n for kw in _COMPLETION_KEYWORDS:\n items.append({\n \"label\": kw,\n \"kind\": 14, # Keyword\n \"detail\": \"God Code \" + (\"built-in\" if kw in _BUILTINS\n else \"keyword\"),\n \"insertText\": kw,\n })\n for label, insert, detail in _SNIPPETS:\n items.append({\n \"label\": label,\n \"kind\": 15, # Snippet\n \"detail\": detail,\n \"insertText\": insert,\n \"insertTextFormat\": 2, # Snippet\n })\n code = tongue_of(text)\n table = tongue_table(code)\n if table:\n items.extend(tongue_keyword_items(code))\n items.extend(tongue_snippet_items(table))\n return items\n\n\n# ---------------------------------------------------------------------------\n# The server\n# ---------------------------------------------------------------------------\n\ndef _log(message: str) -> None:\n sys.stderr.write(f\"[godcode-lsp] {message}\\n\")\n sys.stderr.flush()\n\n\nclass LanguageServer:\n \"\"\"Hand-rolled LSP server over stdio.\"\"\"\n\n def __init__(self,\n stdin: \"io.BufferedReader | None\" = None,\n stdout: \"io.BufferedWriter | None\" = None) -> None:\n import io\n self.stdin = stdin or sys.stdin.buffer\n self.stdout = stdout or sys.stdout.buffer\n self.documents: dict[str, str] = {}\n self._shutdown = False\n self._handlers = {\n \"initialize\": self._on_initialize,\n \"initialized\": self._on_initialized,\n \"shutdown\": self._on_shutdown,\n \"exit\": self._on_exit,\n \"textDocument/didOpen\": self._on_did_open,\n \"textDocument/didChange\": self._on_did_change,\n \"textDocument/hover\": self._on_hover,\n \"textDocument/completion\": self._on_completion,\n }\n\n # -- transport --------------------------------------------------------\n def _read_message(self) -> dict | None:\n \"\"\"Read one Content-Length framed message. None on clean EOF.\"\"\"\n headers: dict[str, str] = {}\n while True:\n line = self.stdin.readline()\n if not line:\n return None # EOF\n line = line.decode(\"latin-1\").strip()\n if not line:\n break\n if \":\" in line:\n name, _, value = line.partition(\":\")\n headers[name.strip().lower()] = value.strip()\n try:\n length = int(headers.get(\"content-length\", \"\"))\n except (TypeError, ValueError):\n _log(\"malformed frame: bad Content-Length; skipping\")\n return {}\n try:\n body = self._read_exact(length)\n except EOFError:\n _log(\"malformed frame: truncated body; skipping\")\n return {}\n try:\n return json.loads(body.decode(\"utf-8\"))\n except (UnicodeDecodeError, json.JSONDecodeError) as exc:\n _log(f\"malformed frame: {exc}; skipping\")\n return {}\n\n def _read_exact(self, length: int) -> bytes:\n body = b\"\"\n while len(body) < length:\n chunk = self.stdin.read(length - len(body))\n if not chunk:\n raise EOFError(\"truncated frame\")\n body += chunk\n return body\n\n def _write(self, payload: dict) -> None:\n body = json.dumps(payload, separators=(\",\", \":\")).encode(\"utf-8\")\n self.stdout.write(\n f\"Content-Length: {len(body)}\\r\\n\\r\\n\".encode(\"ascii\") + body)\n self.stdout.flush()\n\n def _notify(self, method: str, params: dict) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"method\": method, \"params\": params})\n\n def _respond(self, msg_id, result) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"id\": msg_id, \"result\": result})\n\n def _error(self, msg_id, code: int, message: str) -> None:\n self._write({\"jsonrpc\": \"2.0\", \"id\": msg_id,\n \"error\": {\"code\": code, \"message\": message}})\n\n # -- main loop ----------------------------------------------------------\n def serve(self) -> int:\n _log(\"the sanctuary opens (stdio)\")\n while True:\n message = self._read_message()\n if message is None:\n _log(\"stdin closed; ascending\")\n return 1 if not self._shutdown else 0\n if not message:\n continue # malformed frame: already logged, keep serving\n method = message.get(\"method\")\n handler = self._handlers.get(method) if method else None\n msg_id = message.get(\"id\")\n if handler is None:\n _log(f\"unknown method: {method!r}\")\n if msg_id is not None:\n self._error(msg_id, -32601,\n f\"Method not found: {method}\")\n continue\n try:\n stop = handler(msg_id, message.get(\"params\") or {})\n except Exception as exc: # never let a handler kill the server\n _log(f\"handler for {method} failed: {exc}\")\n if msg_id is not None:\n self._error(msg_id, -32603,\n f\"Internal error: {exc}\")\n continue\n if stop:\n return 0\n # pragma: no cover - unreachable\n\n # -- handlers -------------------------------------------------------------\n def _on_initialize(self, msg_id, params: dict) -> None: # noqa: ARG002\n _log(\"initialize received\")\n self._respond(msg_id, {\n \"capabilities\": {\n \"textDocumentSync\": 1, # Full\n \"hoverProvider\": True,\n \"completionProvider\": {\"triggerCharacters\": []},\n },\n \"serverInfo\": {\"name\": \"godcode-lsp\", \"version\": ENGINE_VERSION},\n })\n\n def _on_initialized(self, msg_id, params: dict) -> None: # noqa: ARG002\n _log(\"initialized; no-op\")\n\n def _on_shutdown(self, msg_id, params: dict) -> None: # noqa: ARG002\n _log(\"shutdown requested\")\n self._shutdown = True\n if msg_id is not None:\n self._respond(msg_id, None)\n\n def _on_exit(self, msg_id, params: dict) -> bool: # noqa: ARG002\n _log(\"exit; the sanctuary rests\")\n return True\n\n def _on_did_open(self, msg_id, params: dict) -> None: # noqa: ARG002\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n text = doc.get(\"text\", \"\")\n self.documents[uri] = text\n self._publish_diagnostics(uri, text)\n\n def _on_did_change(self, msg_id, params: dict) -> None: # noqa: ARG002\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n text = self.documents.get(uri, \"\")\n for change in params.get(\"contentChanges\", []):\n if \"range\" not in change: # full-document sync\n text = change.get(\"text\", \"\")\n self.documents[uri] = text\n self._publish_diagnostics(uri, text)\n\n def _publish_diagnostics(self, uri: str, text: str) -> None:\n diagnostics = check_source(text)\n _log(f\"diagnostics for {uri}: {len(diagnostics)} error(s)\")\n self._notify(\"textDocument/publishDiagnostics\",\n {\"uri\": uri, \"diagnostics\": diagnostics})\n\n def _on_hover(self, msg_id, params: dict) -> None:\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n pos = params.get(\"position\", {})\n line_no = pos.get(\"line\", 0)\n char = pos.get(\"character\", 0)\n text = self.documents.get(uri, \"\")\n lines = text.splitlines()\n line_text = lines[line_no] if 0 <= line_no < len(lines) else \"\"\n word = hover_word(line_text, char)\n canonical = word\n code = tongue_of(text)\n if code not in (None, \"en\"):\n tongue_key = tongue_hover_key(line_text, char, code)\n if tongue_key is not None:\n canonical = tongue_key\n markdown = hover_markdown(canonical)\n _log(f\"hover at {uri}:{line_no}:{char} -> {word!r}\"\n + (f\" (tongue {code}: {canonical!r})\" if canonical != word\n else \"\"))\n self._respond(msg_id, {\"contents\": {\"kind\": \"markdown\",\n \"value\": markdown}}\n if markdown else None)\n\n def _on_completion(self, msg_id, params: dict) -> None:\n doc = params.get(\"textDocument\", {})\n uri = doc.get(\"uri\", \"\")\n self._respond(msg_id, completion_items(self.documents.get(uri, \"\")))\n\n\ndef serve() -> int:\n \"\"\"Entry point for ``godcode lsp``.\"\"\"\n return LanguageServer().serve()\n","godcode/mcp.py":"\"\"\"The God Code MCP server -- ``godcode mcp``.\n\nSpeaks the Model Context Protocol over stdio (one JSON-RPC 2.0 message\nper line, the standard stdio transport) so any MCP client -- Claude Code,\nCursor, Codex, or any other agent host -- can check, run, explain,\nformat, and list God Code scrolls, and verify ledgers, without learning\na bespoke protocol.\n\nThe tools are the same eleven the agent bridge offers, plus one rule\nthat only holds here: **runs are always sandboxed**. An MCP client\ntalks to scrolls it did not write, so the server ignores any request\nto run outside the sandbox and says so in the result. The plain\n``godcode bridge`` keeps its own convention for hosts that already\ntrust their scrolls; this server never trusts them.\n\nNo third-party dependencies. Protocol versions are negotiated the way\nMCP asks: the client names the version it speaks, and the server\nanswers with that version when it knows it, or with the newest version\nit speaks when it does not.\n\"\"\"\nfrom __future__ import annotations\n\nimport json\n\nfrom godcode import tools as _tools\n\n#: Newest first. A client version outside this list gets the newest.\nSUPPORTED_PROTOCOL_VERSIONS = (\"2025-06-18\", \"2025-03-26\", \"2024-11-05\")\n\n_PARSE_ERROR = -32700\n_INVALID_REQUEST = -32600\n_METHOD_NOT_FOUND = -32601\n_INVALID_PARAMS = -32602\n_INTERNAL_ERROR = -32603\n\n\nclass _McpError(Exception):\n def __init__(self, code: int, message: str) -> None:\n super().__init__(message)\n self.code = code\n self.message = message\n\n\ndef _response_ok(req_id, result: dict) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id, \"result\": result}\n\n\ndef _response_err(req_id, code: int, message: str) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id,\n \"error\": {\"code\": code, \"message\": message}}\n\n\ndef negotiate_protocol_version(client_version) -> str:\n \"\"\"Answer an MCP initialize with a version both sides speak.\"\"\"\n if isinstance(client_version, str) \\\n and client_version in SUPPORTED_PROTOCOL_VERSIONS:\n return client_version\n return SUPPORTED_PROTOCOL_VERSIONS[0]\n\n\ndef _handle_initialize(params: dict) -> dict:\n from godcode import __version__\n\n return {\n \"protocolVersion\": negotiate_protocol_version(\n params.get(\"protocolVersion\")),\n \"capabilities\": {\"tools\": {}},\n \"serverInfo\": {\"name\": \"godcode\", \"version\": __version__},\n }\n\n\ndef call_mcp_tool(name: str, arguments: dict) -> dict:\n \"\"\"Run one tool the MCP way: runs are always sandboxed.\n\n Any ``sandbox: false`` on a run request is overruled, and the\n result says the run was sandboxed, so a client can never mistake\n an MCP run for an unsandboxed one.\n \"\"\"\n if name == \"run\":\n arguments = dict(arguments)\n arguments[\"sandbox\"] = True\n result = _tools.call_tool(name, arguments)\n result[\"sandbox\"] = True\n return result\n return _tools.call_tool(name, arguments)\n\n\ndef _handle_tools_call(params: dict) -> dict:\n name = params.get(\"name\")\n arguments = params.get(\"arguments\", {})\n if not isinstance(name, str):\n raise _McpError(_INVALID_PARAMS, \"tools/call needs 'name' as a string\")\n if not isinstance(arguments, dict):\n raise _McpError(_INVALID_PARAMS, \"'arguments' must be an object\")\n result = call_mcp_tool(name, arguments)\n payload = {\"content\": [{\"type\": \"text\",\n \"text\": json.dumps(result, ensure_ascii=False)}]}\n if not result.get(\"ok\", True):\n payload[\"isError\"] = True\n return payload\n\n\ndef _dispatch(method: str, params: dict):\n if method == \"initialize\":\n return _handle_initialize(params)\n if method == \"ping\":\n return {}\n if method == \"tools/list\":\n return {\"tools\": _tools.TOOL_SCHEMAS}\n if method == \"tools/call\":\n return _handle_tools_call(params)\n if method == \"resources/list\":\n return {\"resources\": []}\n if method == \"prompts/list\":\n return {\"prompts\": []}\n raise _McpError(_METHOD_NOT_FOUND, f\"no such method '{method}'\")\n\n\ndef handle_message(message: dict):\n \"\"\"Answer one parsed MCP message, or None when no answer is owed.\n\n Notifications (no ``id``) never get an answer, whatever method\n they carry. Anything malformed raises _McpError.\n \"\"\"\n if not isinstance(message, dict) or \"method\" not in message:\n raise _McpError(_INVALID_REQUEST, \"a request needs a 'method'\")\n if \"id\" not in message:\n return None\n params = message.get(\"params\", {})\n if not isinstance(params, dict):\n raise _McpError(_INVALID_PARAMS, \"'params' must be an object\")\n return _dispatch(message[\"method\"], params)\n\n\ndef cmd_mcp(args) -> int: # noqa: ARG001\n \"\"\"Serve the MCP server: JSON-RPC 2.0 over stdio, one message per line.\n\n Stdout carries exactly one protocol message per line. Tool work\n runs muted, so an engine print can never land in the stream: the\n response is written only after handling returns.\n \"\"\"\n import contextlib\n import io\n import sys\n\n stdin, stdout = sys.stdin, sys.stdout\n for line in stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n stdout.write(json.dumps(_response_err(None, _PARSE_ERROR,\n \"the request was not JSON\"))\n + \"\\n\")\n stdout.flush()\n continue\n req_id = request.get(\"id\") if isinstance(request, dict) else None\n try:\n with contextlib.redirect_stdout(io.StringIO()):\n result = handle_message(request)\n except _McpError as err:\n response = _response_err(req_id, err.code, err.message)\n except Exception as exc: # pragma: no cover - defensive\n response = _response_err(req_id, _INTERNAL_ERROR,\n f\"the server faltered: {exc!r}\")\n else:\n if result is None:\n continue\n response = _response_ok(req_id, result)\n stdout.write(json.dumps(response, ensure_ascii=False) + \"\\n\")\n stdout.flush()\n return 0\n","godcode/parser.py":"\"\"\"Recursive-descent parser for God Code v2.0.\n\n``Parser(tokens).parse()`` returns a ``Program``. A program is either a\n``BEGIN CREATION ... END CREATION`` block (wrapped in a Program) or a\nbare sequence of statements (for scrolls / fragments).\n\nStatement forms (spec §4):\n- DECLARE name AS expr (, expr)* -> Declare (multi-expr -> ListLiteral)\n- BREATHE LIFE INTO name -> Breathe\n- REVEAL(expr) -> Reveal\n- PROPHESY -> Prophesy\n- ASCEND / REFLECT -> Ascend / Reflect\n- BLESS name / ANOINT name -> Bless / Anoint\n- SEAL expr / TESTIFY expr -> SealStmt / Testify\n- IF expr THEN ... (block: ENDIF / inline) -> IfStmt\n- FOR name IN expr ... (block: ENDFOR / legacy open / inline) -> ForLoop\n- WHILE expr DO ... (block: ENDWHILE / inline) -> WhileLoop\n- TRY ... CATCH [name] ... ENDTRY (block) -> TryStmt\n- DEFINE RITE name(params) ... END RITE (block or inline) -> DefineRite\n- RETURN expr? -> Return\n- IMPORT \"path\" -> Import\n- INVOKE name(args) | any expression -> CallExpr / ExprStmt\n\nExpression precedence (low -> high):\n or -> and -> not -> comparison (IS [NOT], =, ==, !=, <, >, <=, >=)\n -> additive (+ -) -> multiplicative (* / %) -> unary (-, NOT) -> primary\n``IS``/``IS NOT`` become ``==``/``!=`` BinaryOps.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom . import ast as A\nfrom .errors import ParseError\nfrom .lexer import Lexer\nfrom .tokens import Token, TokenType\n\nTT = TokenType\n\n_EXPR_STARTS = {\n TT.NUMBER, TT.STRING, TT.IDENT, TT.LPAREN, TT.LBRACKET,\n TT.MINUS, TT.NOT, TT.TRUE, TT.FALSE, TT.VOID, TT.INVOKE,\n}\n\n# Tokens after which RETURN takes no expression.\n_RETURN_TERMINATORS = {\n TT.NEWLINE, TT.EOF, TT.END, TT.ENDIF, TT.ELSE, TT.ENDFOR, TT.ENDWHILE,\n TT.CATCH, TT.ENDTRY,\n}\n\n\nclass Parser:\n def __init__(self, tokens: list[Token], tongue: str | None = None):\n if not tokens:\n raise ParseError(\"The scroll is empty; there is nothing to reveal\")\n self.tokens = tokens\n self.pos = 0\n # The tongue the source was lexed in (\"en\" when none); carried into\n # interpolated {expressions} so their keywords speak it too.\n self._tongue = tongue or \"en\"\n # Tracks lexically enclosing FOR/WHILE loops so BREAK and CONTINUE\n # can be rejected at parse time when no loop holds them. A rite\n # body resets this to 0: loop signals never cross a rite boundary.\n self._loop_depth = 0\n\n # -- public ------------------------------------------------------------\n\n def parse(self) -> A.Program:\n self._skip_newlines()\n first = self._peek()\n if self._check(TT.BEGIN):\n block = self._parse_creation_block()\n self._skip_newlines()\n t = self._peek()\n if t.type is not TT.EOF:\n raise ParseError(\n f\"The creation is sealed, yet {self._describe(t)} remains; \"\n \"a scroll holds only one creation\",\n line=t.line, col=t.col,\n )\n return A.Program(statements=[block], line=block.line, col=block.col)\n stmts = self._parse_body(\n end={TT.EOF},\n missing=\"the end of the scroll\",\n opening=None,\n )\n return A.Program(statements=stmts, line=first.line, col=first.col)\n\n # -- cursor helpers ----------------------------------------------------\n\n def _peek(self) -> Token:\n return self.tokens[self.pos]\n\n def _peek_next(self) -> Token:\n if self.pos + 1 < len(self.tokens):\n return self.tokens[self.pos + 1]\n return self.tokens[-1]\n\n def _advance(self) -> Token:\n t = self.tokens[self.pos]\n if self.pos < len(self.tokens) - 1:\n self.pos += 1\n return t\n\n def _check(self, tt: TokenType) -> bool:\n return self._peek().type is tt\n\n def _expect(self, tt: TokenType, what: str | None = None) -> Token:\n t = self._peek()\n if t.type is not tt:\n raise ParseError(\n f\"Expected {what or tt.name} but found {self._describe(t)}\",\n line=t.line, col=t.col,\n )\n return self._advance()\n\n def _skip_newlines(self) -> None:\n while self._check(TT.NEWLINE):\n self._advance()\n\n @staticmethod\n def _describe(t: Token) -> str:\n if t.type is TT.EOF:\n return \"the end of the scroll\"\n if t.type is TT.NEWLINE:\n return \"the end of the line\"\n if t.type is TT.IDENT:\n return f\"the name '{t.value}'\"\n if t.type is TT.NUMBER:\n return f\"the number {t.value!r}\"\n if t.type is TT.STRING:\n return f\"the text {t.value!r}\"\n return f\"'{t.value}'\"\n\n # -- statement lists ---------------------------------------------------\n\n def _parse_body(self, *, end: set[TokenType], missing: str,\n opening: Token | None, legacy_for: bool = False) -> list:\n \"\"\"Parse statements until a token in ``end`` (left unconsumed).\n\n With ``legacy_for``, END CREATION / END RITE / EOF also end the body\n without being consumed (the original sample.godcode's open FOR).\n Otherwise hitting them raises ParseError naming what was missing.\n \"\"\"\n stmts: list = []\n while True:\n self._skip_newlines()\n t = self._peek()\n if t.type in end:\n return stmts\n if t.type is TT.EOF:\n if legacy_for:\n return stmts\n raise ParseError(\n f\"The scroll ends before {missing}; \"\n + (f\"the {opening.value} opened on line {opening.line} \"\n \"was never closed\" if opening else\n \"every opened block must be closed\"),\n line=t.line, col=t.col,\n )\n if t.type is TT.END and self._peek_next().type in (TT.CREATION, TT.RITE):\n if legacy_for:\n return stmts\n raise ParseError(\n f\"Found {t.value} {self._peek_next().value} before {missing}; \"\n \"every opened block must be closed in its own time\",\n line=t.line, col=t.col,\n )\n stmts.append(self._parse_statement())\n\n # -- top level ---------------------------------------------------------\n\n def _parse_creation_block(self) -> A.CreationBlock:\n b = self._expect(TT.BEGIN)\n self._expect(TT.CREATION)\n self._skip_newlines()\n stmts = self._parse_body(end={TT.END}, missing=\"END CREATION\", opening=b)\n self._expect(TT.END)\n self._expect(TT.CREATION)\n return A.CreationBlock(statements=stmts, line=b.line, col=b.col)\n\n # -- statements --------------------------------------------------------\n\n def _parse_statement(self):\n t = self._peek()\n tt = t.type\n if tt is TT.DECLARE:\n return self._parse_declare()\n if tt is TT.BREATHE:\n return self._parse_breathe()\n if tt is TT.REVEAL:\n return self._parse_reveal()\n if tt is TT.PROPHESY:\n return self._parse_prophesy()\n if tt is TT.ASCEND:\n self._advance()\n return A.Ascend(line=t.line, col=t.col)\n if tt is TT.REFLECT:\n self._advance()\n return A.Reflect(line=t.line, col=t.col)\n if tt is TT.BLESS:\n return self._parse_named_single(TT.BLESS, A.Bless)\n if tt is TT.ANOINT:\n return self._parse_named_single(TT.ANOINT, A.Anoint)\n if tt is TT.SEAL:\n self._advance()\n return A.SealStmt(expr=self._parse_expr(), line=t.line, col=t.col)\n if tt is TT.TESTIFY:\n self._advance()\n return A.Testify(expr=self._parse_expr(), line=t.line, col=t.col)\n if tt is TT.IF:\n return self._parse_if()\n if tt is TT.FOR:\n return self._parse_for()\n if tt is TT.WHILE:\n return self._parse_while()\n if tt is TT.BREAK:\n return self._parse_break()\n if tt is TT.CONTINUE:\n return self._parse_continue()\n if tt is TT.TRY:\n return self._parse_try()\n if tt is TT.DEFINE:\n return self._parse_define_rite()\n if tt is TT.RETURN:\n return self._parse_return()\n if tt is TT.IMPORT:\n return self._parse_import()\n if tt in _EXPR_STARTS:\n expr = self._parse_expr()\n return A.ExprStmt(expr=expr, line=t.line, col=t.col)\n raise ParseError(\n f\"Unexpected {self._describe(t)}; a decree must begin with \"\n \"a holy word (DECLARE, IF, FOR, REVEAL, ...)\",\n line=t.line, col=t.col,\n )\n\n def _parse_named_single(self, tt: TokenType, node_cls):\n kw = self._expect(tt)\n name = self._expect(TT.IDENT, \"a name\").value\n return node_cls(name=name, line=kw.line, col=kw.col)\n\n def _parse_declare(self) -> A.Declare:\n d = self._expect(TT.DECLARE)\n # --- v4.0: DECLARE INTENT \"words...\" ON rite_name ---\n # INTENT and ON are soft keywords (plain identifiers by text), so\n # `DECLARE intent AS x` keeps working: only DECLARE followed by the\n # word INTENT and then a quoted string takes the intent path.\n nxt, nxt2 = self._peek(), self._peek_next()\n if (nxt.type is TT.IDENT and nxt.value.upper() == \"INTENT\"\n and nxt2.type is TT.STRING):\n self._advance() # the word INTENT\n text = self._expect(TT.STRING, \"the intent in quotes\").value\n on = self._peek()\n if not (on.type is TT.IDENT and on.value.upper() == \"ON\"):\n raise ParseError(\n 'DECLARE INTENT needs ON and a rite name, as in '\n 'DECLARE INTENT \"bring peace\" ON evening_blessing',\n line=on.line, col=on.col,\n )\n self._advance() # the word ON\n rite = self._expect(TT.IDENT, \"a rite name\").value\n return A.DeclareIntent(text=text, rite=rite, line=d.line, col=d.col)\n # --- permission manifests: DECLARE PERMISSION TO ---\n # PERMISSION and TO are soft keywords (plain identifiers by text), so\n # `DECLARE permission AS x` keeps working: only DECLARE followed by\n # the word PERMISSION takes the manifest path.\n if (nxt.type is TT.IDENT and nxt.value.upper() == \"PERMISSION\"\n and nxt2.type is TT.IDENT and nxt2.value.upper() == \"TO\"):\n return self._parse_declare_permission(d)\n # --- end permission manifests ---\n name = self._expect(TT.IDENT, \"a name to declare\").value\n self._expect(TT.AS)\n items = [self._parse_expr()]\n while self._check(TT.COMMA):\n self._advance()\n items.append(self._parse_expr())\n if len(items) == 1:\n value = items[0]\n else:\n value = A.ListLiteral(items=items, line=items[0].line, col=items[0].col)\n return A.Declare(name=name, value=value, line=d.line, col=d.col)\n\n def _parse_declare_permission(self, d) -> A.DeclarePermission:\n \"\"\"Parse DECLARE PERMISSION TO -- the permission manifest.\"\"\"\n self._advance() # the word PERMISSION\n self._advance() # the word TO\n line, col = d.line, d.col\n\n def word_is(text: str) -> bool:\n t = self._peek()\n return t.type is TT.IDENT and t.value.upper() == text\n\n def eat_word(text: str) -> None:\n t = self._peek()\n if not (t.type is TT.IDENT and t.value.upper() == text):\n raise ParseError(\n f\"DECLARE PERMISSION TO expects the word {text} here, \"\n f\"as in DECLARE PERMISSION TO {text} ...\",\n line=t.line, col=t.col,\n )\n self._advance()\n\n def eat_string(what: str) -> str:\n return self._expect(TT.STRING, what).value\n\n if word_is(\"READ\"):\n self._advance()\n return A.DeclarePermission(\n power=\"read\",\n target=eat_string('a path in quotes, as in DECLARE PERMISSION TO READ \"data/\"'),\n line=line, col=col,\n )\n if word_is(\"WRITE\"):\n self._advance()\n return A.DeclarePermission(\n power=\"write\",\n target=eat_string('a path in quotes, as in DECLARE PERMISSION TO WRITE \"out/\"'),\n line=line, col=col,\n )\n if word_is(\"SPEAK\"):\n self._advance()\n eat_word(\"WITH\")\n return A.DeclarePermission(\n power=\"network\",\n target=eat_string('a host in quotes, as in DECLARE PERMISSION TO SPEAK WITH \"api.example.com\"'),\n line=line, col=col,\n )\n if word_is(\"ASK\"):\n self._advance()\n eat_word(\"THE\")\n eat_word(\"WORLD\")\n return A.DeclarePermission(power=\"stdin\", target=None, line=line, col=col)\n if word_is(\"SUMMON\"):\n self._advance()\n return A.DeclarePermission(\n power=\"summon\",\n target=eat_string('a verb name in quotes, as in DECLARE PERMISSION TO SUMMON \"reports.weekly\"'),\n line=line, col=col,\n )\n t = self._peek()\n raise ParseError(\n \"DECLARE PERMISSION TO grants one power: READ a path, WRITE a \"\n \"path, SPEAK WITH a host, ASK THE WORLD, or SUMMON a verb. \"\n f\"I heard '{t.value}'.\",\n line=t.line, col=t.col,\n )\n\n def _parse_breathe(self) -> A.Breathe:\n b = self._expect(TT.BREATHE)\n self._expect(TT.LIFE)\n self._expect(TT.INTO)\n name = self._expect(TT.IDENT, \"a name to breathe into\").value\n return A.Breathe(name=name, line=b.line, col=b.col)\n\n def _parse_reveal(self) -> A.Reveal:\n r = self._expect(TT.REVEAL)\n self._expect(TT.LPAREN)\n expr = self._parse_expr()\n self._expect(TT.RPAREN)\n return A.Reveal(expr=expr, line=r.line, col=r.col)\n\n def _parse_prophesy(self) -> A.Prophesy:\n p = self._expect(TT.PROPHESY)\n line_no = p.line\n parts: list[str] = []\n while True:\n t = self._peek()\n if t.type in (TT.NEWLINE, TT.EOF) or t.line != line_no:\n break\n parts.append(str(t.value))\n self._advance()\n return A.Prophesy(text=\" \".join(parts), line=p.line, col=p.col)\n\n def _parse_if(self) -> A.IfStmt:\n i = self._expect(TT.IF)\n cond = self._parse_expr()\n self._expect(TT.THEN)\n if self._check(TT.NEWLINE):\n self._skip_newlines()\n then_body = self._parse_body(end={TT.ENDIF, TT.ELSE},\n missing=\"ENDIF\", opening=i)\n else_body: list = []\n has_else = False\n if self._check(TT.ELSE):\n self._advance()\n has_else = True\n self._skip_newlines()\n else_body = self._parse_body(end={TT.ENDIF},\n missing=\"ENDIF\", opening=i)\n self._expect(TT.ENDIF)\n else:\n then_body = [self._parse_statement()]\n else_body = []\n has_else = False\n if self._check(TT.ELSE):\n self._advance()\n has_else = True\n else_body = [self._parse_statement()]\n return A.IfStmt(cond=cond, then_body=then_body, else_body=else_body,\n has_else=has_else, line=i.line, col=i.col)\n\n def _parse_for(self) -> A.ForLoop:\n f = self._expect(TT.FOR)\n var = self._expect(TT.IDENT, \"a name for the traveler\").value\n self._expect(TT.IN)\n iterable = self._parse_expr()\n self._loop_depth += 1\n try:\n if self._check(TT.NEWLINE):\n body = self._parse_body(end={TT.ENDFOR}, missing=\"ENDFOR\",\n opening=f, legacy_for=True)\n if self._check(TT.ENDFOR):\n self._advance()\n else:\n body = [self._parse_statement()]\n finally:\n self._loop_depth -= 1\n return A.ForLoop(var=var, iterable=iterable, body=body,\n line=f.line, col=f.col)\n\n def _parse_while(self) -> A.WhileLoop:\n w = self._expect(TT.WHILE)\n cond = self._parse_expr()\n self._expect(TT.DO)\n self._loop_depth += 1\n try:\n if self._check(TT.NEWLINE):\n body = self._parse_body(end={TT.ENDWHILE}, missing=\"ENDWHILE\",\n opening=w)\n self._expect(TT.ENDWHILE)\n else:\n body = [self._parse_statement()]\n finally:\n self._loop_depth -= 1\n return A.WhileLoop(cond=cond, body=body, line=w.line, col=w.col)\n\n def _parse_break(self) -> A.Break:\n b = self._advance()\n if self._loop_depth == 0:\n raise ParseError(\n \"BREAK can only be used inside a loop. It was spoken with \"\n \"no cycle to release. Place it within a FOR or a WHILE.\",\n line=b.line, col=b.col,\n )\n return A.Break(line=b.line, col=b.col)\n\n def _parse_continue(self) -> A.Continue:\n c = self._advance()\n if self._loop_depth == 0:\n raise ParseError(\n \"CONTINUE can only be used inside a loop. It was spoken with \"\n \"no cycle to turn. Place it within a FOR or a WHILE.\",\n line=c.line, col=c.col,\n )\n return A.Continue(line=c.line, col=c.col)\n\n def _parse_try(self) -> A.TryStmt:\n t = self._expect(TT.TRY)\n if not self._check(TT.NEWLINE):\n raise ParseError(\n \"TRY opens a block: place its works on the following lines, \"\n \"then CATCH ... ENDTRY\",\n line=t.line, col=t.col,\n )\n self._skip_newlines()\n try_body = self._parse_body(end={TT.CATCH}, missing=\"CATCH\", opening=t)\n self._expect(TT.CATCH)\n if self._check(TT.IDENT):\n error_name = self._advance().value\n else:\n error_name = \"ERROR\"\n self._skip_newlines()\n catch_body = self._parse_body(end={TT.ENDTRY}, missing=\"ENDTRY\",\n opening=t)\n self._expect(TT.ENDTRY)\n return A.TryStmt(try_body=try_body, catch_body=catch_body,\n error_name=error_name, line=t.line, col=t.col)\n\n def _parse_define_rite(self) -> A.DefineRite:\n d = self._expect(TT.DEFINE)\n self._expect(TT.RITE)\n name = self._expect(TT.IDENT, \"a name for the rite\").value\n self._expect(TT.LPAREN)\n params: list[str] = []\n if not self._check(TT.RPAREN):\n params.append(self._expect(TT.IDENT, \"a parameter name\").value)\n while self._check(TT.COMMA):\n self._advance()\n params.append(self._expect(TT.IDENT, \"a parameter name\").value)\n self._expect(TT.RPAREN)\n # A rite body is a fresh boundary: BREAK/CONTINUE inside it may only\n # answer to loops within the rite, never to a caller's loop.\n saved_depth, self._loop_depth = self._loop_depth, 0\n try:\n if self._check(TT.NEWLINE):\n self._skip_newlines()\n body = self._parse_body(end={TT.END}, missing=\"END RITE\", opening=d)\n else:\n # inline single-statement body, e.g. DEFINE RITE f(x) SEAL x END RITE\n body = [self._parse_statement()]\n self._skip_newlines()\n finally:\n self._loop_depth = saved_depth\n self._expect(TT.END)\n self._expect(TT.RITE)\n return A.DefineRite(name=name, params=params, body=body,\n line=d.line, col=d.col)\n\n def _parse_return(self) -> A.Return:\n r = self._expect(TT.RETURN)\n if self._peek().type in _RETURN_TERMINATORS:\n return A.Return(expr=None, line=r.line, col=r.col)\n return A.Return(expr=self._parse_expr(), line=r.line, col=r.col)\n\n def _parse_import(self) -> A.Import:\n im = self._expect(TT.IMPORT)\n path = self._expect(TT.STRING, \"a scroll path in quotes\").value\n return A.Import(path=path, line=im.line, col=im.col)\n\n # -- expressions -------------------------------------------------------\n\n def _parse_expr(self):\n return self._parse_or()\n\n def _parse_or(self):\n left = self._parse_and()\n while self._check(TT.OR):\n op = self._advance()\n right = self._parse_and()\n left = A.BinaryOp(op=\"or\", left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_and(self):\n left = self._parse_not_low()\n while self._check(TT.AND):\n op = self._advance()\n right = self._parse_not_low()\n left = A.BinaryOp(op=\"and\", left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_not_low(self):\n if self._check(TT.NOT):\n op = self._advance()\n return A.UnaryOp(op=\"not\", operand=self._parse_not_low(),\n line=op.line, col=op.col)\n return self._parse_comparison()\n\n _COMPARISON_OPS = {\n TT.EQ: \"==\", TT.NEQ: \"!=\", TT.LT: \"<\",\n TT.GT: \">\", TT.LTE: \"<=\", TT.GTE: \">=\",\n }\n\n def _parse_comparison(self):\n left = self._parse_additive()\n while True:\n t = self._peek()\n if t.type is TT.IS:\n self._advance()\n if self._check(TT.NOT):\n self._advance()\n op = \"!=\"\n else:\n op = \"==\"\n elif t.type in self._COMPARISON_OPS:\n self._advance()\n op = self._COMPARISON_OPS[t.type]\n else:\n break\n right = self._parse_additive()\n left = A.BinaryOp(op=op, left=left, right=right,\n line=t.line, col=t.col)\n return left\n\n def _parse_additive(self):\n left = self._parse_multiplicative()\n while self._peek().type in (TT.PLUS, TT.MINUS):\n op = self._advance()\n right = self._parse_multiplicative()\n left = A.BinaryOp(op=op.value, left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_multiplicative(self):\n left = self._parse_unary()\n while self._peek().type in (TT.STAR, TT.SLASH, TT.PERCENT):\n op = self._advance()\n right = self._parse_unary()\n left = A.BinaryOp(op=op.value, left=left, right=right,\n line=op.line, col=op.col)\n return left\n\n def _parse_unary(self):\n t = self._peek()\n if t.type is TT.MINUS:\n self._advance()\n return A.UnaryOp(op=\"-\", operand=self._parse_unary(),\n line=t.line, col=t.col)\n if t.type is TT.NOT:\n self._advance()\n return A.UnaryOp(op=\"not\", operand=self._parse_unary(),\n line=t.line, col=t.col)\n return self._parse_postfix()\n\n def _parse_postfix(self):\n obj = self._parse_primary()\n while self._check(TT.LBRACKET):\n lb = self._advance()\n index = self._parse_expr()\n self._expect(TT.RBRACKET)\n obj = A.Index(obj=obj, index=index, line=lb.line, col=lb.col)\n return obj\n\n def _parse_primary(self):\n t = self._peek()\n tt = t.type\n if tt is TT.NUMBER:\n self._advance()\n return A.Literal(value=t.value, line=t.line, col=t.col)\n if tt is TT.STRING:\n self._advance()\n if \"{\" in t.value or \"}}\" in t.value:\n return self._parse_interpolated(t)\n return A.Literal(value=t.value, line=t.line, col=t.col)\n if tt is TT.TRUE:\n self._advance()\n return A.Literal(value=True, line=t.line, col=t.col)\n if tt is TT.FALSE:\n self._advance()\n return A.Literal(value=False, line=t.line, col=t.col)\n if tt is TT.VOID:\n self._advance()\n return A.Literal(value=None, line=t.line, col=t.col)\n if tt is TT.IDENT:\n self._advance()\n if self._check(TT.LPAREN):\n self._advance()\n args = self._parse_args()\n self._expect(TT.RPAREN)\n return A.CallExpr(callee=t.value, args=args,\n line=t.line, col=t.col)\n return A.Identifier(name=t.value, line=t.line, col=t.col)\n if tt is TT.INVOKE:\n self._advance()\n name = self._expect(TT.IDENT, \"a rite name\").value\n self._expect(TT.LPAREN)\n args = self._parse_args()\n self._expect(TT.RPAREN)\n return A.CallExpr(callee=name, args=args, line=t.line, col=t.col)\n if tt is TT.LPAREN:\n self._advance()\n expr = self._parse_expr()\n self._expect(TT.RPAREN)\n return expr\n if tt is TT.LBRACKET:\n self._advance()\n items = []\n if not self._check(TT.RBRACKET):\n items.append(self._parse_expr())\n while self._check(TT.COMMA):\n self._advance()\n items.append(self._parse_expr())\n self._expect(TT.RBRACKET)\n return A.ListLiteral(items=items, line=t.line, col=t.col)\n raise ParseError(\n f\"Expected a value or name but found {self._describe(t)}\",\n line=t.line, col=t.col,\n )\n\n # -- string interpolation: \"grace upon {name}\" ----------------------------\n\n def _parse_interpolated(self, tok):\n \"\"\"Build an InterpolatedString from a STRING token's value.\n\n ``{expr}`` breathes the expression's revealed value into the string;\n ``{{`` and ``}}`` write a plain brace; a lone ``}`` stays a plain brace.\n \"\"\"\n src = tok.value\n parts: list = []\n buf: list[str] = []\n i, n = 0, len(src)\n while i < n:\n ch = src[i]\n if ch == \"{\" and src[i + 1 : i + 2] == \"{\":\n buf.append(\"{\")\n i += 2\n continue\n if ch == \"}\" and src[i + 1 : i + 2] == \"}\":\n buf.append(\"}\")\n i += 2\n continue\n if ch == \"{\":\n end = self._find_interpolation_end(src, i, tok)\n inner = src[i + 1 : end]\n if not inner.strip():\n raise ParseError(\n \"empty braces breathe nothing into the string; \"\n \"place a name or an expression between '{' and '}', \"\n \"or write '{{}}' for plain braces\",\n line=tok.line, col=tok.col + i,\n )\n if buf:\n parts.append(\"\".join(buf))\n buf = []\n parts.append(self._parse_braced_expr(inner, tok, i))\n i = end + 1\n continue\n buf.append(ch)\n i += 1\n if buf:\n parts.append(\"\".join(buf))\n return A.InterpolatedString(parts=parts, source=src,\n line=tok.line, col=tok.col)\n\n @staticmethod\n def _find_interpolation_end(src: str, start: int, tok) -> int:\n \"\"\"Index of the ``}`` closing the ``{`` at ``start``.\n\n Nested braces count toward the depth, and braces inside a quoted\n string are skipped, so ``\"{greet(\"hi {name}\")}\"`` seals correctly.\n \"\"\"\n depth = 0\n in_string = False\n i, n = start, len(src)\n while i < n:\n c = src[i]\n if in_string:\n if c == \"\\\\\":\n i += 2\n continue\n if c == '\"':\n in_string = False\n elif c == '\"':\n in_string = True\n elif c == \"{\":\n depth += 1\n elif c == \"}\":\n depth -= 1\n if depth == 0:\n return i\n i += 1\n raise ParseError(\n \"an opening '{' breathes a blessing that was never sealed; \"\n \"close it with '}' or write '{{' for a plain brace\",\n line=tok.line, col=tok.col + start,\n )\n\n def _parse_braced_expr(self, inner: str, tok, offset: int):\n \"\"\"Parse the text between one pair of braces as a single expression.\"\"\"\n tokens = [t for t in Lexer(inner, tongue=self._tongue).lex()\n if t.type not in (TT.NEWLINE, TT.EOF)]\n tokens.append(Token(TT.EOF, \"\", tok.line, tok.col + offset))\n sub = Parser(tokens)\n expr = sub._parse_expr()\n if not sub._check(TT.EOF):\n raise ParseError(\n \"the blessing between '{' and '}' could not be understood; \"\n \"only one expression may dwell there\",\n line=tok.line, col=tok.col + offset,\n )\n return expr\n\n def _parse_args(self) -> list:\n args = []\n if not self._check(TT.RPAREN):\n args.append(self._parse_expr())\n while self._check(TT.COMMA):\n self._advance()\n args.append(self._parse_expr())\n return args\n","godcode/permissions.py":"\"\"\"Permission manifests for God Code.\n\nA scroll may declare what it is allowed to touch:\n\n DECLARE PERMISSION TO READ \"data/\"\n DECLARE PERMISSION TO WRITE \"out/\"\n DECLARE PERMISSION TO SPEAK WITH \"api.example.com\"\n DECLARE PERMISSION TO ASK THE WORLD\n DECLARE PERMISSION TO SUMMON \"reports.weekly\"\n\nThe manifest is collected from the scroll's top-level decrees before the\nrun begins. It never widens what the host allows: the effective grant is\nalways *host policy intersect manifest*. A scroll that reaches for a\npower it did not declare is counselled and stopped with a\n``SandboxViolation``.\n\nImported scrolls contribute their own manifests; grants compose by union\n(a run may use any power granted by any scroll it breathes in). Relative\npath patterns are resolved against the directory of the scroll that\ndeclares them.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any\nfrom urllib.parse import urlparse\n\n__all__ = [\n \"PermissionManifest\",\n \"collect_manifest\",\n \"POWERS\",\n]\n\n# The five declared powers, in the order they read in counsel.\nPOWERS = (\"read\", \"write\", \"network\", \"stdin\", \"summon\")\n\n# AST node class name we collect from, so this module never imports the\n# parser or interpreter (no import cycles).\n_DECLARE_PERMISSION_NODE = \"DeclarePermission\"\n\n\ndef _node_is_permission(stmt: Any) -> bool:\n return type(stmt).__name__ == _DECLARE_PERMISSION_NODE\n\n\n@dataclass\nclass PermissionManifest:\n \"\"\"The declared powers of one scroll or one whole run.\n\n Path patterns are stored as absolute directory prefixes. A pattern\n naming a file grants that exact file; a pattern naming a directory\n grants everything beneath it.\n \"\"\"\n\n read_paths: tuple[str, ...] = ()\n write_paths: tuple[str, ...] = ()\n hosts: tuple[str, ...] = ()\n stdin: bool = False\n summons: tuple[str, ...] = ()\n\n def __bool__(self) -> bool:\n return bool(\n self.read_paths\n or self.write_paths\n or self.hosts\n or self.stdin\n or self.summons\n )\n\n # -- composition ----------------------------------------------------\n\n def merge(self, other: \"PermissionManifest\") -> \"PermissionManifest\":\n \"\"\"Union two manifests: grants only ever grow by import.\"\"\"\n def _union(a: tuple[str, ...], b: tuple[str, ...]) -> tuple[str, ...]:\n seen: list[str] = []\n for item in (*a, *b):\n if item not in seen:\n seen.append(item)\n return tuple(seen)\n\n return PermissionManifest(\n read_paths=_union(self.read_paths, other.read_paths),\n write_paths=_union(self.write_paths, other.write_paths),\n hosts=_union(self.hosts, other.hosts),\n stdin=self.stdin or other.stdin,\n summons=_union(self.summons, other.summons),\n )\n\n # -- enforcement ----------------------------------------------------\n\n @staticmethod\n def _under(path: str, granted: tuple[str, ...]) -> bool:\n try:\n resolved = os.path.realpath(path)\n except OSError:\n return False\n for base in granted:\n if resolved == base or resolved.startswith(base + os.sep):\n return True\n return False\n\n def allows_read(self, path: str) -> bool:\n return self._under(path, self.read_paths)\n\n def allows_write(self, path: str) -> bool:\n return self._under(path, self.write_paths)\n\n def allows_host(self, url: str) -> bool:\n try:\n host = (urlparse(url).hostname or \"\").lower()\n except (ValueError, AttributeError):\n return False\n return any(host == granted or host.endswith(\".\" + granted)\n for granted in self.hosts)\n\n def allows_summon(self, verb: str) -> bool:\n return any(verb == name or verb.startswith(name + \".\")\n for name in self.summons)\n\n # -- machine interfaces ----------------------------------------------\n\n def to_json(self) -> dict:\n \"\"\"Stable shape for agents: `godcode permissions --json`.\"\"\"\n return {\n \"read\": list(self.read_paths),\n \"write\": list(self.write_paths),\n \"network\": list(self.hosts),\n \"stdin\": self.stdin,\n \"summon\": list(self.summons),\n }\n\n def describe(self) -> list[str]:\n \"\"\"One human line per granted power, for counsel and CLI output.\"\"\"\n lines: list[str] = []\n for path in self.read_paths:\n lines.append(f\"may read from {path}\")\n for path in self.write_paths:\n lines.append(f\"may write to {path}\")\n for host in self.hosts:\n lines.append(f\"may speak with {host}\")\n if self.stdin:\n lines.append(\"may ask the outer world\")\n for name in self.summons:\n lines.append(f\"may summon {name}\")\n return lines\n\n\ndef collect_manifest(statements: list, base_dir: str | Path | None) -> PermissionManifest:\n \"\"\"Gather DECLARE PERMISSION decrees from top-level statements.\n\n Looks at the scroll's top level and inside any top-level creation\n blocks. ``base_dir`` resolves relative path patterns to absolute\n prefixes; ``None`` resolves them against the current working\n directory.\n \"\"\"\n base = Path(base_dir) if base_dir else Path.cwd()\n reads: list[str] = []\n writes: list[str] = []\n hosts: list[str] = []\n stdin = False\n summons: list[str] = []\n\n def _resolve(pattern: str) -> str:\n candidate = Path(pattern)\n if not candidate.is_absolute():\n candidate = base / candidate\n try:\n return os.path.realpath(candidate)\n except OSError: # pragma: no cover - defensive\n return str(candidate)\n\n def _visit(stmts: list, inside_block: bool) -> None:\n nonlocal stdin\n for stmt in stmts:\n if _node_is_permission(stmt):\n power = getattr(stmt, \"power\", \"\")\n target = getattr(stmt, \"target\", None)\n if power == \"read\" and target:\n reads.append(_resolve(target))\n elif power == \"write\" and target:\n writes.append(_resolve(target))\n elif power == \"network\" and target:\n hosts.append(target.strip().lower())\n elif power == \"stdin\":\n stdin = True\n elif power == \"summon\" and target:\n summons.append(target.strip())\n elif (not inside_block\n and type(stmt).__name__ == \"CreationBlock\"):\n _visit(getattr(stmt, \"statements\", []), True)\n\n _visit(statements, False)\n\n def _dedupe(items: list[str]) -> tuple[str, ...]:\n seen: list[str] = []\n for item in items:\n if item not in seen:\n seen.append(item)\n return tuple(seen)\n\n return PermissionManifest(\n read_paths=_dedupe(reads),\n write_paths=_dedupe(writes),\n hosts=_dedupe(hosts),\n stdin=stdin,\n summons=_dedupe(summons),\n )\n","godcode/plugins.py":"\"\"\"Pillar 3 — plugins and the SUMMON foreign-function interface.\n\nA plugin is a plain Python module living in a plugins directory. On load it\nexposes::\n\n PLUGIN_API_VERSION = 1\n\n def register(interpreter):\n interpreter.register_plugin_verb(\"myns.myverb\", myverb, plugin=\"myns\")\n\nThe interpreter calls ``register(interpreter)`` at startup, so the plugin can\nadd new built-in verbs through the same ``_builtins`` mechanism the v2 core\nverbs use. God Code calls those verbs through the ``SUMMON`` FFI verb::\n\n SUMMON(\"myns.myverb\", arg1, arg2)\n\nPlugins are **trusted host code**: they run with the full power of Python,\nand SUMMON calls into them bypass any sandbox policy *by design*. Every\nplugin verb is recorded with ``trusted=True`` on the interpreter\n(``interpreter.plugin_verb_info``) so a future sandbox pillar can consult the\nmarker when deciding what a scroll may touch.\n\nSet ``GODCODE_NO_PLUGINS=1`` in the environment to skip plugin auto-loading\nentirely.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib.metadata\nimport importlib.util\nimport os\nimport re\nimport sys\nimport types\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nfrom godcode.values import Contract, RiteFunction, Symbol # noqa: F401 (re-exported for plugin authors)\n\nPLUGIN_API_VERSION = 1\n\"\"\"Version of the plugin contract this engine speaks.\"\"\"\n\nENTRY_POINT_GROUP = \"godcode_plugins\"\n\"\"\"importlib.metadata entry-point group for installed plugins (best-effort).\"\"\"\n\nDISABLE_ENV_VAR = \"GODCODE_NO_PLUGINS\"\n\"\"\"Set to \"1\" to skip plugin auto-loading entirely.\"\"\"\n\n\n# ---------------------------------------------------------------------------\n# discovery\n# ---------------------------------------------------------------------------\n\ndef default_plugin_dirs() -> list[Path]:\n \"\"\"Where plugins are looked for: ``./plugins`` then ``~/.godcode/plugins``.\"\"\"\n dirs = [Path.cwd() / \"plugins\"]\n try:\n dirs.append(Path.home() / \".godcode\" / \"plugins\")\n except Exception: # pragma: no cover - exotic platforms without a home\n pass\n return dirs\n\n\ndef _warn(message: str) -> None:\n print(f\"godcode: plugin warning: {message}\", file=sys.stderr)\n\n\ndef _iter_plugin_files(dirs: list[Path]):\n \"\"\"Yield ``(stem, path)`` for each candidate plugin file in *dirs*.\"\"\"\n for directory in dirs:\n try:\n if not directory.is_dir():\n continue\n entries = sorted(directory.iterdir())\n except OSError as exc:\n _warn(f\"cannot scan {directory}: {exc}\")\n continue\n for path in entries:\n if not path.is_file() or path.suffix != \".py\":\n continue\n stem = path.stem\n if stem == \"__init__\" or stem.startswith((\"_\", \".\")):\n continue\n yield stem, path\n\n\ndef _module_name_for(stem: str) -> str:\n safe = re.sub(r\"[^0-9a-zA-Z_]\", \"_\", stem)\n if not safe or safe[0].isdigit():\n safe = \"_\" + safe\n return f\"godcode_plugin_{safe}\"\n\n\ndef _import_from_path(stem: str, path: Path) -> types.ModuleType:\n \"\"\"Import the module at *path* without touching ``sys.path``.\"\"\"\n name = _module_name_for(stem)\n spec = importlib.util.spec_from_file_location(name, path)\n if spec is None or spec.loader is None: # pragma: no cover - defensive\n raise ImportError(f\"cannot build a module spec for {path}\")\n module = importlib.util.module_from_spec(spec)\n # NOTE: deliberately *not* cached in sys.modules — each interpreter gets a\n # freshly executed plugin module, so plugin state never leaks between runs.\n spec.loader.exec_module(module)\n return module\n\n\ndef _entry_point_plugins() -> dict[str, Any]:\n \"\"\"Best-effort load of the ``godcode_plugins`` entry-point group.\"\"\"\n found: dict[str, Any] = {}\n try:\n entry_points = importlib.metadata.entry_points()\n except Exception as exc: # pragma: no cover - metadata backend missing\n _warn(f\"could not read entry points: {exc}\")\n return found\n try:\n if hasattr(entry_points, \"select\"): # Python 3.10+ EntryPoints\n selected = entry_points.select(group=ENTRY_POINT_GROUP)\n else: # pragma: no cover - legacy dict-style interface\n selected = entry_points.get(ENTRY_POINT_GROUP, ())\n except Exception as exc:\n _warn(f\"could not select {ENTRY_POINT_GROUP!r} entry points: {exc}\")\n return found\n for ep in selected:\n try:\n found[ep.name] = ep.load()\n except Exception as exc:\n _warn(f\"entry-point plugin {ep.name!r} failed to load: {exc}\")\n return found\n\n\ndef discover_plugins(dirs: list[Path] | None = None) -> dict[str, Any]:\n \"\"\"Import every plugin module found and return ``{name: module}``.\n\n *dirs* defaults to :func:`default_plugin_dirs`, with the\n ``godcode_plugins`` entry-point group consulted afterwards (later sources\n shadow earlier ones on name clashes).\n\n A module that fails to import is skipped with a warning on stderr — a\n broken plugin never crashes the host run.\n \"\"\"\n if dirs is None:\n dirs = default_plugin_dirs()\n discovered: dict[str, Any] = {}\n for stem, path in _iter_plugin_files(dirs):\n try:\n discovered[stem] = _import_from_path(stem, path)\n except Exception as exc:\n _warn(f\"plugin {path} failed to import ({exc}). Skipped\")\n for name, module in _entry_point_plugins().items():\n discovered[name] = module\n return discovered\n\n\ndef load_plugins(interpreter, dirs: list[Path] | None = None) -> list[str]:\n \"\"\"Discover plugins and call ``register(interpreter)`` on each.\n\n Returns the names of the plugins whose ``register()`` ran cleanly. A\n missing ``register()``, a ``PLUGIN_API_VERSION`` mismatch, or an\n exception inside ``register()`` only produces a stderr warning — never\n an exception, so startup always survives a bad plugin.\n \"\"\"\n loaded: list[str] = []\n for name, module in discover_plugins(dirs).items():\n api = getattr(module, \"PLUGIN_API_VERSION\", 1)\n if api != PLUGIN_API_VERSION:\n _warn(\n f\"plugin {name!r} speaks API version {api}, \"\n f\"this engine speaks {PLUGIN_API_VERSION}. Skipped\"\n )\n continue\n register = getattr(module, \"register\", None)\n if not callable(register):\n _warn(f\"plugin {name!r} exposes no register(interpreter). Skipped\")\n continue\n try:\n register(interpreter)\n except Exception as exc:\n _warn(f\"plugin {name!r} register() failed ({exc}). Skipped\")\n continue\n loaded.append(name)\n return loaded\n\n\n# ---------------------------------------------------------------------------\n# value conversion: God Code <-> Python\n# ---------------------------------------------------------------------------\n#\n# God Code values already *are* Python objects inside the interpreter, so most\n# conversions are the identity. The table below is the contract plugin\n# authors can rely on:\n#\n# God Code number <-> Python int / float (identity)\n# God Code string <-> Python str (identity)\n# God Code boolean <-> Python bool (identity)\n# God Code void <-> Python None (identity)\n# God Code list <-> Python list (recursive)\n# God Code symbol <-> Symbol, a str subclass (identity)\n# God Code contract <-> Contract (opaque, identity)\n# God Code rite <-> RiteFunction (opaque, identity)\n#\n# Anything else a plugin returns (dict, set, tuple, custom objects, ...)\n# passes through opaquely, except tuples which become lists recursively.\n# REVEAL renders opaque values with str().\n\ndef to_python(value: Any) -> Any:\n \"\"\"Convert a God Code value to the Python value a plugin receives.\n\n Identity for every documented God Code value; see the table above.\n \"\"\"\n return value\n\n\ndef to_godcode(value: Any) -> Any:\n \"\"\"Convert a plugin's Python return value back into a God Code value.\n\n Tuples become lists (recursively); every other value passes through\n as-is. Values with no God Code counterpart (dicts, sets, custom\n objects) travel opaquely and are rendered with ``str()`` by REVEAL.\n \"\"\"\n if isinstance(value, tuple):\n return [to_godcode(item) for item in value]\n if isinstance(value, list):\n return [to_godcode(item) for item in value]\n return value\n\n\n# ---------------------------------------------------------------------------\n# interpreter mixin helpers (kept here so interpreter.py stays small)\n# ---------------------------------------------------------------------------\n\ndef make_verb_adapter(name: str, func: Callable[..., Any]):\n \"\"\"Wrap a plain ``func(*args)`` into the ``(args, line)`` builtin shape.\n\n Arguments are converted God Code -> Python, the return value Python ->\n God Code. A plugin exception becomes a line-numbered GodRuntimeError;\n divine errors pass through untouched.\n \"\"\"\n from godcode.errors import GodCodeError, GodRuntimeError\n\n def _adapter(args: list, line):\n py_args = [to_python(arg) for arg in args]\n try:\n result = func(*py_args)\n except GodCodeError:\n raise\n except Exception as exc:\n raise GodRuntimeError(\n f\"The '{name}' verb faltered in the outer world: {exc}\",\n line,\n ) from exc\n return to_godcode(result)\n\n _adapter.__name__ = f\"plugin:{name}\"\n _adapter.__doc__ = getattr(func, \"__doc__\", None)\n return _adapter\n","godcode/registry.py":"\"\"\"Pillar 2 — the Scroll Registry: installable, versioned God Code scrolls.\n\nA scroll is a directory holding a ``scroll.toml`` manifest beside its entry\n``.god`` file. The local registry (``registry/`` at the repo root) is the\nsource of truth: ``publish`` copies a scroll into\n``registry/scrolls///`` and records it in\n``registry/index.json``; ``install`` copies from there into\n``~/.godcode/scrolls///`` (user-global) or\n``.godcode/scrolls/`` (project-local, wins over user-global).\n\nrequires-python is >=3.10, so ``tomllib`` (3.11+) is off the table: the\nmanifest parser below is a hand-rolled TOML subset covering exactly the\nkeys this registry defines.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nimport os\nimport re\nimport shutil\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nfrom typing import Any, Optional\n\ntry: # the package version is the engine version; tolerate odd import orders\n from godcode import __version__ as ENGINE_VERSION\nexcept Exception: # pragma: no cover - defensive\n ENGINE_VERSION = \"2.0.0\"\n\n# ---------------------------------------------------------------------------\n# errors\n\n\nclass ScrollError(Exception):\n \"\"\"Raised when a manifest, publish, install, or lookup fails.\"\"\"\n\n\nclass ScrollNotFoundError(ScrollError):\n \"\"\"Raised when a scroll cannot be found in a registry.\n\n Kept distinct from ScrollError so the CLI can fall back from the local\n registry to the remote one on exactly this failure.\n \"\"\"\n\n\n# ---------------------------------------------------------------------------\n# manifest parsing (TOML subset: key = \"value\" pairs, # comments)\n\n\nMANIFEST_KEYS = frozenset(\n {\"name\", \"version\", \"author\", \"description\", \"entry\", \"godcode\",\n \"dependencies\"}\n)\nREQUIRED_KEYS = frozenset(\n {\"name\", \"version\", \"author\", \"description\", \"entry\", \"godcode\"}\n) # dependencies is optional\n_NAME_RE = re.compile(r\"^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$\")\n_SEMVER_RE = re.compile(r\"^(\\d+)\\.(\\d+)\\.(\\d+)$\")\n_REQ_CLAUSE_RE = re.compile(r\"^(>=|<=|==|!=|>|<)\\s*(\\d+(?:\\.\\d+){0,2})$\")\n\n# Human-readable blurbs shown in errors; keep them short.\n_KEY_HINTS = {\n \"name\": 'e.g. name = \"json-tools\"',\n \"version\": 'e.g. version = \"1.0.0\"',\n \"author\": 'e.g. author = \"Ama Seretse\"',\n \"description\": 'e.g. description = \"JSON helpers written in God Code\"',\n \"entry\": 'e.g. entry = \"json-tools.god\"',\n \"godcode\": 'e.g. godcode = \">=2.0\"',\n \"dependencies\": 'e.g. dependencies = \"json-tools >= 1.0.0, dates\"',\n}\n\n\ndef _strip_comment(line: str) -> str:\n \"\"\"Cut a trailing ``#`` comment, ignoring ``#`` inside quoted strings.\"\"\"\n in_quote: str | None = None\n i = 0\n while i < len(line):\n ch = line[i]\n if in_quote:\n if ch == \"\\\\\" and in_quote == '\"':\n i += 2\n continue\n if ch == in_quote:\n in_quote = None\n elif ch in ('\"', \"'\"):\n in_quote = ch\n elif ch == \"#\":\n return line[:i]\n i += 1\n return line\n\n\ndef _parse_toml_value(raw: str, source: str, lineno: int) -> str:\n \"\"\"Parse a quoted TOML string value (double- or single-quoted).\"\"\"\n if len(raw) >= 2 and raw[0] == '\"' and raw[-1] == '\"':\n out: list[str] = []\n i = 1\n while i < len(raw) - 1:\n ch = raw[i]\n if ch == \"\\\\\":\n i += 1\n if i >= len(raw) - 1:\n raise ScrollError(\n f\"{source}:{lineno}: dangling backslash in manifest value\"\n )\n esc = raw[i]\n out.append({\"n\": \"\\n\", \"t\": \"\\t\", \"r\": \"\\r\"}.get(esc, esc))\n else:\n out.append(ch)\n i += 1\n return \"\".join(out)\n if len(raw) >= 2 and raw[0] == \"'\" and raw[-1] == \"'\":\n return raw[1:-1] # literal string: no escapes\n raise ScrollError(\n f\"{source}:{lineno}: manifest values must be quoted strings \"\n f\"(got {raw!r})\"\n )\n\n\ndef parse_manifest(text: str, source: str = \"\") -> dict[str, str]:\n \"\"\"Parse and validate a ``scroll.toml`` manifest. Returns a plain dict.\"\"\"\n data: dict[str, str] = {}\n for lineno, raw_line in enumerate(text.splitlines(), 1):\n line = _strip_comment(raw_line).strip()\n if not line:\n continue\n if \"=\" not in line:\n raise ScrollError(\n f\"{source}:{lineno}: expected `key = \\\"value\\\"`, got {line!r}\"\n )\n key, _, value = line.partition(\"=\")\n key, value = key.strip(), value.strip()\n if not re.fullmatch(r\"[A-Za-z_][A-Za-z0-9_-]*\", key):\n raise ScrollError(f\"{source}:{lineno}: bad manifest key {key!r}\")\n if key in data:\n raise ScrollError(\n f\"{source}:{lineno}: duplicate manifest key {key!r}\"\n )\n data[key] = _parse_toml_value(value, source, lineno)\n\n unknown = sorted(set(data) - MANIFEST_KEYS)\n if unknown:\n raise ScrollError(\n f\"{source}: unknown manifest key(s) {', '.join(unknown)}; \"\n \"known keys: \" + \", \".join(sorted(MANIFEST_KEYS))\n )\n missing = sorted(REQUIRED_KEYS - set(data))\n if missing:\n hints = \"; \".join(_KEY_HINTS[k] for k in missing)\n raise ScrollError(\n f\"{source}: missing required manifest key(s) \"\n f\"{', '.join(missing)} ({hints})\"\n )\n\n name = data[\"name\"]\n if not _NAME_RE.match(name):\n raise ScrollError(\n f\"{source}: name {name!r} must be lowercase letters, digits and \"\n \"hyphens, starting with a letter\"\n )\n parse_semver(data[\"version\"], source=source) # validates\n entry = data[\"entry\"]\n if not entry or \"/\" in entry or \"\\\\\" in entry or entry.startswith(\".\"):\n raise ScrollError(\n f\"{source}: entry must be a plain filename, got {entry!r}\"\n )\n req = data[\"godcode\"]\n if not requirement_satisfied(req):\n raise ScrollError(\n f\"{source}: this scroll needs God Code {req}, \"\n f\"but the engine is {ENGINE_VERSION}\"\n )\n if \"dependencies\" in data:\n parse_dependencies(data[\"dependencies\"], source=source)\n return data\n\n\ndef read_manifest(path: str | os.PathLike) -> dict[str, str]:\n \"\"\"Read, parse, and validate the manifest at ``path``.\"\"\"\n path = Path(path)\n try:\n text = path.read_text(encoding=\"utf-8\")\n except OSError as exc:\n raise ScrollError(f\"cannot read manifest {path}: {exc}\") from exc\n return parse_manifest(text, source=str(path))\n\n\n# ---------------------------------------------------------------------------\n# semver-ish versions (X.Y.Z only)\n\n\ndef parse_semver(text: str, source: str = \"\") -> tuple[int, int, int]:\n \"\"\"Parse ``X.Y.Z``; raise ScrollError on anything else.\"\"\"\n match = _SEMVER_RE.match(text.strip())\n if not match:\n raise ScrollError(\n f\"{source}: version must look like X.Y.Z, got {text!r}\"\n )\n return int(match.group(1)), int(match.group(2)), int(match.group(3))\n\n\ndef compare_versions(a: str, b: str) -> int:\n \"\"\"-1 if a < b, 0 if equal, 1 if a > b (numeric per component).\"\"\"\n ta, tb = parse_semver(a), parse_semver(b)\n return (ta > tb) - (ta < tb)\n\n\ndef latest_version(versions: list[str]) -> str:\n \"\"\"The highest version; ties are impossible (versions are unique).\"\"\"\n if not versions:\n raise ScrollError(\"no versions to choose from\")\n best = versions[0]\n for v in versions[1:]:\n if compare_versions(v, best) > 0:\n best = v\n return best\n\n\n# ---------------------------------------------------------------------------\n# godcode version requirements, e.g. \">=2.0, <4\"\n\n\ndef _parse_requirement(req: str) -> list[tuple[str, tuple[int, ...]]]:\n clauses: list[tuple[str, tuple[int, ...]]] = []\n for part in req.split(\",\"):\n part = part.strip()\n if not part:\n raise ScrollError(f\"bad godcode requirement {req!r}: empty clause\")\n match = _REQ_CLAUSE_RE.match(part)\n if not match:\n raise ScrollError(\n f\"bad godcode requirement {req!r}: expected e.g. \"\n f\"'>=2.0', got {part!r}\"\n )\n op, ver = match.group(1), match.group(2)\n clauses.append((op, tuple(int(x) for x in ver.split(\".\"))))\n return clauses\n\n\ndef _pad(parts: tuple[int, ...], length: int) -> tuple[int, ...]:\n return parts + (0,) * (length - len(parts))\n\n\ndef _clauses_satisfied(\n req: str, engine: str, clauses: list[tuple[str, tuple[int, ...]]]\n) -> bool:\n engine_parts = _pad(tuple(int(x) for x in engine.split(\".\")), 3)\n for op, want in clauses:\n want = _pad(want, 3)\n if op == \">=\" and not (engine_parts >= want):\n return False\n if op == \"<=\" and not (engine_parts <= want):\n return False\n if op == \"==\" and not (engine_parts == want):\n return False\n if op == \"!=\" and not (engine_parts != want):\n return False\n if op == \">\" and not (engine_parts > want):\n return False\n if op == \"<\" and not (engine_parts < want):\n return False\n return True\n\n\ndef requirement_satisfied(req: str, engine: str = ENGINE_VERSION) -> bool:\n \"\"\"True when ``engine`` satisfies a requirement like ``>=2.0``.\"\"\"\n return _clauses_satisfied(req, engine, _parse_requirement(req))\n\n\n# ---------------------------------------------------------------------------\n# scroll dependencies, e.g. dependencies = \"json-tools >= 1.0.0, dates\"\n\n\ndef parse_dependencies(\n spec: str, source: str = \"\"\n) -> list[tuple[str, str | None]]:\n \"\"\"Parse a manifest ``dependencies`` value.\n\n Returns ``[(name, requirement)]``; requirement is None when the clause\n names the scroll with no version constraint. A clause carries at most\n one requirement clause (``>= 1.0.0``); commas separate dependencies.\n \"\"\"\n if not spec.strip():\n return []\n deps: list[tuple[str, str | None]] = []\n for part in spec.split(\",\"):\n part = part.strip()\n if not part:\n raise ScrollError(\n f\"{source}: bad dependencies {spec!r}: empty clause\"\n )\n tokens = part.split()\n name = tokens[0]\n if not _NAME_RE.match(name):\n raise ScrollError(\n f\"{source}: bad dependency name {name!r} in \"\n f\"dependencies {spec!r}\"\n )\n requirement = \" \".join(tokens[1:]) or None\n if requirement is not None:\n _parse_requirement(requirement) # validates the clause shape\n if name in {n for n, _ in deps}:\n raise ScrollError(\n f\"{source}: duplicate dependency {name!r} in \"\n f\"dependencies {spec!r}\"\n )\n deps.append((name, requirement))\n return deps\n\n\ndef render_manifest(manifest: dict[str, str]) -> str:\n \"\"\"Render a manifest dict as ``scroll.toml`` text.\"\"\"\n lines: list[str] = []\n for key in (\"name\", \"version\", \"author\", \"description\", \"entry\",\n \"godcode\", \"dependencies\"):\n if key in manifest:\n value = manifest[key].replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"')\n lines.append(f'{key} = \"{value}\"')\n return \"\\n\".join(lines) + \"\\n\"\n\n\n# ---------------------------------------------------------------------------\n# the registry\n\n\ndef _default_registry_root() -> Path:\n return Path(__file__).resolve().parent.parent / \"registry\"\n\n\ndef _sha256_file(path: Path) -> str:\n \"\"\"Hex sha256 of a file's bytes.\"\"\"\n digest = hashlib.sha256()\n with open(path, \"rb\") as handle:\n for chunk in iter(lambda: handle.read(65536), b\"\"):\n digest.update(chunk)\n return digest.hexdigest()\n\n\ndef _checksum_tree(root: Path) -> dict[str, str]:\n \"\"\"sha256 for every file under ``root``, keyed by relative path.\"\"\"\n checksums: dict[str, str] = {}\n for path in sorted(root.rglob(\"*\")):\n if path.is_file():\n checksums[path.relative_to(root).as_posix()] = _sha256_file(path)\n return checksums\n\n\nclass ScrollRegistry:\n \"\"\"Local scroll registry: publish into ``registry/``, install from it.\"\"\"\n\n def __init__(\n self,\n registry_root: str | os.PathLike | None = None,\n home: str | os.PathLike | None = None,\n project_dir: str | os.PathLike | None = None,\n ) -> None:\n self.registry_root = Path(registry_root or _default_registry_root())\n self.scrolls_root = self.registry_root / \"scrolls\"\n self.index_path = self.registry_root / \"index.json\"\n self.home = Path(home or Path.home()) # honors $HOME, monkeypatchable\n self.user_dir = self.home / \".godcode\" / \"scrolls\"\n self.project_dir = Path(project_dir or Path.cwd())\n self.project_scrolls_dir = self.project_dir / \".godcode\" / \"scrolls\"\n\n # ------------------------------------------------------------- index ---\n\n def load_index(self) -> dict[str, Any]:\n \"\"\"The published index; {} when nothing has been published yet.\"\"\"\n if not self.index_path.is_file():\n return {}\n try:\n return json.loads(self.index_path.read_text(encoding=\"utf-8\"))\n except (OSError, json.JSONDecodeError) as exc:\n raise ScrollError(\n f\"cannot read registry index {self.index_path}: {exc}\"\n ) from exc\n\n def _save_index(self, index: dict[str, Any]) -> None:\n self.index_path.parent.mkdir(parents=True, exist_ok=True)\n self.index_path.write_text(\n json.dumps(index, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\"\n )\n\n # ----------------------------------------------------------- publish ---\n\n def publish(self, scroll_dir: str | os.PathLike) -> dict[str, str]:\n \"\"\"Validate a scroll directory and publish it into the registry.\n\n Copies ``scroll_dir`` to ``registry/scrolls///`` and\n updates ``index.json``. Refuses when that exact version is already\n published. Returns the validated manifest.\n \"\"\"\n src = Path(scroll_dir)\n if not src.is_dir():\n raise ScrollError(f\"publish: {src} is not a directory\")\n manifest_path = src / \"scroll.toml\"\n if not manifest_path.is_file():\n raise ScrollError(f\"publish: {src} holds no scroll.toml manifest\")\n manifest = read_manifest(manifest_path)\n\n name, version = manifest[\"name\"], manifest[\"version\"]\n if src.name != name:\n raise ScrollError(\n f\"publish: manifest name {name!r} does not match directory \"\n f\"name {src.name!r}\"\n )\n entry_path = src / manifest[\"entry\"]\n if not entry_path.is_file():\n raise ScrollError(\n f\"publish: entry file {manifest['entry']!r} not found in {src}\"\n )\n\n index = self.load_index()\n published = index.get(name, {}).get(\"versions\", [])\n if version in published:\n raise ScrollError(\n f\"publish: {name} {version} is already in the registry. \"\n \"Bump the version to publish again\"\n )\n\n dest = self.scrolls_root / name / version\n if dest.exists():\n raise ScrollError(\n f\"publish: {dest} already exists on disk but is not indexed; \"\n \"remove it or repair the index first\"\n )\n shutil.copytree(src, dest)\n\n versions = sorted(set(published) | {version},\n key=lambda v: parse_semver(v))\n index[name] = {\n \"name\": name,\n \"versions\": versions,\n \"latest\": latest_version(versions),\n \"manifest\": manifest,\n \"checksums\": {\n **index.get(name, {}).get(\"checksums\", {}),\n version: _checksum_tree(dest),\n },\n }\n self._save_index(index)\n return manifest\n\n # ----------------------------------------------------------- install ---\n\n def _remote_client(self, remote: bool | Any) -> Any | None:\n \"\"\"A RemoteRegistry when ``remote`` asks for one, else None.\n\n ``remote`` may be True (build a default client), a RemoteRegistry\n instance (use it), or False/None (local only).\n \"\"\"\n if remote is True:\n from godcode.remote_registry import RemoteRegistry\n\n return RemoteRegistry()\n return remote or None\n\n def resolve_version(self, name: str, version: str | None = None) -> str:\n \"\"\"The version to install: ``version`` if given, else the latest.\"\"\"\n index = self.load_index()\n entry = index.get(name)\n if entry is None:\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the registry \"\n f\"({self.registry_root})\"\n )\n versions: list[str] = entry[\"versions\"]\n if version is None:\n return entry[\"latest\"]\n if version not in versions:\n raise ScrollError(\n f\"install: {name} has no version {version!r}; \"\n f\"published: {', '.join(versions)}\"\n )\n return version\n\n def _choose_source(\n self,\n name: str,\n requirement: str | None,\n remote_client: Any | None,\n stack: tuple[str, ...],\n ) -> tuple[str, str, dict[str, Any] | None]:\n \"\"\"Pick (version, source, info) for ``name`` under ``requirement``.\n\n ``requirement`` is None (any version), ``==X.Y.Z`` (exact, from\n ``--version`` or a pinned dependency), or a dep clause like\n ``>= 1.0.0``. The local index always wins; the remote registry is\n consulted only when a client was passed and the local index cannot\n serve the requirement.\n \"\"\"\n context = f\" (needed by {' -> '.join(stack)})\" if stack else \"\"\n index = self.load_index()\n entry = index.get(name)\n\n if requirement is not None and requirement.startswith(\"==\"):\n exact = requirement[2:].strip()\n if entry is not None:\n if exact in entry[\"versions\"]:\n return exact, \"local\", None\n if remote_client is None:\n raise ScrollError(\n f\"install: {name} has no version {exact!r}; \"\n f\"published: {', '.join(entry['versions'])}\"\n )\n # else: fall through to the remote lookup below\n elif entry is not None:\n matching = [\n v\n for v in entry[\"versions\"]\n if requirement is None\n or requirement_satisfied(requirement, v)\n ]\n if matching:\n return latest_version(matching), \"local\", None\n\n if remote_client is not None:\n try:\n info, matching = remote_client.versions_satisfying(\n name, requirement\n )\n except ScrollError as exc:\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the local registry and the \"\n f\"remote registry cannot serve it: {exc}{context}\"\n ) from exc\n if matching:\n return matching[0], \"remote\", info\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the local registry and the \"\n f\"remote registry has no version matching \"\n f\"{requirement or 'any'!r}{context}\"\n )\n if entry is None:\n raise ScrollNotFoundError(\n f\"install: {name!r} is not in the registry \"\n f\"({self.registry_root}){context}\"\n )\n raise ScrollNotFoundError(\n f\"install: {name!r} has no published version matching \"\n f\"{requirement!r}{context}\"\n )\n\n def _manifest_for(\n self,\n name: str,\n version: str,\n source: str,\n info: dict[str, Any] | None,\n ) -> dict[str, str]:\n \"\"\"The validated manifest for a chosen (name, version).\"\"\"\n if source == \"local\":\n return read_manifest(self.scrolls_root / name / version / \"scroll.toml\")\n from godcode.remote_registry import synthesized_manifest\n\n manifest = synthesized_manifest(name, info or {}, version)\n return parse_manifest(\n render_manifest(manifest), source=f\"\"\n )\n\n def _plan_install(\n self,\n name: str,\n requirement: str | None,\n stack: tuple[str, ...],\n remote_client: Any | None,\n plan: dict[str, dict[str, Any]],\n ) -> None:\n \"\"\"Fill ``plan`` (insertion-ordered, dependencies first) with the\n scrolls this install needs, resolving versions and detecting cycles.\n \"\"\"\n if name in stack:\n cycle = \" -> \".join([*stack, name])\n raise ScrollError(\n f\"dependency cycle detected: {cycle}. A scroll cannot depend \"\n \"on itself through a circle of dependencies; break the \"\n \"circle and publish again.\"\n )\n if name in plan:\n chosen = plan[name][\"version\"]\n if requirement is None or requirement_satisfied(requirement, chosen):\n return\n raise ScrollError(\n f\"install: version conflict for {name!r}: this install \"\n f\"already resolved {chosen}, which does not satisfy \"\n f\"{requirement!r}\"\n )\n version, source, info = self._choose_source(\n name, requirement, remote_client, stack\n )\n manifest = self._manifest_for(name, version, source, info)\n for dep_name, dep_req in parse_dependencies(\n manifest.get(\"dependencies\", \"\"), source=f\"<{name} {version}>\"\n ):\n self._plan_install(dep_name, dep_req, stack + (name,),\n remote_client, plan)\n plan[name] = {\n \"name\": name,\n \"version\": version,\n \"source\": source,\n \"info\": info,\n \"manifest\": manifest,\n }\n\n def _dependency_tree(\n self, manifest: dict[str, str], plan: dict[str, dict[str, Any]]\n ) -> dict[str, str]:\n \"\"\"Resolved {dependency name: version} for a receipt.\"\"\"\n tree: dict[str, str] = {}\n for dep_name, _ in parse_dependencies(manifest.get(\"dependencies\", \"\")):\n if dep_name in plan:\n tree[dep_name] = plan[dep_name][\"version\"]\n return tree\n\n def _verify_checksums(self, name: str, version: str, src: Path) -> dict[str, str]:\n \"\"\"Check published files against the checksums recorded on publish.\n\n Returns the recorded checksums (for the receipt). Index entries\n written before checksums existed carry none and are trusted as-is.\n \"\"\"\n index = self.load_index()\n recorded: dict[str, str] = (\n index.get(name, {}).get(\"checksums\", {}) or {}\n ).get(version, {})\n for rel, expected in recorded.items():\n path = src / rel\n if not path.is_file():\n raise ScrollError(\n f\"install: {name} {version} is missing published file \"\n f\"{rel!r} in the registry; republish the scroll\"\n )\n actual = _sha256_file(path)\n if actual != expected:\n raise ScrollError(\n f\"install: checksum mismatch for {name} {version} file \"\n f\"{rel!r}: the registry copy changed after publish \"\n f\"(expected {expected[:12]}..., got {actual[:12]}...). \"\n \"Republish the scroll to heal the registry.\"\n )\n return recorded\n\n def _write_install(\n self,\n name: str,\n version: str,\n project: bool,\n manifest: dict[str, str],\n *,\n source: str,\n checksums: dict[str, str],\n dependencies: dict[str, str],\n copy_from: Path | None = None,\n files: dict[str, str] | None = None,\n ) -> dict[str, Any]:\n \"\"\"Materialize one installed scroll directory and its receipt.\"\"\"\n base = self.project_scrolls_dir if project else self.user_dir\n dest = base / name / version\n if dest.exists():\n shutil.rmtree(dest)\n if copy_from is not None:\n shutil.copytree(copy_from, dest)\n else:\n dest.mkdir(parents=True)\n for rel, content in (files or {}).items():\n (dest / rel).write_text(content, encoding=\"utf-8\")\n\n receipt = {\n \"name\": name,\n \"version\": version,\n \"source\": source,\n \"location\": \"project\" if project else \"user\",\n \"installed_at\": datetime.now(timezone.utc).isoformat(),\n \"checksums\": checksums,\n \"dependencies\": dependencies,\n \"manifest\": manifest,\n }\n (dest / \"install.json\").write_text(\n json.dumps(receipt, indent=2, sort_keys=True) + \"\\n\",\n encoding=\"utf-8\",\n )\n return receipt\n\n def _install_local(\n self,\n name: str,\n version: str,\n manifest: dict[str, str],\n project: bool,\n dependency_tree: dict[str, str],\n ) -> dict[str, Any]:\n \"\"\"Install one planned scroll from the local registry directory.\"\"\"\n src = self.scrolls_root / name / version\n if not src.is_dir():\n raise ScrollError(\n f\"install: registry is missing files for {name} {version} \"\n f\"(expected {src})\"\n )\n checksums = self._verify_checksums(name, version, src)\n return self._write_install(\n name, version, project, manifest,\n source=\"local\", checksums=checksums,\n dependencies=dependency_tree, copy_from=src,\n )\n\n def _install_remote(\n self,\n name: str,\n version: str,\n manifest: dict[str, str],\n project: bool,\n remote_client: Any,\n dependency_tree: dict[str, str],\n ) -> dict[str, Any]:\n \"\"\"Install one planned scroll by downloading it from the remote.\"\"\"\n code, resolved = remote_client.fetch_code(name, version)\n entry_name = manifest[\"entry\"]\n manifest_text = render_manifest({**manifest, \"version\": resolved})\n checksums = {\n entry_name: hashlib.sha256(code.encode(\"utf-8\")).hexdigest(),\n \"scroll.toml\": hashlib.sha256(\n manifest_text.encode(\"utf-8\")).hexdigest(),\n }\n return self._write_install(\n name, resolved, project, {**manifest, \"version\": resolved},\n source=\"remote\", checksums=checksums,\n dependencies=dependency_tree,\n files={entry_name: code, \"scroll.toml\": manifest_text},\n )\n\n def install(\n self,\n name: str,\n version: str | None = None,\n project: bool = False,\n remote: bool | Any = False,\n ) -> dict[str, Any]:\n \"\"\"Install a scroll and its dependencies into an install directory.\n\n ``project=True`` installs under ``.godcode/scrolls/`` in the current\n (or given) project directory; otherwise under ``~/.godcode/scrolls/``.\n Dependencies declared in the manifest are resolved recursively, the\n local index first and then the remote registry when ``remote`` is a\n client (or True for a default client); cycles are refused with a\n clear error. Returns the top-level install receipt.\n \"\"\"\n remote_client = self._remote_client(remote)\n plan: dict[str, dict[str, Any]] = {}\n self._plan_install(\n name,\n f\"=={version}\" if version is not None else None,\n (),\n remote_client,\n plan,\n )\n receipts: list[dict[str, Any]] = []\n for item in plan.values():\n tree = self._dependency_tree(item[\"manifest\"], plan)\n if item[\"source\"] == \"local\":\n receipts.append(\n self._install_local(\n item[\"name\"], item[\"version\"], item[\"manifest\"],\n project, tree,\n )\n )\n else:\n assert remote_client is not None # chosen by _choose_source\n receipts.append(\n self._install_remote(\n item[\"name\"], item[\"version\"], item[\"manifest\"],\n project, remote_client, tree,\n )\n )\n return receipts[-1]\n\n # --------------------------------------------------------- uninstall ---\n\n def uninstall(\n self, name: str, version: str | None = None\n ) -> list[dict[str, str]]:\n \"\"\"Remove an installed scroll (one version, or every installed\n version when ``version`` is None) from both install scopes.\"\"\"\n removed: list[dict[str, str]] = []\n for base, location in (\n (self.project_scrolls_dir, \"project\"),\n (self.user_dir, \"user\"),\n ):\n name_dir = base / name\n if not name_dir.is_dir():\n continue\n if version is None:\n targets = sorted(d for d in name_dir.iterdir() if d.is_dir())\n else:\n single = name_dir / version\n targets = [single] if single.is_dir() else []\n for target in targets:\n shutil.rmtree(target)\n removed.append(\n {\"name\": name, \"version\": target.name,\n \"location\": location}\n )\n if version is None and name_dir.is_dir() and not any(\n name_dir.iterdir()\n ):\n name_dir.rmdir()\n if not removed:\n raise ScrollError(\n f\"uninstall: {name!r}\"\n + (f\" {version}\" if version else \"\")\n + \" is not installed\"\n )\n return removed\n\n # ------------------------------------------------------------ update ---\n\n def _newest_available(\n self, name: str, remote_client: Any | None\n ) -> tuple[str | None, str]:\n \"\"\"(newest version known anywhere, source) for ``name``.\"\"\"\n best: str | None = None\n source = \"local\"\n entry = self.load_index().get(name)\n if entry:\n best = entry[\"latest\"]\n if remote_client is not None:\n try:\n info, matching = remote_client.versions_satisfying(name, None)\n except ScrollError:\n matching = []\n info = {}\n if matching and (\n best is None or compare_versions(matching[0], best) > 0\n ):\n best, source = matching[0], \"remote\"\n return best, source\n\n def update(\n self,\n name: str | None = None,\n project: bool = False,\n remote: bool | Any = False,\n ) -> list[dict[str, Any]]:\n \"\"\"Update one installed scroll (or all, when ``name`` is None) to the\n newest version known to the local index or the remote registry.\"\"\"\n remote_client = self._remote_client(remote)\n rows = {r[\"name\"]: r for r in self.list_installed()}\n names = [name] if name is not None else sorted(rows)\n if name is not None and name not in rows:\n raise ScrollError(f\"update: {name!r} is not installed\")\n results: list[dict[str, Any]] = []\n for scroll_name in names:\n installed = rows[scroll_name][\"latest\"]\n available, _source = self._newest_available(scroll_name,\n remote_client)\n if available is not None and compare_versions(available,\n installed) > 0:\n receipt = self.install(\n scroll_name, version=available, project=project,\n remote=remote,\n )\n results.append(\n {\"name\": scroll_name, \"from\": installed,\n \"to\": available, \"source\": receipt[\"source\"]}\n )\n else:\n results.append(\n {\"name\": scroll_name, \"from\": installed,\n \"to\": installed, \"up_to_date\": True}\n )\n return results\n\n # -------------------------------------------------------------- read ---\n\n def _installed_versions(self, base: Path) -> dict[str, list[str]]:\n \"\"\"name -> sorted installed versions found under ``base``.\"\"\"\n found: dict[str, list[str]] = {}\n if not base.is_dir():\n return found\n for name_dir in sorted(base.iterdir()):\n if not name_dir.is_dir():\n continue\n for ver_dir in sorted(name_dir.iterdir()):\n if not ver_dir.is_dir():\n continue\n if not (ver_dir / \"scroll.toml\").is_file():\n continue\n try:\n parse_semver(ver_dir.name)\n except ScrollError:\n continue\n found.setdefault(name_dir.name, []).append(ver_dir.name)\n return found\n\n def list_installed(self) -> list[dict[str, Any]]:\n \"\"\"Every installed scroll; project-local entries win over user ones.\"\"\"\n user = self._installed_versions(self.user_dir)\n project = self._installed_versions(self.project_scrolls_dir)\n rows: list[dict[str, Any]] = []\n for name in sorted(set(user) | set(project)):\n versions = sorted(\n set(user.get(name, [])) | set(project.get(name, [])),\n key=lambda v: parse_semver(v),\n )\n rows.append(\n {\n \"name\": name,\n \"versions\": versions,\n \"latest\": latest_version(versions),\n \"locations\": sorted(\n {\n *((\"user\",) if name in user else ()),\n *((\"project\",) if name in project else ()),\n }\n ),\n }\n )\n return rows\n\n def info(self, name: str) -> dict[str, Any]:\n \"\"\"Manifest, published versions, and install state for ``name``.\"\"\"\n index = self.load_index()\n entry = index.get(name)\n user = self._installed_versions(self.user_dir).get(name, [])\n project = self._installed_versions(self.project_scrolls_dir).get(name, [])\n installed = sorted(set(user) | set(project),\n key=lambda v: parse_semver(v))\n return {\n \"name\": name,\n \"published\": entry[\"versions\"] if entry else [],\n \"latest\": entry[\"latest\"] if entry else None,\n \"manifest\": entry[\"manifest\"] if entry else None,\n \"installed\": installed,\n \"installed_project\": sorted(project, key=lambda v: parse_semver(v)),\n \"installed_user\": sorted(user, key=lambda v: parse_semver(v)),\n }\n\n # ------------------------------------------- interpreter resolution ----\n\n def resolve_entry(self, name: str) -> Optional[Path]:\n \"\"\"Path to the installed entry ``.god`` file for ``name``, if any.\n\n Project-local installs win; otherwise the latest user-global\n version wins. Returns None when the scroll is not installed.\n \"\"\"\n for base in (self.project_scrolls_dir, self.user_dir):\n name_dir = base / name\n if not name_dir.is_dir():\n continue\n versions: list[str] = []\n for ver_dir in name_dir.iterdir():\n if ver_dir.is_dir() and (ver_dir / \"scroll.toml\").is_file():\n try:\n parse_semver(ver_dir.name)\n except ScrollError:\n continue\n versions.append(ver_dir.name)\n if not versions:\n continue\n latest = latest_version(versions)\n scroll_dir = name_dir / latest\n try:\n manifest = read_manifest(scroll_dir / \"scroll.toml\")\n except ScrollError:\n continue\n entry = scroll_dir / manifest[\"entry\"]\n if entry.is_file():\n return entry.resolve()\n # project-local dir exists but is broken: fall through to user\n return None\n","godcode/remote_registry.py":"\"\"\"Pillar 2b. The remote Scroll Registry client.\n\nTalks to the live scroll registry over HTTPS (default\n``https://api.getgodcode.com``) using only the standard library, so no new\ndependencies are needed. The base URL comes from the\n``GODCODE_REGISTRY_URL`` environment variable, which lets tests point the\nclient at a local fake server instead of the live registry.\n\nEndpoints used (all read-only unless noted):\n\n- ``GET /v1/scrolls?q=&limit=&offset=``. Search.\n- ``GET /v1/scrolls/:name``. Scroll info (name, description, author,\n downloads, versions[], latest, updated_at).\n- ``GET /v1/scrolls/:name/download``. The latest entry ``.god`` code.\n- ``GET /v1/scrolls/:name/versions/:version``. JSON {name, version, code,\n created_at} for one version.\n- ``POST /v1/scrolls``. Publish (needs ``Authorization: Bearer ``).\n\nThe remote catalog does not carry engine requirements or dependency lists\nfor individual versions, so installs from remote synthesize a permissive\n``scroll.toml`` from the info endpoint and record their checksum in the\ninstall receipt instead of verifying one from the index.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom typing import Any\n\nfrom godcode.registry import ENGINE_VERSION, ScrollError, requirement_satisfied\n\nDEFAULT_BASE_URL = \"https://api.getgodcode.com\"\n_REQUEST_TIMEOUT = 20\n\n\nclass RegistryClientError(ScrollError):\n \"\"\"The remote registry could not be reached or refused the request.\"\"\"\n\n\ndef registry_base_url() -> str:\n \"\"\"Base URL for the remote registry (env-overridable, for tests).\"\"\"\n return (\n os.environ.get(\"GODCODE_REGISTRY_URL\") or DEFAULT_BASE_URL\n ).rstrip(\"/\")\n\n\ndef synthesized_manifest(name: str, info: dict[str, Any], version: str) -> dict[str, str]:\n \"\"\"Build a ``scroll.toml``-shaped manifest for a remote scroll.\n\n The info endpoint carries no engine requirement or dependency list, so\n the synthesis is permissive: it admits any modern engine and declares\n no dependencies. A future info field (``godcode`` / ``dependencies``)\n is passed straight through when present.\n \"\"\"\n manifest: dict[str, str] = {\n \"name\": name,\n \"version\": version,\n \"author\": str(info.get(\"author\", \"unknown\")),\n \"description\": str(info.get(\"description\", \"\") or \"\"),\n \"entry\": f\"{name}.god\",\n \"godcode\": \">=2.0\",\n }\n if info.get(\"godcode\"):\n manifest[\"godcode\"] = str(info[\"godcode\"])\n if info.get(\"dependencies\"):\n manifest[\"dependencies\"] = str(info[\"dependencies\"])\n # guard the synthesis itself against a broken requirement shape\n requirement_satisfied(manifest[\"godcode\"], ENGINE_VERSION)\n return manifest\n\n\nclass RemoteRegistry:\n \"\"\"Thin HTTPS client for the remote scroll registry.\"\"\"\n\n def __init__(self, base_url: str | None = None) -> None:\n self.base_url = (base_url or registry_base_url()).rstrip(\"/\")\n\n # ------------------------------------------------------------ http -----\n\n def _request(\n self,\n method: str,\n path: str,\n params: dict[str, str] | None = None,\n body: dict[str, Any] | None = None,\n token: str | None = None,\n ) -> tuple[int, Any]:\n \"\"\"Issue one request; return (status, parsed body).\"\"\"\n url = self.base_url + path\n if params:\n url += \"?\" + urllib.parse.urlencode(params)\n data = None\n headers = {\"Accept\": \"application/json\"}\n if body is not None:\n data = json.dumps(body).encode(\"utf-8\")\n headers[\"Content-Type\"] = \"application/json\"\n if token:\n headers[\"Authorization\"] = f\"Bearer {token}\"\n request = urllib.request.Request(\n url, data=data, headers=headers, method=method\n )\n try:\n with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT) as resp:\n raw = resp.read().decode(\"utf-8\")\n status = resp.status\n except urllib.error.HTTPError as exc:\n try:\n payload = json.loads(exc.read().decode(\"utf-8\"))\n except Exception:\n payload = {\"ok\": False, \"error\": exc.reason}\n raise RegistryClientError(\n f\"remote registry: {method} {path} failed with HTTP \"\n f\"{exc.code}: {payload.get('error', exc.reason)}\"\n ) from exc\n except (urllib.error.URLError, TimeoutError, OSError) as exc:\n raise RegistryClientError(\n f\"remote registry: cannot reach {self.base_url} \"\n f\"({exc}); is the network up and GODCODE_REGISTRY_URL set?\"\n ) from exc\n try:\n return status, json.loads(raw)\n except json.JSONDecodeError:\n # download endpoints return plain .god source, not JSON\n return status, raw\n\n # ------------------------------------------------------------ reads ----\n\n def search(\n self, query: str, limit: int = 20, offset: int = 0\n ) -> list[dict[str, Any]]:\n \"\"\"Search the remote catalog; rows carry name, description, author,\n latest version, downloads, and updated_at.\"\"\"\n _, payload = self._request(\n \"GET\",\n \"/v1/scrolls\",\n params={\"q\": query, \"limit\": str(limit), \"offset\": str(offset)},\n )\n if isinstance(payload, dict) and payload.get(\"ok\"):\n return list(payload.get(\"scrolls\", []))\n raise RegistryClientError(\n f\"remote registry: unexpected search response for {query!r}\"\n )\n\n def info(self, name: str) -> dict[str, Any]:\n \"\"\"Full catalog record for ``name`` (versions[], latest, ...).\"\"\"\n _, payload = self._request(\n \"GET\", f\"/v1/scrolls/{urllib.parse.quote(name, safe='')}\"\n )\n if isinstance(payload, dict) and payload.get(\"ok\"):\n record = dict(payload)\n record.setdefault(\"versions\", [])\n return record\n error = payload.get(\"error\") if isinstance(payload, dict) else None\n raise RegistryClientError(\n f\"remote registry: scroll {name!r} not found ({error or 'no record'})\"\n )\n\n def fetch_code(self, name: str, version: str | None = None) -> tuple[str, str]:\n \"\"\"The entry ``.god`` source for ``name``; returns (code, version).\n\n ``version`` selects an exact release; without it the latest entry\n is downloaded.\n \"\"\"\n quoted = urllib.parse.quote(name, safe=\"\")\n if version is None:\n _, payload = self._request(\"GET\", f\"/v1/scrolls/{quoted}/download\")\n if not isinstance(payload, str):\n raise RegistryClientError(\n f\"remote registry: download for {name!r} did not \"\n \"return scroll source\"\n )\n resolved = self.info(name)[\"latest\"]\n return payload, resolved\n _, payload = self._request(\n \"GET\",\n f\"/v1/scrolls/{quoted}/versions/{urllib.parse.quote(version, safe='')}\",\n )\n if isinstance(payload, dict) and payload.get(\"code\") is not None:\n return str(payload[\"code\"]), str(payload.get(\"version\", version))\n raise RegistryClientError(\n f\"remote registry: no code for {name!r} version {version!r}\"\n )\n\n def versions_satisfying(\n self, name: str, requirement: str | None\n ) -> tuple[dict[str, Any], list[str]]:\n \"\"\"The info record plus the versions matching ``requirement``\n (None means any version), highest first.\"\"\"\n from functools import cmp_to_key\n\n from godcode.registry import compare_versions, requirement_satisfied\n\n record = self.info(name)\n versions: list[str] = list(record.get(\"versions\") or [])\n matching = [\n v\n for v in versions\n if requirement is None\n or requirement_satisfied(requirement, v)\n ]\n matching.sort(key=cmp_to_key(compare_versions), reverse=True)\n return record, matching\n\n # ----------------------------------------------------------- publish ---\n\n def publish_scroll(\n self,\n *,\n name: str,\n version: str,\n code: str,\n description: str,\n author: str,\n token: str,\n ) -> dict[str, Any]:\n \"\"\"Publish one scroll version to the remote registry.\n\n The token travels as ``Authorization: Bearer ``. The body\n mirrors the version-fetch shape: {name, version, code, description,\n author}. Returns the registry's acknowledgement.\n \"\"\"\n if not token:\n raise RegistryClientError(\n \"remote publish needs a token; refusing to publish unsigned\"\n )\n _, payload = self._request(\n \"POST\",\n \"/v1/scrolls\",\n body={\n \"name\": name,\n \"version\": version,\n \"code\": code,\n \"description\": description,\n \"author\": author,\n },\n token=token,\n )\n if isinstance(payload, dict) and payload.get(\"ok\") is not False:\n return payload\n raise RegistryClientError(\n f\"remote registry refused the publish of {name} {version}: \"\n f\"{payload!r}\"\n )\n","godcode/sandbox.py":"\"\"\"In-process sandbox for God Code v3.0 — Pillar 1 (\"Strong Foundations\").\n\nRuns a God Code creation under a deny-by-default :class:`SandboxPolicy`:\nevery side-effecting power (scroll imports outside the consecrated paths,\nthe ASK rite that speaks with the outer world) is withheld unless the\npolicy explicitly grants it. File-writing rites keep their meaning but\nnot their reach: ANCHOR is answered with an ephemeral in-memory chain,\nso nothing is ever written to disk. A step budget and a wall-clock grant\nbound runaway creations.\n\nEntry points\n------------\n``run_sandboxed(source, policy, source_name)``\n Lex, parse, and run ``source`` under ``policy``; returns the list of\n REVEAL lines captured during the run.\n\n``apply_policy(interpreter, policy)``\n Install the sandbox hooks on an existing ``Interpreter``; returns the\n ``Sandbox`` guard.\n\n``SandboxPolicy.strict(...)``\n The policy the CLI uses: no writes, no network, no subprocesses, no\n stdin, scroll imports limited to the stdlib scrolls and (optionally)\n the creation's own directory, a 5-second time grant, and a 100,000\n step budget.\n\nHonest limits (see docs/sandbox.md): this is an *in-process* sandbox —\na cooperative audit of the tree-walker, not OS-level isolation. It\ncannot contain a hostile program that escapes the interpreter, and it\ncannot cap memory.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport os\nimport signal\nimport time\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodCodeError, SandboxViolation\n\n__all__ = [\n \"SandboxPolicy\",\n \"Sandbox\",\n \"SandboxViolation\",\n \"apply_policy\",\n \"run_sandboxed\",\n \"run_sandboxed_with_interpreter\",\n]\n\n\ndef _stdlib_scrolls_dir() -> str:\n return str(Path(__file__).parent / \"scrolls\")\n\n\n# ---------------------------------------------------------------------------\n# Policy\n# ---------------------------------------------------------------------------\n@dataclass\nclass SandboxPolicy:\n \"\"\"What a sandboxed creation is permitted to do. Deny-by-default.\n\n ``allow_read_paths``\n Approved directories for filesystem *reads*. ``None`` (the\n default) denies all reads; a tuple of directories grants reads\n under those trees. (No file-reading rites exist in v2.0; this is\n enforced should any be added.)\n ``allow_write`` / ``allow_network`` / ``allow_subprocess``\n Filesystem writes, network access, subprocess spawning. All deny\n by default. The ANCHOR rite is the one file-writing rite: under a\n policy that denies writes it is answered with an ephemeral\n in-memory chain instead of being refused, so creations keep\n their meaning without touching the disk.\n ``allow_stdin``\n Whether the ASK rite may speak with the outer world (``input()``).\n Denied by default.\n ``allowed_import_paths``\n Approved directories for IMPORT of scrolls. Empty (the default)\n denies every import. Each entry is a directory; a scroll is\n allowed if its real path lies under one of them.\n ``timeout_seconds``\n Wall-clock grant for the whole run. ``None`` or ``<= 0``\n disables the grant (not recommended).\n ``max_steps``\n Step budget: every statement dispatch and every expression\n evaluation counts one step, bounding both runaway loops and\n unbounded rite recursion.\n \"\"\"\n\n allow_read_paths: tuple[str, ...] | None = None\n allow_write: bool = False\n allow_network: bool = False\n allow_subprocess: bool = False\n allow_stdin: bool = False\n allowed_import_paths: tuple[str, ...] = ()\n timeout_seconds: float | None = 5.0\n max_steps: int = 100_000\n\n @classmethod\n def strict(\n cls,\n *,\n source_dir: str | None = None,\n timeout_seconds: float | None = 5.0,\n allow_read_paths: tuple[str, ...] | None = None,\n ) -> \"SandboxPolicy\":\n \"\"\"The CLI's strict policy: deny everything, bless the stdlib.\n\n Scroll imports are allowed from the bundled stdlib scrolls and,\n when given, the creation's own directory — nothing else.\n Filesystem reads stay denied unless the invoker names them:\n ``allow_read_paths`` grants host reads under those trees only,\n and the scroll's own permission manifest still narrows the\n grant, so the effective read set is host grant intersect\n manifest. The invoker's grant is the invoker's own act, never\n the creation's: a scroll cannot widen its own cage.\n \"\"\"\n paths = [_stdlib_scrolls_dir()]\n if source_dir:\n paths.append(str(source_dir))\n return cls(\n allow_read_paths=allow_read_paths,\n allowed_import_paths=tuple(paths),\n timeout_seconds=timeout_seconds,\n )\n\n @classmethod\n def open(cls) -> \"SandboxPolicy\":\n \"\"\"The permissive host policy used under a permission manifest.\n\n A plain `godcode run` of a scroll without --sandbox has always run\n unbound; installing the guard with the open policy preserves that\n while letting the scroll's own permission manifest do the\n narrowing. No step budget, no time grant, every power allowed —\n the manifest alone withholds.\n \"\"\"\n return cls(\n allow_read_paths=(os.sep,),\n allow_write=True,\n allow_network=True,\n allow_subprocess=True,\n allow_stdin=True,\n allowed_import_paths=(os.sep,),\n timeout_seconds=None,\n max_steps=10**15,\n )\n\n\n# ---------------------------------------------------------------------------\n# The guard\n# ---------------------------------------------------------------------------\n# Builtin rite name -> SandboxPolicy attribute that must be truthy for the\n# rite to run. ANCHOR is deliberately absent: under a policy that denies\n# writes it is answered with an ephemeral in-memory chain (see\n# run_sandboxed_with_interpreter), so the rite itself never reaches the\n# filesystem and needs no grant. The vault builtins (godcode.stdlib_vault)\n# reach the host filesystem directly, so they are policed here too;\n# READ_FILE/LIST_DIR/FILE_EXISTS additionally enforce the granted\n# directories per path inside the builtins themselves.\n_SIDE_EFFECT_RITES: dict[str, str] = {\n \"ASK\": \"allow_stdin\",\n \"WRITE_FILE\": \"allow_write\",\n \"READ_FILE\": \"allow_read_paths\",\n \"LIST_DIR\": \"allow_read_paths\",\n \"FILE_EXISTS\": \"allow_read_paths\",\n \"HTTP_GET\": \"allow_network\",\n}\n\n_HOOKS = (\"_exec_stmt\", \"_eval_expr\", \"_call\", \"_exec_import\")\n\n\nclass Sandbox:\n \"\"\"Enforces a :class:`SandboxPolicy` on a live Interpreter.\n\n Installed hooks (see :meth:`install`):\n\n * ``_exec_stmt`` / ``_eval_expr`` — count one step per statement\n dispatch and expression evaluation; check the step budget and the\n wall-clock grant; record the current line for divine errors.\n * ``_call`` — refuse side-effecting rites the policy does not grant\n (ASK today; the registry above grows with the language).\n * ``_exec_import`` — resolve the scroll, then refuse any path\n outside ``allowed_import_paths``.\n \"\"\"\n\n def __init__(self, interpreter: Any, policy: SandboxPolicy):\n self.interpreter = interpreter\n self.policy = policy\n self.steps = 0\n self.started_at: float | None = None\n self.current_line: int | None = None\n self._originals: dict[str, Callable] = {}\n self._allowed_import_dirs = [\n os.path.realpath(p) for p in policy.allowed_import_paths\n ]\n # The open policy blesses the whole filesystem: every import path\n # is consecrated, as in a plain `godcode run` with no guard.\n self._import_open = any(\n d == os.path.realpath(os.sep) for d in self._allowed_import_dirs\n )\n\n # -- installation ---------------------------------------------------\n\n def install(self) -> \"Sandbox\":\n \"\"\"Wrap the interpreter's dispatch points. Idempotent.\n\n Also marks the interpreter with ``_sandbox_guard`` so builtins\n that reach the host world (the vault builtins in\n godcode.stdlib_vault) can see the policy and honor its grants.\n \"\"\"\n interp = self.interpreter\n if self._originals:\n return self\n interp._sandbox_guard = self\n for name in _HOOKS:\n original = getattr(interp, name)\n self._originals[name] = original\n setattr(interp, name, self._wrap(name, original))\n return self\n\n def uninstall(self) -> None:\n \"\"\"Restore the interpreter's original dispatch points.\"\"\"\n for name, original in self._originals.items():\n setattr(self.interpreter, name, original)\n self._originals.clear()\n self.interpreter.__dict__.pop(\"_sandbox_guard\", None)\n\n def _wrap(self, name: str, original: Callable) -> Callable:\n if name == \"_exec_stmt\":\n def exec_stmt(stmt, env):\n self.tick(stmt)\n return original(stmt, env)\n return exec_stmt\n if name == \"_eval_expr\":\n def eval_expr(expr, env):\n self.tick(expr)\n return original(expr, env)\n return eval_expr\n if name == \"_call\":\n def call(rite_name, args, env, line):\n self.check_rite(rite_name, line, tuple(args or ()))\n return original(rite_name, args, env, line)\n return call\n if name == \"_exec_import\":\n def exec_import(stmt, env):\n line = getattr(stmt, \"line\", None)\n path = self.interpreter._resolve_import(stmt.path, line)\n self.check_import_path(path, stmt.path, line)\n return original(stmt, env)\n return exec_import\n raise AssertionError(f\"unknown hook: {name}\") # pragma: no cover\n\n # -- enforcement -----------------------------------------------------\n\n def tick(self, node: Any) -> None:\n \"\"\"Count one interpreter step; enforce budget and time grant.\"\"\"\n self.steps += 1\n line = getattr(node, \"line\", None)\n if line is not None:\n self.current_line = line\n if self.steps > self.policy.max_steps:\n raise SandboxViolation(\n \"The sandbox withholds this power: the creation has taken \"\n f\"more than {self.policy.max_steps:,} steps. \"\n \"The step budget is spent, and the cycle is released.\",\n self.current_line,\n )\n if self.started_at is not None and self.policy.timeout_seconds:\n elapsed = time.monotonic() - self.started_at\n if elapsed > self.policy.timeout_seconds:\n raise SandboxViolation(\n \"The sandbox withholds this power: the appointed time \"\n f\"({self.policy.timeout_seconds:g}s) is spent. \"\n \"The creation is released in peace.\",\n self.current_line,\n )\n\n def check_rite(self, name: str, line: int | None, args: tuple = ()) -> None:\n \"\"\"Refuse side-effecting rites the policy does not grant.\n\n The host policy is consulted first; then the scroll's own\n permission manifest (when the scroll declared one) narrows the\n grant to the declared targets. The manifest never widens the host.\n \"\"\"\n need = _SIDE_EFFECT_RITES.get(str(name).upper())\n if need is not None and not getattr(self.policy, need, False):\n divine = {\n \"ASK\": \"the rite ASK would speak with the outer world\",\n \"WRITE_FILE\": \"the rite WRITE_FILE would write to the outer world\",\n \"READ_FILE\": \"the rite READ_FILE would read from the outer world\",\n \"LIST_DIR\": \"the rite LIST_DIR would read from the outer world\",\n \"FILE_EXISTS\": \"the rite FILE_EXISTS would read from the outer world\",\n \"HTTP_GET\": \"the rite HTTP_GET would reach out to the web\",\n }.get(str(name).upper(), f\"the rite {name}\")\n raise SandboxViolation(\n f\"The sandbox withholds this power: {divine}. \"\n \"It is not granted.\",\n line,\n )\n self._check_manifest(name, line, args)\n\n def _check_manifest(self, name: str, line: int | None, args: tuple) -> None:\n \"\"\"Enforce the scroll's declared permission manifest, if any.\n\n The guard reads the manifest live from the interpreter so that\n imported scrolls may widen the run's grants by declaring their\n own (grants compose by union; the host policy still narrows).\n \"\"\"\n manifest = getattr(self.interpreter, \"manifest\", None)\n if not manifest:\n return\n rite = str(name).upper()\n target = args[0] if args else None\n # Runtime file targets resolve exactly the way the builtins open\n # them: relative to the invocation directory. realpath() on the\n # raw target mirrors that, so the check can never be talked into\n # blessing a different file than the rite will touch.\n\n def withheld(counsel: str) -> SandboxViolation:\n return SandboxViolation(\n f\"The scroll reaches for a power it did not declare: {counsel} \"\n \"Declare it at the top of the scroll with DECLARE PERMISSION \"\n \"TO, or leave the power untouched.\",\n line,\n )\n\n if rite == \"ASK\" and not manifest.stdin:\n raise withheld(\"ASK would speak with the outer world\")\n if rite == \"WRITE_FILE\":\n if not (isinstance(target, str) and manifest.allows_write(target)):\n raise withheld(f\"WRITE_FILE would write '{target}'\")\n if rite in (\"READ_FILE\", \"LIST_DIR\", \"FILE_EXISTS\"):\n if not (isinstance(target, str) and manifest.allows_read(target)):\n raise withheld(f\"{rite} would read '{target}'\")\n if rite == \"HTTP_GET\":\n if not (isinstance(target, str) and manifest.allows_host(target)):\n raise withheld(f\"HTTP_GET would reach '{target}'\")\n if rite == \"SUMMON\":\n if not (isinstance(target, str) and manifest.allows_summon(target)):\n raise withheld(f\"SUMMON would call upon '{target}'\")\n\n def check_import_path(\n self, path: Path, requested: str, line: int | None\n ) -> None:\n \"\"\"Refuse scrolls outside the consecrated import paths.\"\"\"\n if self._import_open:\n return\n resolved = os.path.realpath(path)\n for allowed in self._allowed_import_dirs:\n if resolved == allowed or resolved.startswith(allowed + os.sep):\n return\n raise SandboxViolation(\n \"The sandbox withholds this power: the scroll \"\n f\"'{requested}' lies outside the consecrated paths. \"\n \"It may not be breathed in.\",\n line,\n )\n\n\ndef apply_policy(interpreter: Any, policy: SandboxPolicy) -> Sandbox:\n \"\"\"Install sandbox hooks on ``interpreter``; return the guard.\n\n One guard per interpreter; the hooks stay installed until\n ``guard.uninstall()`` is called.\n \"\"\"\n return Sandbox(interpreter, policy).install()\n\n\n# ---------------------------------------------------------------------------\n# Timeout: POSIX signal alarm with a wall-clock fallback\n# ---------------------------------------------------------------------------\n@contextlib.contextmanager\ndef _time_limit(seconds: float | None, guard: Sandbox):\n \"\"\"Raise SandboxViolation from a POSIX alarm when the grant expires.\n\n The wall-clock check in :meth:`Sandbox.tick` is the fallback (and the\n only enforcement on platforms without ``setitimer``, or outside the\n main thread, where signals cannot be armed).\n \"\"\"\n armed = False\n old_handler = None\n\n def _handler(signum, frame): # noqa: ARG001\n raise SandboxViolation(\n \"The sandbox withholds this power: the appointed time \"\n f\"({seconds:g}s) is spent. The creation is released in peace.\",\n guard.current_line,\n )\n\n try:\n if seconds and hasattr(signal, \"setitimer\"):\n old_handler = signal.signal(signal.SIGALRM, _handler)\n signal.setitimer(signal.ITIMER_REAL, seconds)\n armed = True\n except (ValueError, OSError, RuntimeError):\n armed = False # not the main thread, or signals unavailable\n try:\n yield\n finally:\n if armed:\n try:\n signal.setitimer(signal.ITIMER_REAL, 0)\n signal.signal(signal.SIGALRM, old_handler)\n except (ValueError, OSError, RuntimeError):\n pass\n\n\n# ---------------------------------------------------------------------------\n# High-level entry point\n# ---------------------------------------------------------------------------\ndef run_sandboxed_with_interpreter(\n source: str,\n policy: SandboxPolicy | None = None,\n source_name: str = \"\",\n) -> tuple[list[str], Any]:\n \"\"\"Run God Code ``source`` under ``policy``; return (REVEAL lines, interpreter).\n\n The interpreter is returned so callers can read machine state the run\n gathered (e.g. ``intent_checks`` for the v4.0 intent layer).\n \"\"\"\n from godcode import plugins\n from godcode.chain import MemoryChainAdapter\n from godcode.interpreter import Interpreter\n from godcode.spirit import SpiritEngine\n\n policy = policy or SandboxPolicy.strict()\n env_var = plugins.DISABLE_ENV_VAR\n previous = os.environ.get(env_var)\n os.environ[env_var] = \"1\"\n try:\n interpreter = Interpreter(log_path=None, interactive=False)\n finally:\n if previous is None:\n os.environ.pop(env_var, None)\n else:\n os.environ[env_var] = previous\n # v4.0: the covenant ledger and the audit log stay unbound (they write\n # to the host world, which the sandbox does not permit). The Spirit\n # only reads its dataset, so it is bound: CONSULT and the DECLARE\n # INTENT discernment need it. ANCHOR is answered with an ephemeral\n # in-memory chain, so no file is ever written.\n try:\n interpreter.spirit = SpiritEngine()\n except Exception:\n pass\n if not policy.allow_write:\n interpreter.chain_adapters = {\"simulated\": MemoryChainAdapter()}\n guard = apply_policy(interpreter, policy)\n guard.started_at = time.monotonic()\n try:\n with _time_limit(policy.timeout_seconds, guard):\n interpreter.run_source(source, source_name=source_name)\n except RecursionError:\n raise SandboxViolation(\n \"The sandbox withholds this power: the rites called upon \"\n \"themselves past the deep places. The recursion budget is \"\n \"spent, and the cycle is released.\",\n guard.current_line,\n ) from None\n finally:\n guard.started_at = None\n return list(interpreter.output), interpreter\n\n\ndef run_sandboxed(\n source: str,\n policy: SandboxPolicy | None = None,\n source_name: str = \"\",\n) -> list[str]:\n \"\"\"Run God Code ``source`` under ``policy``; return captured REVEAL lines.\n\n Uses the strict policy when none is given. The covenant ledger and\n the audit log stay unbound -- they write to the host world, which\n the sandbox does not permit. The Spirit is bound (it only reads its\n dataset), and ANCHOR answers with an ephemeral in-memory chain, so\n CONSULT and DECLARE INTENT work while no file is ever written. Host\n plugin auto-loading is disabled for the run (via the plugin system's\n own opt-out): plugins are trusted host code that runs outside any\n policy, so a deny-by-default sandbox must not breathe them in unasked.\n Raises :class:`SandboxViolation` (a GodCodeError, line-numbered)\n when the creation reaches beyond its grant.\n \"\"\"\n output, _ = run_sandboxed_with_interpreter(source, policy, source_name)\n return output\n","godcode/scaffold.py":"\"\"\"`godcode new` — raise a new God Code project from the dust.\n\nOne command lays out everything a first scroll needs: a manifest the\nscroll registry understands, a warm starter scroll that runs pure, a\ntest scroll the test runner discovers, and a small README that points\nat the next steps. The sanctuary welcomes the newcomer.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\n#: Scroll/project names: lowercase, digits, and hyphens, starting with a letter.\nNAME_RE = re.compile(r\"^[a-z][a-z0-9-]{0,63}$\")\n\n#: The engine release line this scaffold targets.\nENGINE_LINE = \">=4.1\"\n\n\nclass ScaffoldError(Exception):\n \"\"\"A gentle refusal to raise the project (bad name, occupied ground).\"\"\"\n\n\n@dataclass\nclass ScaffoldResult:\n \"\"\"What `create_project` laid down.\"\"\"\n\n name: str\n directory: Path\n files: list[str] = field(default_factory=list)\n\n\ndef validate_name(name: str) -> str:\n \"\"\"Return the cleaned name, or raise ScaffoldError with counsel.\"\"\"\n cleaned = (name or \"\").strip().lower()\n if not NAME_RE.match(cleaned):\n raise ScaffoldError(\n f\"'{name}' is not a fitting scroll name: use lowercase letters, \"\n \"digits, and hyphens, beginning with a letter \"\n \"(for example: my-scroll).\"\n )\n return cleaned\n\n\ndef _main_god(name: str) -> str:\n return f\"\"\"\\\n# {name}, a newborn scroll.\n# Run it with: godcode run main.god\n# Test it with: godcode test .\n# Declare the powers your scroll may touch (uncomment what it needs):\n# DECLARE PERMISSION TO READ \"data/\"\n# DECLARE PERMISSION TO WRITE \"out/\"\n\nBEGIN CREATION\n\n DECLARE INTENT \"speak a blessing of peace over the household\" ON evening_blessing\n\n DEFINE RITE evening_blessing()\n REVEAL(\"Peace be upon this house.\")\n REVEAL(\"May the morning bring grace and the evening bring rest.\")\n END RITE\n\n DECLARE day AS \"a new day\"\n evening_blessing()\n REVEAL(\"Walk into {{day}} with courage.\")\n\nEND CREATION\n\"\"\"\n\n\ndef _test_god(name: str) -> str:\n return f\"\"\"\\\n# Tests for the {name} scroll.\n# Run them with: godcode test .\n\nBEGIN CREATION\n\n DEFINE RITE TEST_day_declared()\n DECLARE day AS \"a new day\"\n TESTIFY day IS \"a new day\"\n END RITE\n\n DEFINE RITE TEST_blessing_holds()\n TESTIFY 2 + 3 IS 5\n END RITE\n\nEND CREATION\n\"\"\"\n\n\ndef _scroll_toml(name: str, author: str) -> str:\n return f\"\"\"\\\n# Scroll manifest — `godcode scroll publish .` reads this.\nname = \"{name}\"\nversion = \"0.1.0\"\nauthor = \"{author}\"\ndescription = \"A newborn God Code scroll.\"\nentry = \"main.god\"\ngodcode = \"{ENGINE_LINE}\"\n\"\"\"\n\n\ndef _readme(name: str) -> str:\n return f\"\"\"\\\n# {name}\n\nA God Code scroll, freshly created with `godcode new`.\n\n## Speak it\n\n godcode run main.god\n\n## Test it\n\n godcode test .\n\n## Polish it\n\n godcode check main.god # purity, without running\n godcode lint main.god # quiet troubles surfaced\n godcode fmt main.god # canonical form\n\n## Share it\n\n godcode scroll publish . # publish to the local scroll registry\n\nLearn the language: https://godcode-phi.vercel.app/learn/\n\"\"\"\n\n\ndef create_project(name: str, dest: Path | str = \".\",\n author: str = \"\") -> ScaffoldResult:\n \"\"\"Raise the project directory and write the four starter files.\n\n Raises ScaffoldError when the name is unfitting or the ground is\n already occupied.\n \"\"\"\n cleaned = validate_name(name)\n root = Path(dest).expanduser() / cleaned\n if root.exists():\n raise ScaffoldError(\n f\"'{root}' already stands: choose another name or an empty place.\"\n )\n root.mkdir(parents=True)\n\n files = {\n \"main.god\": _main_god(cleaned),\n \"test_main.god\": _test_god(cleaned),\n \"scroll.toml\": _scroll_toml(cleaned, author.replace('\"', \"\")),\n \"README.md\": _readme(cleaned),\n }\n for filename, text in files.items():\n (root / filename).write_text(text, encoding=\"utf-8\")\n return ScaffoldResult(name=cleaned, directory=root,\n files=sorted(files))\n","godcode/scrolls/covenant.god":"# The Scroll of the Covenant -- making and sealing binding promises.\n# Rites: NEW_COVENANT, SEAL_COVENANT.\n\nDEFINE RITE NEW_COVENANT(name)\nRETURN contract(name)\nEND RITE\n\nDEFINE RITE SEAL_COVENANT(c)\nSEAL c\nEND RITE\n","godcode/scrolls/covenant.toml":"name = \"covenant\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of the Covenant: making and sealing binding promises. Rites: NEW_COVENANT, SEAL_COVENANT.\"\nentry = \"covenant.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/lists.god":"# The Scroll of Multitudes -- reckonings over gathered lists.\n# Rites: SUM, AVG, CONTAINS, SECOND, TAIL, COUNT.\n\nDEFINE RITE SUM(xs)\nDECLARE total AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nDECLARE total AS total + xs[i]\nDECLARE i AS i + 1\nENDWHILE\nRETURN total\nEND RITE\n\nDEFINE RITE AVG(xs)\nRETURN SUM(xs) / LEN(xs)\nEND RITE\n\nDEFINE RITE CONTAINS(xs, x)\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nRETURN 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN 0\nEND RITE\n\nDEFINE RITE SECOND(xs)\nRETURN xs[1]\nEND RITE\n\nDEFINE RITE TAIL(xs)\nDECLARE tail AS []\nDECLARE i AS 1\nWHILE i < LEN(xs) DO\nDECLARE tail AS PUSH(tail, xs[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN tail\nEND RITE\n\nDEFINE RITE COUNT(xs, x)\nDECLARE n AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nDECLARE n AS n + 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN n\nEND RITE\n","godcode/scrolls/lists.toml":"name = \"lists\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Multitudes: reckonings over gathered lists. Rites: SUM, AVG, CONTAINS, SECOND, TAIL, COUNT.\"\nentry = \"lists.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/math.god":"# The Scroll of Numbers -- divine arithmetic for the children of creation.\n# Rites: SQRT, POW, ABS, MIN, MAX, FACTORIAL, IS_EVEN.\n\nDEFINE RITE SQRT(x)\nIF x IS 0 THEN\nRETURN 0\nENDIF\nIF x < 0 THEN\nRETURN 0\nENDIF\nDECLARE guess AS x\nWHILE ABS(guess * guess - x) > 0.000000001 DO\nDECLARE guess AS guess - (guess * guess - x) / (2 * guess)\nENDWHILE\nRETURN guess\nEND RITE\n\nDEFINE RITE POW(b, e)\nDECLARE result AS 1\nDECLARE i AS 0\nWHILE i < e DO\nDECLARE result AS result * b\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE ABS(x)\nIF x < 0 THEN\nRETURN 0 - x\nENDIF\nRETURN x\nEND RITE\n\nDEFINE RITE MIN(a, b)\nIF a < b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE MAX(a, b)\nIF a > b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE FACTORIAL(n)\nDECLARE result AS 1\nDECLARE i AS 1\nWHILE i <= n DO\nDECLARE result AS result * i\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE IS_EVEN(n)\nIF n % 2 IS 0 THEN\nRETURN 1\nENDIF\nRETURN 0\nEND RITE\n","godcode/scrolls/math.toml":"name = \"math\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Numbers: divine arithmetic. Rites: SQRT, POW, ABS, MIN, MAX, FACTORIAL, IS_EVEN.\"\nentry = \"math.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/prophecy.god":"# The Scroll of Lots -- discerning choice by sacred chance.\n# Rites: PROPHESY_NUMBER, CAST_LOTS, CHOOSE.\n\nDEFINE RITE PROPHESY_NUMBER(n)\nRETURN RANDOM(n)\nEND RITE\n\nDEFINE RITE CAST_LOTS()\nRETURN RANDOM(2)\nEND RITE\n\nDEFINE RITE CHOOSE(xs)\nRETURN xs[RANDOM(LEN(xs))]\nEND RITE\n","godcode/scrolls/prophecy.toml":"name = \"prophecy\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Lots: discerning choice by sacred chance. Rites: PROPHESY_NUMBER, CAST_LOTS, CHOOSE.\"\nentry = \"prophecy.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/strings.god":"# The Scroll of Tongues -- words shaped, lifted up, and proclaimed.\n# Rites: SHOUT, WHISPER, WORDS, CHARS, FIRST, LAST.\n\nDEFINE RITE SHOUT(s)\nRETURN UPPER(s) + \"!\"\nEND RITE\n\nDEFINE RITE WHISPER(s)\nRETURN LOWER(s)\nEND RITE\n\nDEFINE RITE WORDS(s)\nRETURN SPLIT(s, \" \")\nEND RITE\n\nDEFINE RITE CHARS(s)\nDECLARE chars AS []\nDECLARE i AS 0\nWHILE i < LEN(s) DO\nDECLARE chars AS PUSH(chars, s[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN chars\nEND RITE\n\nDEFINE RITE FIRST(s)\nRETURN s[0]\nEND RITE\n\nDEFINE RITE LAST(s)\nRETURN s[LEN(s) - 1]\nEND RITE\n","godcode/scrolls/strings.toml":"name = \"strings\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Tongues: words shaped, lifted up, and proclaimed. Rites: SHOUT, WHISPER, WORDS, CHARS, FIRST, LAST.\"\nentry = \"strings.god\"\ngodcode = \">=2.0\"\n","godcode/scrolls/time.god":"# The Scroll of Appointed Times -- beholding the hour and the day.\n# Rites: NOW, TODAY.\n\nDEFINE RITE NOW()\nRETURN BEHOLD()\nEND RITE\n\nDEFINE RITE TODAY()\nRETURN SPLIT(BEHOLD(), \"T\")[0]\nEND RITE\n","godcode/scrolls/time.toml":"name = \"time\"\nversion = \"1.0.0\"\nauthor = \"God Code contributors\"\ndescription = \"The Scroll of Appointed Times: beholding the hour and the day. Rites: NOW, TODAY.\"\nentry = \"time.god\"\ngodcode = \">=2.0\"\n","godcode/spirit.py":"\"\"\"SpiritEngine -- discerns the spiritual intent behind words. 🕊\n\nLoads the God Code training dataset, builds a keyword index over each row's\nprimary_action + spiritual_intent + logic_flows, and classifies new text by\nkeyword overlap. When nothing resonates, it falls back to silent contemplation.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport csv\nimport re\nfrom collections import Counter\nfrom pathlib import Path\n\n_WORD_RE = re.compile(r\"[a-z0-9]+\")\n\nSTOPWORDS = frozenset(\n \"\"\"\n a an the of and to in for on with by or is are was were be been being\n this that these those it its as at from into over under between through\n during before after above below up down out off again further then once\n here there when where why how all any both each few more most other some\n such no nor not only own same so than too very can will just don should\n now your you we they them their our us my me him her his she he i\n do does did have has had shall may might must would could ought\n \"\"\".split()\n)\n\nSILENT_CONTEMPLATION = {\n \"intent\": \"Silent contemplation\",\n \"confidence\": 0.0,\n \"spiritual_intent\": \"The Spirit is quiet on this matter.\",\n \"suggestion\": \"BREATHE and try again.\",\n \"keywords\": [],\n}\n\n\ndef _keywords(text: str) -> set[str]:\n \"\"\"Lowercase word tokens with stopwords removed.\"\"\"\n return {w for w in _WORD_RE.findall((text or \"\").lower()) if w not in STOPWORDS}\n\n\nclass SpiritEngine:\n \"\"\"Keyword-overlap classifier over the God Code training dataset.\"\"\"\n\n def __init__(self, dataset_path: str | Path | None = None) -> None:\n if dataset_path is None:\n # Default: god_code_training_dataset.csv at the repo root.\n dataset_path = Path(__file__).resolve().parent.parent / \"god_code_training_dataset.csv\"\n self.dataset_path = Path(dataset_path)\n self.rows: list[dict] = self._load()\n # v4.0 -- declared intents: rite name -> natural-language intent text,\n # registered by DECLARE INTENT and consulted by resolve_intent().\n self.declared_intents: dict[str, str] = {}\n\n def _load(self) -> list[dict]:\n try:\n with open(self.dataset_path, newline=\"\", encoding=\"utf-8\") as f:\n records = list(csv.reader(f))\n except OSError:\n # No dataset beside the engine (e.g. an installed copy):\n # the Spirit is quiet, and classify() falls back gracefully.\n return []\n if not records:\n return []\n header, records = records[0], records[1:]\n rows: list[dict] = []\n buf: list[str] = []\n for rec in records:\n if len(rec) == len(header):\n # A row ends here: the code field may have spanned earlier\n # physical lines (unquoted), accumulated in buf.\n code = \"\\n\".join(buf + [rec[0]])\n row = dict(zip(header, [code] + rec[1:]))\n row[\"keywords\"] = _keywords(\n \" \".join(row[c] for c in (\"primary_action\", \"spiritual_intent\", \"logic_flows\"))\n )\n rows.append(row)\n buf = []\n else:\n # Continuation line of the multi-line code field.\n buf.extend(rec)\n return rows\n\n def classify(self, text: str) -> dict:\n \"\"\"Classify text -> {intent, confidence, spiritual_intent, suggestion, keywords}.\"\"\"\n words = _keywords(text)\n best: dict | None = None\n best_overlap = 0\n best_confidence = 0.0\n for row in self.rows:\n overlap = len(words & row[\"keywords\"])\n if overlap == 0:\n continue\n confidence = overlap / max(1, len(row[\"keywords\"]))\n # Most shared keywords wins; ties go to the row whose\n # vocabulary best explains the input (highest confidence),\n # so an incidental word cannot outshout the true theme.\n if overlap > best_overlap or (\n overlap == best_overlap and confidence > best_confidence\n ):\n best, best_overlap, best_confidence = row, overlap, confidence\n if best is None:\n return dict(SILENT_CONTEMPLATION)\n confidence = min(1.0, best_overlap / max(1, len(best[\"keywords\"])))\n return {\n \"intent\": best[\"primary_action\"],\n \"confidence\": round(confidence, 4),\n \"spiritual_intent\": best[\"spiritual_intent\"],\n \"suggestion\": best[\"next_suggestions\"],\n \"keywords\": sorted(words & best[\"keywords\"]),\n }\n\n def prophesy(self, program_text: str) -> str:\n \"\"\"Compose a 2-3 sentence divine forecast over a program's lines.\"\"\"\n lines = [ln.strip() for ln in (program_text or \"\").splitlines() if ln.strip()]\n results = [self.classify(ln) for ln in lines] or [dict(SILENT_CONTEMPLATION)]\n counts = Counter(r[\"intent\"] for r in results)\n top = max(counts.values())\n # Dominant intent = mode; ties resolve to the earliest line's intent.\n dominant = next(r for r in results if counts[r[\"intent\"]] == top)\n avg_conf = sum(r[\"confidence\"] for r in results) / len(results)\n pct = round(avg_conf * 100)\n return (\n f\"Thus the Spirit speaks over this creation: the prevailing wind is \"\n f\"'{dominant['intent']}', discerned with {pct}% certainty. \"\n f\"{dominant['spiritual_intent']} \"\n f\"Therefore the counsel of heaven is this: {dominant['suggestion']}\"\n )\n\n # ------------------------------------------------- v4.0: intent layer\n\n def declare_intent(self, rite_name: str, text: str) -> None:\n \"\"\"Register a natural-language intent on a named rite.\"\"\"\n self.declared_intents[str(rite_name)] = str(text)\n\n def intents_aligned(self, declared: str, discerned: dict) -> bool:\n \"\"\"True when the declared intent shares a keyword with the discerned one.\n\n *declared* is the natural-language text from DECLARE INTENT;\n *discerned* is a classify() result for the rite's actual words.\n The Spirit counsels on divergence; it never condemns.\n \"\"\"\n declared_words = _keywords(declared)\n discerned_words = (\n _keywords(discerned.get(\"intent\") or \"\")\n | _keywords(discerned.get(\"spiritual_intent\") or \"\")\n | {str(k).lower() for k in (discerned.get(\"keywords\") or [])}\n )\n return bool(declared_words & discerned_words)\n\n def resolve_intent(self, text: str) -> dict:\n \"\"\"Classify *text* and report which declared intents it aligns with.\n\n Returns the classify() payload plus ``aligned_with``: a list of\n ``{rite, declared, shared_keywords}`` for every declared intent\n sharing at least one keyword with the text.\n \"\"\"\n result = self.classify(text)\n words = _keywords(text)\n aligned_with = []\n for rite, declared in self.declared_intents.items():\n shared = sorted(words & _keywords(declared))\n if shared:\n aligned_with.append(\n {\"rite\": rite, \"declared\": declared,\n \"shared_keywords\": shared}\n )\n result[\"aligned_with\"] = aligned_with\n return result\n\n def counsel(self, question: str) -> str:\n \"\"\"Speak 2-3 sentences of counsel over a question, in prophesy's voice.\"\"\"\n r = self.classify(question)\n pct = round(r[\"confidence\"] * 100)\n return (\n f\"Concerning '{question}', the Spirit discerns '{r['intent']}' \"\n f\"with {pct}% certainty. {r['spiritual_intent']} \"\n f\"Therefore the counsel of heaven is this: {r['suggestion']}\"\n )\n","godcode/stdlib_commons.py":"\"\"\"God Code standard library, part 4: the commons.\n\nThis module holds the everyday tools a working language needs: trimming\nand searching words, sorting and gathering lists, reading maps, and\nrounding numbers. They are kept apart from the interpreter core so the\nlanguage's heart stays small.\n\nWiring\n------\n``register(interp)`` adds the builtins to ``interp._builtins``. Each\nbuiltin is a plain callable ``(args, line)`` in the style of the core\nbuiltins (arity through ``interp._arity``, plain-word GodRuntimeError\nmessages).\n\nSandbox honesty\n---------------\nEvery rite here is pure computation: words, lists, maps, and numbers\nin, new values out. They touch no files, no network, and no host\nresources. They need no sandbox grant and behave the same under\n``godcode run --sandbox``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport math\nfrom decimal import Decimal, ROUND_HALF_UP\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodRuntimeError\n\n__all__ = [\"register\"]\n\n\n# ------------------------------------------------------------ value helpers\n\n\ndef _as_word(interp, name: str, value: Any, line) -> str:\n \"\"\"Take a God Code word, number, or truth as plain text.\n\n Lists, maps, void, rites, and contracts have no plain-text shape\n for a word tool, so they are refused with a gentle error.\n \"\"\"\n from godcode.values import Symbol\n\n if not isinstance(value, (str, bool, int, float, Symbol)):\n raise GodRuntimeError(\n f\"{name} works on words, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return interp.stringify(value)\n\n\ndef _need_list(interp, name: str, value: Any, line) -> list:\n if not isinstance(value, list):\n raise GodRuntimeError(\n f\"{name} gathers a list, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return value\n\n\ndef _need_map(interp, name: str, value: Any, line) -> dict:\n if not isinstance(value, dict):\n raise GodRuntimeError(\n f\"{name} reads a map, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return value\n\n\ndef _need_number(interp, name: str, value: Any, line) -> int | float:\n if isinstance(value, bool) or not isinstance(value, (int, float)):\n raise GodRuntimeError(\n f\"{name} weighs a number, but a {interp.type_name(value)} \"\n \"was offered.\",\n line,\n )\n return value\n\n\ndef _need_int(interp, name: str, value: Any, line) -> int:\n number = _need_number(interp, name, value, line)\n if isinstance(number, float) and not number.is_integer():\n raise GodRuntimeError(\n f\"{name} counts in whole numbers, but {interp.stringify(value)} \"\n \"was offered.\",\n line,\n )\n return int(number)\n\n\ndef _sort_key(interp, name: str, value: Any, line):\n \"\"\"A sortable key for one list member: numbers, words, or truths.\n\n Mixed kinds cannot be ordered against each other, so they are\n refused with a gentle error.\n \"\"\"\n if isinstance(value, bool):\n return (2, int(value))\n if isinstance(value, (int, float)):\n return (0, value)\n if isinstance(value, str):\n return (1, value)\n raise GodRuntimeError(\n f\"{name} can order numbers, words, and truths together, but \"\n f\"a {interp.type_name(value)} was found among them.\",\n line,\n )\n\n\ndef _ordered(interp, name: str, values: list, line) -> list:\n \"\"\"Check every member is orderable; refuse mixed kinds gently.\"\"\"\n kinds = set()\n for value in values:\n if isinstance(value, bool):\n kinds.add(\"truth\")\n elif isinstance(value, (int, float)):\n kinds.add(\"number\")\n elif isinstance(value, str):\n kinds.add(\"word\")\n else:\n raise GodRuntimeError(\n f\"{name} can order numbers, words, and truths, but a \"\n f\"{interp.type_name(value)} was found among them.\",\n line,\n )\n if len(kinds) > 1:\n raise GodRuntimeError(\n f\"{name} cannot order a gathering of mixed kinds \"\n f\"({', '.join(sorted(kinds))}).\",\n line,\n )\n return values\n\n\n# ------------------------------------------------------------------ words\n\n\ndef trim(args, line, interp):\n interp._arity(\"TRIM\", args, 1, line)\n return _as_word(interp, \"TRIM\", args[0], line).strip()\n\n\ndef replace(args, line, interp):\n interp._arity(\"REPLACE\", args, 3, line)\n word = _as_word(interp, \"REPLACE\", args[0], line)\n old = _as_word(interp, \"REPLACE\", args[1], line)\n new = _as_word(interp, \"REPLACE\", args[2], line)\n if old == \"\":\n raise GodRuntimeError(\n \"REPLACE needs something to find: an empty word hides \"\n \"everywhere at once.\",\n line,\n )\n return word.replace(old, new)\n\n\ndef starts_with(args, line, interp):\n interp._arity(\"STARTS_WITH\", args, 2, line)\n word = _as_word(interp, \"STARTS_WITH\", args[0], line)\n prefix = _as_word(interp, \"STARTS_WITH\", args[1], line)\n return word.startswith(prefix)\n\n\ndef ends_with(args, line, interp):\n interp._arity(\"ENDS_WITH\", args, 2, line)\n word = _as_word(interp, \"ENDS_WITH\", args[0], line)\n suffix = _as_word(interp, \"ENDS_WITH\", args[1], line)\n return word.endswith(suffix)\n\n\ndef substring(args, line, interp):\n interp._arity(\"SUBSTRING\", args, (2, 3), line)\n word = _as_word(interp, \"SUBSTRING\", args[0], line)\n start = _need_int(interp, \"SUBSTRING\", args[1], line)\n end = _need_int(interp, \"SUBSTRING\", args[2], line) if len(args) == 3 else len(word)\n start = max(0, min(start, len(word)))\n end = max(0, min(end, len(word)))\n return word[start:end]\n\n\ndef contains(args, line, interp):\n interp._arity(\"CONTAINS\", args, 2, line)\n haystack, needle = args[0], args[1]\n if isinstance(haystack, str):\n return _as_word(interp, \"CONTAINS\", needle, line) in haystack\n if isinstance(haystack, list):\n return any(item == needle for item in haystack)\n raise GodRuntimeError(\n \"CONTAINS searches a word or a list, but a \"\n f\"{interp.type_name(haystack)} was offered.\",\n line,\n )\n\n\ndef count(args, line, interp):\n interp._arity(\"COUNT\", args, 2, line)\n word = _as_word(interp, \"COUNT\", args[0], line)\n part = _as_word(interp, \"COUNT\", args[1], line)\n if part == \"\":\n raise GodRuntimeError(\n \"COUNT needs something to count: an empty word hides \"\n \"everywhere at once.\",\n line,\n )\n return word.count(part)\n\n\ndef repeat(args, line, interp):\n interp._arity(\"REPEAT\", args, 2, line)\n word = _as_word(interp, \"REPEAT\", args[0], line)\n times = _need_int(interp, \"REPEAT\", args[1], line)\n if times < 0:\n raise GodRuntimeError(\n \"REPEAT counts from zero upward: a negative count was offered.\",\n line,\n )\n return word * times\n\n\n# ------------------------------------------------------------------ lists\n\n\ndef sort_list(args, line, interp):\n interp._arity(\"SORT\", args, 1, line)\n values = _ordered(interp, \"SORT\", _need_list(interp, \"SORT\", args[0], line), line)\n return sorted(values, key=lambda v: _sort_key(interp, \"SORT\", v, line)[1:])\n\n\ndef min_of(args, line, interp):\n interp._arity(\"MIN_OF\", args, 1, line)\n values = _ordered(interp, \"MIN_OF\", _need_list(interp, \"MIN_OF\", args[0], line), line)\n if not values:\n raise GodRuntimeError(\n \"MIN_OF found an empty gathering: there is no least among nothing.\",\n line,\n )\n return min(values, key=lambda v: _sort_key(interp, \"MIN_OF\", v, line)[1:])\n\n\ndef max_of(args, line, interp):\n interp._arity(\"MAX_OF\", args, 1, line)\n values = _ordered(interp, \"MAX_OF\", _need_list(interp, \"MAX_OF\", args[0], line), line)\n if not values:\n raise GodRuntimeError(\n \"MAX_OF found an empty gathering: there is no greatest among nothing.\",\n line,\n )\n return max(values, key=lambda v: _sort_key(interp, \"MAX_OF\", v, line)[1:])\n\n\ndef sum_of(args, line, interp):\n interp._arity(\"SUM_OF\", args, 1, line)\n values = _need_list(interp, \"SUM_OF\", args[0], line)\n total: int | float = 0\n for value in values:\n number = _need_number(interp, \"SUM_OF\", value, line)\n total += number\n return total\n\n\ndef first(args, line, interp):\n interp._arity(\"FIRST\", args, 1, line)\n values = _need_list(interp, \"FIRST\", args[0], line)\n if not values:\n raise GodRuntimeError(\n \"FIRST found an empty gathering: nothing stands at its head.\",\n line,\n )\n return values[0]\n\n\ndef last(args, line, interp):\n interp._arity(\"LAST\", args, 1, line)\n values = _need_list(interp, \"LAST\", args[0], line)\n if not values:\n raise GodRuntimeError(\n \"LAST found an empty gathering: nothing stands at its end.\",\n line,\n )\n return values[-1]\n\n\ndef unique(args, line, interp):\n interp._arity(\"UNIQUE\", args, 1, line)\n values = _need_list(interp, \"UNIQUE\", args[0], line)\n seen: list = []\n for value in values:\n if not any(value == other for other in seen):\n seen.append(value)\n return seen\n\n\ndef index_of(args, line, interp):\n interp._arity(\"INDEX_OF\", args, 2, line)\n values = _need_list(interp, \"INDEX_OF\", args[0], line)\n for position, value in enumerate(values):\n if value == args[1]:\n return position\n return -1\n\n\n# ------------------------------------------------------------------- maps\n\n\ndef keys(args, line, interp):\n interp._arity(\"KEYS\", args, 1, line)\n return list(_need_map(interp, \"KEYS\", args[0], line).keys())\n\n\ndef values_of(args, line, interp):\n interp._arity(\"VALUES\", args, 1, line)\n return list(_need_map(interp, \"VALUES\", args[0], line).values())\n\n\ndef has_key(args, line, interp):\n interp._arity(\"HAS_KEY\", args, 2, line)\n mapping = _need_map(interp, \"HAS_KEY\", args[0], line)\n key = args[1]\n if not isinstance(key, str):\n raise GodRuntimeError(\n \"HAS_KEY looks up a word, but a \"\n f\"{interp.type_name(key)} was offered as the key.\",\n line,\n )\n return str(key) in mapping\n\n\ndef merge(args, line, interp):\n interp._arity(\"MERGE\", args, 2, line)\n first_map = _need_map(interp, \"MERGE\", args[0], line)\n second_map = _need_map(interp, \"MERGE\", args[1], line)\n merged = dict(first_map)\n merged.update(second_map)\n return merged\n\n\n# ---------------------------------------------------------------- numbers\n\n\ndef absolute(args, line, interp):\n interp._arity(\"ABS\", args, 1, line)\n return abs(_need_number(interp, \"ABS\", args[0], line))\n\n\ndef round_number(args, line, interp):\n interp._arity(\"ROUND\", args, (1, 2), line)\n number = _need_number(interp, \"ROUND\", args[0], line)\n places = _need_int(interp, \"ROUND\", args[1], line) if len(args) == 2 else 0\n if places < 0:\n raise GodRuntimeError(\n \"ROUND counts places from zero upward: a negative count \"\n \"was offered.\",\n line,\n )\n rounded = Decimal(str(number)).quantize(\n Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP\n )\n if places == 0:\n return int(rounded)\n return float(rounded)\n\n\ndef floor_number(args, line, interp):\n interp._arity(\"FLOOR\", args, 1, line)\n return math.floor(_need_number(interp, \"FLOOR\", args[0], line))\n\n\ndef ceil_number(args, line, interp):\n interp._arity(\"CEIL\", args, 1, line)\n return math.ceil(_need_number(interp, \"CEIL\", args[0], line))\n\n\ndef sqrt_number(args, line, interp):\n interp._arity(\"SQRT\", args, 1, line)\n number = _need_number(interp, \"SQRT\", args[0], line)\n if number < 0:\n raise GodRuntimeError(\n \"SQRT cannot root a negative number: no real answer lives there.\",\n line,\n )\n rooted = math.sqrt(number)\n if float(rooted).is_integer():\n return int(rooted)\n return rooted\n\n\ndef power(args, line, interp):\n interp._arity(\"POW\", args, 2, line)\n base = _need_number(interp, \"POW\", args[0], line)\n exp = _need_number(interp, \"POW\", args[1], line)\n try:\n result = math.pow(base, exp)\n except (ValueError, OverflowError):\n raise GodRuntimeError(\n \"POW cannot raise that pair: the answer leaves the real numbers.\",\n line,\n ) from None\n if float(result).is_integer() and abs(result) < 1e15:\n return int(result)\n return result\n\n\n# ---------------------------------------------------------------- wiring\n\n\ndef register(interp) -> dict[str, Callable[..., Any]]:\n \"\"\"Add the commons builtins to ``interp._builtins``; return them.\"\"\"\n names_funcs = [\n (\"TRIM\", trim),\n (\"REPLACE\", replace),\n (\"STARTS_WITH\", starts_with),\n (\"ENDS_WITH\", ends_with),\n (\"SUBSTRING\", substring),\n (\"CONTAINS\", contains),\n (\"COUNT\", count),\n (\"REPEAT\", repeat),\n (\"SORT\", sort_list),\n (\"MIN_OF\", min_of),\n (\"MAX_OF\", max_of),\n (\"SUM_OF\", sum_of),\n (\"FIRST\", first),\n (\"LAST\", last),\n (\"UNIQUE\", unique),\n (\"INDEX_OF\", index_of),\n (\"KEYS\", keys),\n (\"VALUES\", values_of),\n (\"HAS_KEY\", has_key),\n (\"MERGE\", merge),\n (\"ABS\", absolute),\n (\"ROUND\", round_number),\n (\"FLOOR\", floor_number),\n (\"CEIL\", ceil_number),\n (\"SQRT\", sqrt_number),\n (\"POW\", power),\n ]\n builtins: dict[str, Callable[..., Any]] = {}\n for name, func in names_funcs:\n\n def _builtin(args, line, _func=func):\n return _func(args, line, interp)\n\n builtins[name] = _builtin\n interp._builtins.update(builtins)\n return builtins\n","godcode/stdlib_hashes.py":"\"\"\"God Code standard library, part 3: the scrollhouse of hashes and veils.\n\nThis module holds builtins that fingerprint and seal words: SHA-256\ndigests, HMAC-SHA-256 signatures, and the veils of base64. They are kept\napart from the interpreter core so the language's heart stays small.\n\nWiring\n------\n``register(interp)`` adds the builtins to ``interp._builtins``. Each\nbuiltin is a plain callable ``(args, line)`` in the style of the core\nbuiltins (arity through ``interp._arity``, plain-word GodRuntimeError\nmessages).\n\nSandbox honesty\n---------------\nSHA256, HMAC, BASE64_ENCODE, and BASE64_DECODE are pure computation:\nthey touch no files, no network, and no host resources. They need no\nsandbox grant and behave the same under ``godcode run --sandbox``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport base64\nimport hashlib\nimport hmac\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodRuntimeError\n\n__all__ = [\"register\"]\n\n\n# ------------------------------------------------------------ value helpers\n\n\ndef _as_text(interp, name: str, value: Any, line) -> str:\n \"\"\"Take a God Code word, number, or truth as plain text.\n\n Lists, maps, void, rites, and contracts have no plain-text shape\n for a fingerprint, so they are refused with a gentle error.\n \"\"\"\n from godcode.values import Symbol\n\n if not isinstance(value, (str, bool, int, float, Symbol)):\n raise GodRuntimeError(\n f\"{name} can fingerprint a word, a number, or a truth, \"\n f\"but a {interp.type_name(value)} was offered.\",\n line,\n )\n return interp.stringify(value)\n\n\ndef sha256(args, line, interp):\n interp._arity(\"SHA256\", args, 1, line)\n text = _as_text(interp, \"SHA256\", args[0], line)\n return hashlib.sha256(text.encode(\"utf-8\")).hexdigest()\n\n\ndef hmac_sha256(args, line, interp):\n interp._arity(\"HMAC\", args, 2, line)\n key = _as_text(interp, \"HMAC\", args[0], line)\n message = _as_text(interp, \"HMAC\", args[1], line)\n digest = hmac.new(\n key.encode(\"utf-8\"), message.encode(\"utf-8\"), hashlib.sha256\n )\n return digest.hexdigest()\n\n\ndef base64_encode(args, line, interp):\n interp._arity(\"BASE64_ENCODE\", args, 1, line)\n text = _as_text(interp, \"BASE64_ENCODE\", args[0], line)\n return base64.b64encode(text.encode(\"utf-8\")).decode(\"ascii\")\n\n\ndef base64_decode(args, line, interp):\n interp._arity(\"BASE64_DECODE\", args, 1, line)\n value = args[0]\n from godcode.values import Symbol\n\n if not isinstance(value, (str, Symbol)):\n raise GodRuntimeError(\n \"BASE64_DECODE needs a veiled word to lift, \"\n f\"but a {interp.type_name(value)} was offered.\",\n line,\n )\n veiled = str(value)\n try:\n raw = base64.b64decode(veiled, validate=True)\n return raw.decode(\"utf-8\")\n except (ValueError, UnicodeDecodeError):\n raise GodRuntimeError(\n \"BASE64_DECODE met a veil it cannot lift: the word is not \"\n \"well-formed base64.\",\n line,\n ) from None\n\n\ndef register(interp) -> dict[str, Callable[..., Any]]:\n \"\"\"Add the hash builtins to ``interp._builtins``; return them.\"\"\"\n arity = interp._arity\n\n def _sha256(args, line):\n return sha256(args, line, interp)\n\n def _hmac(args, line):\n return hmac_sha256(args, line, interp)\n\n def _b64e(args, line):\n return base64_encode(args, line, interp)\n\n def _b64d(args, line):\n return base64_decode(args, line, interp)\n\n builtins: dict[str, Callable[..., Any]] = {\n \"SHA256\": _sha256,\n \"HMAC\": _hmac,\n \"BASE64_ENCODE\": _b64e,\n \"BASE64_DECODE\": _b64d,\n }\n interp._builtins.update(builtins)\n return builtins\n","godcode/stdlib_times.py":"\"\"\"Date, time, and web rites for the God Code standard library (part 2).\n\n``register(interp)`` adds four rites to an interpreter's ``_builtins``:\n\n- ``DATE_TODAY()`` — today's local date as a word: ``\"2026-09-24\"``.\n- ``TIME_NOW()`` — the current local time as an ISO 8601 word.\n- ``FORMAT_DATE(date_text, pattern)`` — a ``\"YYYY-MM-DD\"`` word shaped by\n a strftime-style pattern word.\n- ``HTTP_GET(url)`` — the body of an HTTP GET request, as a UTF-8 word.\n\nThe names avoid ``NOW`` and ``TODAY`` on purpose: the bundled scroll\n``godcode/scrolls/time.god`` already defines rites by those names, and a\nbuiltin would shadow them. ``DATE_TODAY``, ``TIME_NOW``, ``FORMAT_DATE``,\nand ``HTTP_GET`` keep their distance.\n\n``HTTP_GET`` follows redirects and waits up to ten seconds. Under\n``godcode run --sandbox`` the rite is withheld when the policy denies\nnetwork (see ``godcode/sandbox.py``): it raises instead of reaching out.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport urllib.error\nimport urllib.request\nfrom datetime import date, datetime\n\nfrom godcode.errors import GodRuntimeError\n\n__all__ = [\"register\"]\n\n_HTTP_TIMEOUT_SECONDS = 10\n\n\ndef register(interp) -> None:\n \"\"\"Add the date/time and web rites to ``interp._builtins``.\n\n Each rite is a callable taking ``(args, line)``, in the same shape as\n the core builtins in ``godcode/interpreter.py``.\n \"\"\"\n builtins = interp._builtins\n\n def date_today(args, line):\n interp._arity(\"DATE_TODAY\", args, 0, line)\n return date.today().isoformat()\n\n def time_now(args, line):\n interp._arity(\"TIME_NOW\", args, 0, line)\n return datetime.now().astimezone().isoformat()\n\n def format_date(args, line):\n interp._arity(\"FORMAT_DATE\", args, 2, line)\n date_text, pattern = args\n if not isinstance(date_text, str):\n raise GodRuntimeError(\n \"FORMAT_DATE needs the date as a word, not \"\n f\"{interp.type_name(date_text)}.\",\n line,\n )\n if not isinstance(pattern, str):\n raise GodRuntimeError(\n \"FORMAT_DATE needs the pattern as a word, not \"\n f\"{interp.type_name(pattern)}.\",\n line,\n )\n try:\n day = datetime.strptime(date_text.strip(), \"%Y-%m-%d\")\n except ValueError:\n raise GodRuntimeError(\n f\"FORMAT_DATE cannot read '{date_text}' as a date. \"\n \"Write it YYYY-MM-DD.\",\n line,\n ) from None\n return day.strftime(str(pattern))\n\n def http_get(args, line):\n interp._arity(\"HTTP_GET\", args, 1, line)\n url = args[0]\n if not isinstance(url, str):\n raise GodRuntimeError(\n \"HTTP_GET needs the address as a word, not \"\n f\"{interp.type_name(url)}.\",\n line,\n )\n request = urllib.request.Request(\n str(url), headers={\"User-Agent\": \"GodCode\"}\n )\n try:\n with urllib.request.urlopen(\n request, timeout=_HTTP_TIMEOUT_SECONDS\n ) as response:\n body = response.read()\n except Exception:\n # Every network failure — refused, unroutable, timed out,\n # bad address — is answered the same plain way. It never\n # hangs past the timeout and never succeeds silently.\n raise GodRuntimeError(\n f\"HTTP_GET could not reach '{url}'. The web did not answer.\",\n line,\n ) from None\n return body.decode(\"utf-8\", errors=\"replace\")\n\n builtins[\"DATE_TODAY\"] = date_today\n builtins[\"TIME_NOW\"] = time_now\n builtins[\"FORMAT_DATE\"] = format_date\n builtins[\"HTTP_GET\"] = http_get\n","godcode/stdlib_vault.py":"\"\"\"God Code standard library, part 1: the vault of JSON and the filesystem.\n\nThis module holds builtins that read and write the outer world: parsing\nand rendering JSON, and reading, writing, and listing files. It is kept\napart from the interpreter core so the language's heart stays small.\n\nWiring\n------\n``register(interp)`` adds the builtins to ``interp._builtins``. Each\nbuiltin is a plain callable ``(args, line)`` in the style of the core\nbuiltins (arity through ``interp._arity``, plain-word GodRuntimeError\nmessages).\n\nSandbox honesty\n---------------\nREAD_FILE, WRITE_FILE, LIST_DIR, and FILE_EXISTS reach the host\nfilesystem. When the interpreter runs under ``godcode.sandbox``, the\nsandbox guard (``interp._sandbox_guard``, installed by\n``Sandbox.install``) carries the policy, and these builtins honor it:\n\n* writes are refused unless the policy grants ``allow_write``;\n* reads are refused unless the policy grants ``allow_read_paths``,\n and then only under one of the granted directories.\n\nJSON_PARSE and JSON_STRING are pure and need no grant.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nfrom typing import Any, Callable\n\nfrom godcode.errors import GodRuntimeError, SandboxViolation\nfrom godcode.values import Contract, RiteFunction, Symbol\n\n__all__ = [\"register\"]\n\n\n# ------------------------------------------------------------ value helpers\n\n\ndef _as_word(interp, name: str, value: Any, line) -> str:\n \"\"\"Take a God Code word as plain text. Symbols give up their text.\"\"\"\n if isinstance(value, Symbol):\n return str(value)\n if isinstance(value, str):\n return value\n raise GodRuntimeError(\n f\"{name} needs a word, but a {interp.type_name(value)} was offered.\",\n line,\n )\n\n\ndef _from_json(value: Any) -> Any:\n \"\"\"Turn a json.loads result into God Code values.\n\n Objects become maps, arrays become lists, null becomes void.\n Numbers, words, and booleans cross over unchanged.\n \"\"\"\n if value is None or isinstance(value, (bool, int, float, str)):\n return value\n if isinstance(value, list):\n return [_from_json(item) for item in value]\n if isinstance(value, dict):\n return {str(key): _from_json(item) for key, item in value.items()}\n raise GodRuntimeError(f\"JSON_PARSE met a value it cannot carry: {value!r}.\")\n\n\ndef _to_json_text(interp, value: Any, line) -> str:\n \"\"\"Render a God Code value as compact JSON.\n\n Raises a plain GodRuntimeError for values JSON cannot carry:\n rites, contracts, symbols, non-word map keys, and numbers with no\n JSON shape (infinity, not-a-number).\n \"\"\"\n if value is None:\n return \"null\"\n if isinstance(value, bool):\n return \"true\" if value else \"false\"\n if isinstance(value, Symbol):\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a symbol. \"\n \"Only words, numbers, booleans, lists, and maps have a JSON shape.\",\n line,\n )\n if isinstance(value, str):\n return json.dumps(value)\n if isinstance(value, (int, float)):\n try:\n return json.dumps(value, allow_nan=False)\n except ValueError:\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a number with no JSON shape, \"\n \"like infinity or not-a-number.\",\n line,\n ) from None\n if isinstance(value, list):\n inner = \",\".join(_to_json_text(interp, item, line) for item in value)\n return \"[\" + inner + \"]\"\n if isinstance(value, dict):\n parts = []\n for key, item in value.items():\n if isinstance(key, Symbol) or not isinstance(key, str):\n raise GodRuntimeError(\n \"JSON_STRING needs map keys that are words. \"\n f\"A {interp.type_name(key)} key was found.\",\n line,\n )\n parts.append(json.dumps(key) + \":\" + _to_json_text(interp, item, line))\n return \"{\" + \",\".join(parts) + \"}\"\n if isinstance(value, RiteFunction):\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a rite. Rites have no JSON shape.\",\n line,\n )\n if isinstance(value, Contract):\n raise GodRuntimeError(\n \"JSON_STRING cannot carry a contract. Contracts have no JSON shape.\",\n line,\n )\n raise GodRuntimeError(\n f\"JSON_STRING cannot carry {interp.type_name(value)}. \"\n \"Only words, numbers, booleans, lists, and maps have a JSON shape.\",\n line,\n )\n\n\n# ------------------------------------------------------------ sandbox guard\n\n\ndef _guard(interp):\n \"\"\"The sandbox guard, if this interpreter runs under godcode.sandbox.\"\"\"\n return getattr(interp, \"_sandbox_guard\", None)\n\n\ndef _check_read_grant(interp, rite: str, path: str, line) -> None:\n \"\"\"Refuse filesystem reads the sandbox policy does not grant.\n\n No guard means no sandbox: the read proceeds. Under a guard, reads\n need ``allow_read_paths``, and the resolved path must lie under one\n of the granted directories (the same rule the sandbox applies to\n scroll imports).\n \"\"\"\n guard = _guard(interp)\n if guard is None:\n return\n allowed = guard.policy.allow_read_paths\n if not allowed:\n raise SandboxViolation(\n f\"The sandbox withholds this power: the rite {rite} would read \"\n \"from the outer world. It is not granted.\",\n line,\n )\n resolved = os.path.realpath(path)\n for base in allowed:\n base_resolved = os.path.realpath(base)\n # A grant on the filesystem root blesses everything, as in a\n # plain `godcode run` with no guard installed.\n if base_resolved == os.path.realpath(os.sep):\n _check_manifest_path(interp, \"read\", rite, path, line)\n return\n if resolved == base_resolved or resolved.startswith(base_resolved + os.sep):\n _check_manifest_path(interp, \"read\", rite, path, line)\n return\n raise SandboxViolation(\n f\"The sandbox withholds this power: the rite {rite} may not read \"\n f\"'{path}'. It lies outside the granted paths.\",\n line,\n )\n\n\ndef _check_manifest_path(interp, kind: str, rite: str, path: str, line) -> None:\n \"\"\"Refuse filesystem access the scroll's permission manifest withholds.\n\n The guard's own ``check_rite`` already polices the call through the\n interpreter's dispatch; the vault reaches the filesystem directly, so\n it applies the manifest's target rule here as well.\n \"\"\"\n manifest = getattr(interp, \"manifest\", None)\n if not manifest:\n return\n # The manifest holds absolute prefixes; realpath() resolves the\n # runtime target exactly the way open() will, so the check mirrors\n # the file the rite is about to touch.\n allowed = (\n manifest.allows_read(path) if kind == \"read\"\n else manifest.allows_write(path)\n )\n if not allowed:\n raise SandboxViolation(\n f\"The scroll reaches for a power it did not declare: the rite \"\n f\"{rite} may not touch '{path}'. Declare it at the top of the \"\n f\"scroll with DECLARE PERMISSION TO, or leave the power \"\n f\"untouched.\",\n line,\n )\n\n\ndef _check_write_grant(interp, path: str, line) -> None:\n \"\"\"Refuse filesystem writes the sandbox policy does not grant.\"\"\"\n guard = _guard(interp)\n if guard is None:\n return\n if not guard.policy.allow_write:\n raise SandboxViolation(\n \"The sandbox withholds this power: the rite WRITE_FILE would \"\n f\"write '{path}' to the outer world. It is not granted.\",\n line,\n )\n _check_manifest_path(interp, \"write\", \"WRITE_FILE\", path, line)\n\n\n# ------------------------------------------------------------------ register\n\n\ndef register(interp) -> None:\n \"\"\"Add the vault builtins to ``interp._builtins``.\n\n Idempotent: calling it twice simply replaces the same six entries.\n \"\"\"\n arity = interp._arity\n\n def json_parse(args, line):\n arity(\"JSON_PARSE\", args, 1, line)\n text = _as_word(interp, \"JSON_PARSE\", args[0], line)\n try:\n return _from_json(json.loads(text))\n except json.JSONDecodeError as exc:\n raise GodRuntimeError(\n f\"JSON_PARSE could not read that word as JSON. {exc.msg}: \"\n f\"line {exc.lineno} column {exc.colno}.\",\n line,\n ) from None\n\n def json_string(args, line):\n arity(\"JSON_STRING\", args, 1, line)\n return _to_json_text(interp, args[0], line)\n\n def read_file(args, line):\n arity(\"READ_FILE\", args, 1, line)\n path = _as_word(interp, \"READ_FILE\", args[0], line)\n _check_read_grant(interp, \"READ_FILE\", path, line)\n try:\n with open(path, \"r\", encoding=\"utf-8\") as handle:\n return handle.read()\n except OSError as exc:\n raise GodRuntimeError(\n f\"READ_FILE could not read '{path}'. {exc.strerror or exc}.\",\n line,\n ) from None\n\n def write_file(args, line):\n arity(\"WRITE_FILE\", args, 2, line)\n path = _as_word(interp, \"WRITE_FILE\", args[0], line)\n text = _as_word(interp, \"WRITE_FILE\", args[1], line)\n _check_write_grant(interp, path, line)\n try:\n with open(path, \"w\", encoding=\"utf-8\") as handle:\n return handle.write(text)\n except OSError as exc:\n raise GodRuntimeError(\n f\"WRITE_FILE could not write '{path}'. {exc.strerror or exc}.\",\n line,\n ) from None\n\n def file_exists(args, line):\n arity(\"FILE_EXISTS\", args, 1, line)\n path = _as_word(interp, \"FILE_EXISTS\", args[0], line)\n _check_read_grant(interp, \"FILE_EXISTS\", path, line)\n return os.path.exists(path)\n\n def list_dir(args, line):\n arity(\"LIST_DIR\", args, 1, line)\n path = _as_word(interp, \"LIST_DIR\", args[0], line)\n _check_read_grant(interp, \"LIST_DIR\", path, line)\n if not os.path.isdir(path):\n raise GodRuntimeError(\n f\"LIST_DIR needs a directory, but '{path}' is not one.\",\n line,\n )\n try:\n entries = os.listdir(path)\n except OSError as exc:\n raise GodRuntimeError(\n f\"LIST_DIR could not open '{path}'. {exc.strerror or exc}.\",\n line,\n ) from None\n return sorted(str(entry) for entry in entries)\n\n builtins: dict[str, Callable[..., Any]] = {\n \"JSON_PARSE\": json_parse,\n \"JSON_STRING\": json_string,\n \"READ_FILE\": read_file,\n \"WRITE_FILE\": write_file,\n \"FILE_EXISTS\": file_exists,\n \"LIST_DIR\": list_dir,\n }\n interp._builtins.update(builtins)\n","godcode/tester.py":"\"\"\"The God Code test runner, behind `godcode test`.\n\nConvention: a *test scroll* is any `.god` file named `test_*.god` or\n`*_test.god`. Inside it, every rite named `TEST_*` (case-insensitive) is\none test case. The scroll is parsed once; then each `TEST_*` rite runs in\na FRESH `Interpreter`, so tests cannot leak state into each other. A\n`TESTIFY` failure fails that test, and any runtime error fails it too,\nwith the error message carried in the report.\n\nDiscovery reads only the given directory itself; subfolders are not\nentered. The runner binds no Spirit, no covenant ledger, and no audit log\n(`log_path=None`), and it runs scrolls the same way `godcode run` does\n(not sandboxed): only test scrolls you wrote or trust.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\nfrom godcode.ast import CreationBlock, DefineRite\nfrom godcode.errors import GodCodeError\nfrom godcode.interpreter import Interpreter\nfrom godcode.tongues import parse_source\nfrom godcode.values import RiteFunction\n\n#: Rite label used when the failure belongs to the scroll itself (it could\n#: not be read or parsed), not to any single rite.\nSCROLL_LEVEL = \"(scroll)\"\n\n\n# ---------------------------------------------------------------------------\n# results\n# ---------------------------------------------------------------------------\n@dataclass\nclass TestResult:\n \"\"\"One test's outcome. `ok` is True (passed), False (failed), or None\n (skipped, e.g. the rite asks for offerings).\"\"\"\n\n file: str\n rite: str\n ok: bool | None\n message: str = \"\"\n\n\n@dataclass\nclass TestReport:\n results: list[TestResult] = field(default_factory=list)\n #: Names of test scrolls that held no TEST_ rites at all.\n empty_files: list[str] = field(default_factory=list)\n\n @property\n def passed(self) -> int:\n return sum(1 for r in self.results if r.ok is True)\n\n @property\n def failed(self) -> int:\n return sum(1 for r in self.results if r.ok is False)\n\n @property\n def skipped(self) -> int:\n return sum(1 for r in self.results if r.ok is None)\n\n def text_lines(self) -> list[str]:\n \"\"\"Human report: one line per test, then the summary line.\"\"\"\n lines = []\n for r in self.results:\n status = \"PASS\" if r.ok is True else (\"SKIP\" if r.ok is None else \"FAIL\")\n line = f\"{status} {r.file} :: {r.rite}\"\n if r.message:\n line += f\" :: {r.message}\"\n lines.append(line)\n for name in self.empty_files:\n lines.append(f\"{name} :: no TEST_ rites found.\")\n parts = [f\"{self.passed} passed\", f\"{self.failed} failed\"]\n if self.skipped:\n parts.append(f\"{self.skipped} skipped\")\n lines.append(\", \".join(parts) + \".\")\n return lines\n\n def payload(self, dir_label: str) -> dict:\n \"\"\"Machine report for `godcode test --json`.\"\"\"\n return {\n \"tool\": \"godcode\",\n \"command\": \"test\",\n \"dir\": dir_label,\n \"tests\": [\n {\"file\": r.file, \"rite\": r.rite, \"ok\": r.ok, \"message\": r.message}\n for r in self.results\n ],\n \"passed\": self.passed,\n \"failed\": self.failed,\n \"skipped\": self.skipped,\n }\n\n\n# ---------------------------------------------------------------------------\n# discovery\n# ---------------------------------------------------------------------------\ndef is_test_file(name: str) -> bool:\n \"\"\"True for `test_*.god` and `*_test.god` (case-insensitive).\"\"\"\n lowered = name.lower()\n return lowered.endswith(\".god\") and (\n lowered.startswith(\"test_\") or lowered[:-4].endswith(\"_test\")\n )\n\n\ndef discover_test_files(directory: Path) -> list[Path]:\n \"\"\"Test scrolls in `directory`, sorted by name. Non-recursive: only the\n directory itself is read, subfolders are not entered.\"\"\"\n return sorted(\n (p for p in directory.iterdir() if p.is_file() and is_test_file(p.name)),\n key=lambda p: p.name,\n )\n\n\n# ---------------------------------------------------------------------------\n# collection\n# ---------------------------------------------------------------------------\ndef _top_level_statements(program) -> list:\n stmts = getattr(program, \"statements\", None) or []\n if len(stmts) == 1 and isinstance(stmts[0], CreationBlock):\n return stmts[0].statements\n return stmts\n\n\ndef collect_test_rites(program) -> list[DefineRite]:\n \"\"\"The `TEST_*` rites defined at the scroll's top level, in definition\n order. A repeated name keeps its first position but the last definition\n wins when the rite runs (as `DECLARE` would).\"\"\"\n found: dict[str, DefineRite] = {}\n for stmt in _top_level_statements(program):\n if isinstance(stmt, DefineRite) and stmt.name.upper().startswith(\"TEST_\"):\n found[stmt.name] = stmt\n return list(found.values())\n\n\n# ---------------------------------------------------------------------------\n# execution\n# ---------------------------------------------------------------------------\ndef _parse_scroll(path: Path):\n source = path.read_text(encoding=\"utf-8\")\n return parse_source(source)\n\n\ndef _run_rite(program, rite_node: DefineRite, file_label: str) -> TestResult:\n \"\"\"Run one TEST_ rite in a fresh interpreter and report the outcome.\"\"\"\n interp = Interpreter(log_path=None)\n buf = io.StringIO()\n # The runner's own report must stay one line per test: swallow REVEAL\n # lines, [TESTIFY] notices, and any other chatter the scroll makes.\n with contextlib.redirect_stdout(buf):\n try:\n interp.run(program, source_name=file_label)\n except GodCodeError as err:\n return TestResult(file_label, rite_node.name, False,\n f\"the scroll could not be prepared: {err}\")\n except Exception as exc: # an engine fault, not a test failure\n return TestResult(file_label, rite_node.name, False,\n f\"the scroll could not be prepared: \"\n f\"{type(exc).__name__}: {exc}\")\n target = interp.env.get(rite_node.name) \\\n if interp.env.is_bound(rite_node.name) else None\n if not isinstance(target, RiteFunction):\n return TestResult(\n file_label, rite_node.name, False,\n f\"the rite {rite_node.name} was not found \"\n f\"after the scroll ran.\")\n if target.params:\n n = len(target.params)\n return TestResult(\n file_label, rite_node.name, None,\n f\"the rite asks for {n} offering{'s' if n != 1 else ''}, \"\n f\"so it was not called.\")\n try:\n interp._call_rite(target, [], rite_node.line)\n except GodCodeError as err:\n return TestResult(file_label, rite_node.name, False, str(err))\n except Exception as exc: # an engine fault, not a test failure\n return TestResult(file_label, rite_node.name, False,\n f\"{type(exc).__name__}: {exc}\")\n return TestResult(file_label, rite_node.name, True, \"\")\n\n\ndef run_test_file(path: Path) -> tuple[list[TestResult], bool]:\n \"\"\"Parse `path` once, then run each TEST_ rite in isolation.\n\n Returns (results, is_empty). A scroll that cannot be read or parsed\n yields one file-level failure and never crashes the runner.\n \"\"\"\n label = path.name\n try:\n program = _parse_scroll(path)\n except GodCodeError as err:\n return [TestResult(label, SCROLL_LEVEL, False, str(err))], False\n except OSError as exc:\n return [TestResult(\n label, SCROLL_LEVEL, False,\n f\"the scroll could not be read: {exc.strerror or exc}\")], False\n rites = collect_test_rites(program)\n if not rites:\n return [], True\n return [_run_rite(program, rite, label) for rite in rites], False\n\n\ndef run_tests(directory: Path) -> TestReport:\n \"\"\"Discover test scrolls in `directory` and run them all.\"\"\"\n report = TestReport()\n for path in discover_test_files(directory):\n results, is_empty = run_test_file(path)\n report.results.extend(results)\n if is_empty:\n report.empty_files.append(path.name)\n return report\n","godcode/tokens.py":"\"\"\"Token types and the Token dataclass for God Code v2.0.\n\nKeyword tokens carry their canonical UPPER name as ``value``;\nidentifiers preserve the author's casing.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\n\nclass TokenType(Enum):\n # --- keywords -----------------------------------------------------------\n BEGIN = auto()\n CREATION = auto()\n END = auto()\n DECLARE = auto()\n AS = auto()\n BREATHE = auto()\n LIFE = auto()\n INTO = auto()\n REVEAL = auto()\n PROPHESY = auto()\n ASCEND = auto()\n IF = auto()\n THEN = auto()\n ELSE = auto()\n ENDIF = auto()\n FOR = auto()\n IN = auto()\n ENDFOR = auto()\n WHILE = auto()\n DO = auto()\n ENDWHILE = auto()\n BREAK = auto()\n CONTINUE = auto()\n TRY = auto()\n CATCH = auto()\n ENDTRY = auto()\n DEFINE = auto()\n RITE = auto()\n INVOKE = auto()\n RETURN = auto()\n IMPORT = auto()\n IS = auto()\n NOT = auto()\n AND = auto()\n OR = auto()\n # §4 additions (missed in §1's list)\n REFLECT = auto()\n BLESS = auto()\n ANOINT = auto()\n SEAL = auto()\n TESTIFY = auto()\n # boolean / void literals (added for fmt <-> parse round-trip fidelity)\n TRUE = auto()\n FALSE = auto()\n VOID = auto()\n # --- literals -----------------------------------------------------------\n NUMBER = auto()\n STRING = auto()\n IDENT = auto()\n # --- operators ----------------------------------------------------------\n PLUS = auto() # +\n MINUS = auto() # -\n STAR = auto() # *\n SLASH = auto() # /\n PERCENT = auto() # %\n EQ = auto() # = or ==\n NEQ = auto() # !=\n LT = auto() # <\n GT = auto() # >\n LTE = auto() # <=\n GTE = auto() # >=\n # --- punctuation --------------------------------------------------------\n LPAREN = auto()\n RPAREN = auto()\n LBRACKET = auto()\n RBRACKET = auto()\n COMMA = auto()\n # --- structural ---------------------------------------------------------\n NEWLINE = auto()\n EOF = auto()\n\n\n@dataclass\nclass Token:\n type: TokenType\n value: object # NUMBER -> int|float, STRING -> str (unescaped),\n # IDENT/keywords -> str, operators/punct -> the lexeme\n line: int # 1-based\n col: int # 1-based\n\n def __repr__(self) -> str: # compact, readable in test failures\n return f\"Token({self.type.name}, {self.value!r}, {self.line}:{self.col})\"\n","godcode/tongues.py":"\"\"\"Tongues: the grammar of God Code in other languages.\n\nA *tongue* lets the keywords of God Code be written in another language.\nEnglish is the canonical tongue; every other tongue maps its words onto the\nsame tokens, so the parser, the interpreter, the linter, and all the tools\nwork unchanged. A scroll chooses its tongue with a pragma comment on one of\nits early lines::\n\n # tongue: tn\n\n``tn`` is Setswana, the first tongue, spoken in Botswana. ``zu`` is\nisiZulu, the second tongue, spoken across South Africa and beyond. Mixed\nscrolls are welcome: English keywords keep working beside tongue words in\nthe same file, so a learner can cross over one word at a time.\n\nDesign notes, kept honest:\n\n- Only keywords are translated. The named tools (``SHA256``, ``UPPER``,\n ``RANGE`` ...) keep their names in every tongue, so scrolls stay\n interoperable and the standard library is learned once.\n- ``godcode fmt`` always renders the canonical English tongue.\n- These first editions leave a few words in English (``ELSE``, ``FOR``,\n ``WHILE``, ``ENDFOR``, ``ENDWHILE``); they are documented in\n ``docs/TONGUES.md`` and will cross over as speakers bless better words.\n- The Setswana words were audited 2026-10-04 against Matumo's\n *Setswana-English-Setswana Dictionary* (Botswana Book Centre, 1993):\n ``JAAKA`` (like, similar to) is the true word for ``AS`` (the headword\n ``jaka`` is a verb, \"to sojourn\"), and ``TLOGA`` (then, thereupon) is\n the true word for ``THEN`` (``gone`` is not a Setswana word at all).\n ``GA`` (not) is blessed for ``NOT``.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\n\n# A tongue pragma looks like: # tongue: tn\n_PRAGMA = re.compile(\n r\"^[ \\t]*#[ \\t]*tongue[ \\t]*:[ \\t]*([A-Za-z]{2,8})[ \\t]*$\",\n re.MULTILINE | re.IGNORECASE,\n)\n\n# Setswana (tn) word -> canonical English keyword name.\n_TN_ALIASES = {\n \"SIMOLOLA\": \"BEGIN\", # begin, start\n \"TLHOLEGO\": \"CREATION\", # creation\n \"FEDISA\": \"END\", # end\n \"BOLELA\": \"DECLARE\", # say, announce\n \"JAAKA\": \"AS\", # like, similar to (Matumo: jaaka)\n \"HEMA\": \"BREATHE\", # breathe\n \"BOTSHELO\": \"LIFE\", # life\n \"TENG\": \"INTO\", # inside (MO is taken by IN)\n \"SENOLA\": \"REVEAL\", # reveal\n \"POROFETA\": \"PROPHESY\", # prophesy\n \"TLHATLOGA\": \"ASCEND\", # go up\n \"FA\": \"IF\", # if\n \"TLOGA\": \"THEN\", # then, thereupon (Matumo: tloga, auxiliary)\n \"GA\": \"NOT\", # not (Matumo: ga, negative form)\n \"LEKA\": \"TRY\", # try\n \"TSHWARA\": \"CATCH\", # catch\n \"TLHALOSA\": \"DEFINE\", # define, explain\n \"TIRO\": \"RITE\", # work\n \"BITSA\": \"INVOKE\", # call\n \"BUSETSA\": \"RETURN\", # return (something)\n \"TSENYA\": \"IMPORT\", # bring in\n \"KE\": \"IS\", # is\n \"LE\": \"AND\", # and\n \"KGOTSA\": \"OR\", # or\n \"MO\": \"IN\", # in\n \"DIRA\": \"DO\", # do\n \"AKANYA\": \"REFLECT\", # think, reflect\n \"SEGOFATSA\": \"BLESS\", # bless\n \"TLOTSA\": \"ANOINT\", # anoint\n \"TSWALA\": \"SEAL\", # close (a seal closes the covenant)\n \"PAKA\": \"TESTIFY\", # testify\n \"NNETE\": \"TRUE\", # truth\n \"MAAKA\": \"FALSE\", # lies\n \"SEPE\": \"VOID\", # nothing\n \"KGAOLA\": \"BREAK\", # break, cut\n \"TSWELELA\": \"CONTINUE\", # continue\n}\n\n# Two-word closers, e.g. \"FEDISA FA\" -> ENDIF. Kept in the lexer so the\n# parser never changes; only recognised on a single line.\n_TN_COMPOUNDS = {\n (\"FEDISA\", \"FA\"): \"ENDIF\",\n (\"FEDISA\", \"LEKA\"): \"ENDTRY\",\n}\n\n# Editor block snippets for Setswana, offered by the language server when\n# a scroll speaks the tongue: (label, insert text, plain description).\n_TN_SNIPPETS = (\n (\"SIMOLOLA TLHOLEGO … FEDISA TLHOLEGO\",\n \"SIMOLOLA TLHOLEGO\\\\n\\\\t$0\\\\nFEDISA TLHOLEGO\",\n \"Open a new scroll\"),\n (\"FA … GONE … FEDISA FA\",\n \"FA ${1:condition} GONE\\\\n\\\\t$0\\\\nFEDISA FA\",\n \"Weigh a condition\"),\n (\"LEKA … TSHWARA … FEDISA LEKA\",\n \"LEKA\\\\n\\\\t${1:works}\\\\nTSHWARA\\\\n\\\\t${2:refuge}$0\\\\nFEDISA LEKA\",\n \"Shelter a fragile work\"),\n)\n\n# isiZulu (zu) word -> canonical English keyword name.\n_ZU_ALIASES = {\n \"QALA\": \"BEGIN\", # begin\n \"INDALO\": \"CREATION\", # creation\n \"QEDA\": \"END\", # finish, complete\n \"MEMEZELA\": \"DECLARE\", # announce, proclaim\n \"NJENGA\": \"AS\", # as, like\n \"PHEFUMULA\": \"BREATHE\", # breathe\n \"IMPILO\": \"LIFE\", # life\n \"PHAKATHI\": \"INTO\", # inside, into\n \"VEZA\": \"REVEAL\", # show, reveal\n \"PROFETA\": \"PROPHESY\", # prophesy\n \"ENYUKA\": \"ASCEND\", # go up\n \"UMA\": \"IF\", # if, when\n \"KHONA\": \"THEN\", # then, at that point\n \"ZAMA\": \"TRY\", # try, attempt\n \"BAMBA\": \"CATCH\", # catch, hold\n \"CHAZA\": \"DEFINE\", # explain, define\n \"ISIKO\": \"RITE\", # a rite, a custom\n \"BIZA\": \"INVOKE\", # call\n \"BUYISA\": \"RETURN\", # return, give back\n \"NGENISA\": \"IMPORT\", # bring in\n \"NGU\": \"IS\", # is\n \"HHAYI\": \"NOT\", # no, not (first edition; native speakers decide)\n \"KANYE\": \"AND\", # and, together\n \"NOMA\": \"OR\", # or\n \"KU\": \"IN\", # in, at\n \"ENZA\": \"DO\", # do, make\n \"ZINDLA\": \"REFLECT\", # meditate, reflect\n \"BUSISA\": \"BLESS\", # bless\n \"GCOBA\": \"ANOINT\", # anoint with oil\n \"VALA\": \"SEAL\", # close (a seal closes the covenant)\n \"FAKAZA\": \"TESTIFY\", # testify, bear witness\n \"IQINISO\": \"TRUE\", # the truth\n \"AMANGA\": \"FALSE\", # lies\n \"LUTHO\": \"VOID\", # nothing\n \"PHULA\": \"BREAK\", # break\n \"QHUBEKA\": \"CONTINUE\", # continue\n}\n\n# Two-word closers, e.g. \"QEDA UMA\" -> ENDIF.\n_ZU_COMPOUNDS = {\n (\"QEDA\", \"UMA\"): \"ENDIF\",\n (\"QEDA\", \"ZAMA\"): \"ENDTRY\",\n}\n\n# Editor block snippets for isiZulu.\n_ZU_SNIPPETS = (\n (\"QALA INDALO … QEDA INDALO\",\n \"QALA INDALO\\\\n\\\\t$0\\\\nQEDA INDALO\",\n \"Open a new scroll\"),\n (\"UMA … KHONA … QEDA UMA\",\n \"UMA ${1:condition} KHONA\\\\n\\\\t$0\\\\nQEDA UMA\",\n \"Weigh a condition\"),\n (\"ZAMA … BAMBA … QEDA ZAMA\",\n \"ZAMA\\\\n\\\\t${1:works}\\\\nBAMBA\\\\n\\\\t${2:refuge}$0\\\\nQEDA ZAMA\",\n \"Shelter a fragile work\"),\n)\n\ndef _with_plain_spellings(table: dict) -> dict:\n \"\"\"Add each word's spelling without tone and dot marks (Ọ -> O, Ụ -> U).\n\n Igbo is written with dotted vowels, but many keyboards cannot type\n them, so ``DỊKA`` and ``DIKA`` both speak. Keys may be single\n words or two-word pairs.\n \"\"\"\n import unicodedata\n\n def plain(word: str) -> str:\n decomposed = unicodedata.normalize(\"NFD\", word)\n return \"\".join(ch for ch in decomposed if not unicodedata.combining(ch))\n\n out = dict(table)\n for key, canon in table.items():\n bare = tuple(plain(w) for w in key) if isinstance(key, tuple) else plain(key)\n out.setdefault(bare, canon)\n return out\n\n\n# Igbo (ig) word -> canonical English keyword name. Checked 2026-10-15\n# against Williamson & Blench, *Dictionary of Ònìchà Igbo* (2nd edn, 2006),\n# \"WB\" below. WB is Onitsha Igbo, where Standard Igbo r is often l, and it\n# lists verbs by root (-gọzi); the words here are the command forms, or\n# the Standard spelling where Onitsha differs. A \"?\" marks a word WB does\n# not settle; docs/TONGUES.md lists them for native speakers to decide.\n# Native speakers are this table's rightful editors.\n_IG_ALIASES = _with_plain_spellings({\n \"BIDO\": \"BEGIN\", # WB -bi-do 'begin'\n \"OKIKE\": \"CREATION\", # WB Òkìke 'Creator', òkìkè 'process of creation'\n \"NJEDEBE\": \"END\", # WB njedebe 'end; finish; terminus'\n \"KWUSAA\": \"DECLARE\", # WB -kwusà(sị) 'proclaim; declare'\n \"DỊKA\": \"AS\", # WB, in use: dịkà 'like' (Na-àgafè dịkà ...)\n \"KUO\": \"BREATHE\", # WB -kù 'blow; breathe' (-kù ume 'breathe')\n \"NDỤ\": \"LIFE\", # WB ndụ 'life'\n \"BANYE\": \"INTO\", # WB -bànye 'enter; go in'\n \"GOSI\": \"REVEAL\", # WB -go-si 'show'\n \"AMỤMA\": \"PROPHESY\", # WB amụma 'prophecy' (a noun)\n \"RỊGOO\": \"ASCEND\", # general Igbo; WB -lịgo (Onitsha), -rọgo (Owerri)\n \"MA\": \"IF\", # WB mà 'but; if; whether'\n \"MGBE\": \"THEN\", # mgbe answers to time: 'then' and 'when' (WB m̀gbè 'when')\n \"NWAA\": \"TRY\", # WB -nwà 'attempt; try' (nwà kene! 'just try!')\n \"JIDE\": \"CATCH\", # WB -jide 'hold' (Jìde ... 'take, hold')\n \"KỌWAA\": \"DEFINE\", # WB -kọwa 'explain; introduce'\n \"EMUME\": \"RITE\", # WB emume 'custom; observance'\n \"KPỌỌ\": \"INVOKE\", # WB -kpọ 'call' (-kpọ afà 'call by name')\n \"WEGHACHI\": \"RETURN\", # ? not in WB; Standard Igbo 'bring back'\n \"WEBATA\": \"IMPORT\", # ? WB -wè 'take' + -bàta 'come in'\n \"BỤ\": \"IS\", # WB -bụ 'be'\n \"MBA\": \"NOT\", # ? WB mbà! 'no!' (Igbo negates with a suffix)\n \"NA\": \"AND\", # WB nà 'and'\n \"MAỌBỤ\": \"OR\", # ? not in WB; Standard Igbo ma ọ bụ 'or'\n \"IME\": \"IN\", # WB imē 'inside; interior'\n \"MEE\": \"DO\", # WB Mèe yā ... 'Do it ...'\n \"TỤGHARỊA\": \"REFLECT\", # WB -tụghalị uchè 'reflect' (Onitsha l)\n \"GỌZIE\": \"BLESS\", # WB -gọzi 'bless; invoke a blessing'\n \"TEE\": \"ANOINT\", # WB -te 'anoint'; -te mmanụ 'anoint with oil'\n \"MECHIE\": \"SEAL\", # WB -mechi 'shut, close'\n \"AKAEBE\": \"TESTIFY\", # ? WB aka ebē 'witness' (written as two words)\n \"EZIOKWU\": \"TRUE\", # WB ezi okwū 'truth' (Standard: eziokwu)\n \"ỤGHA\": \"FALSE\", # WB àma ụghā 'false witness'\n \"EFU\": \"VOID\", # WB efù 'emptiness'\n \"KWỤSỊ\": \"BREAK\", # WB -kwụsị 'stop'\n \"GABA\": \"CONTINUE\", # WB -gaba 'go on; continue to go'\n})\n\n# Two-word phrases: closers, plus the natural Igbo \"Ọ bụrụ\" (if; WB has\n# the Onitsha form \"Ọ bụlụ nà ...\") and \"mgbe ahụ\" (then; Onitsha says\n# \"afù\" for \"that\").\n_IG_COMPOUNDS = _with_plain_spellings({\n (\"NJEDEBE\", \"MA\"): \"ENDIF\",\n (\"NJEDEBE\", \"NWAA\"): \"ENDTRY\",\n (\"Ọ\", \"BỤRỤ\"): \"IF\",\n (\"MGBE\", \"AHỤ\"): \"THEN\",\n})\n\n_IG_SNIPPETS = (\n (\"BIDO OKIKE … NJEDEBE OKIKE\",\n \"BIDO OKIKE\\\\n\\\\t$0\\\\nNJEDEBE OKIKE\",\n \"Open a new scroll\"),\n (\"Ọ BỤRỤ … MGBE AHỤ … NJEDEBE MA\",\n \"Ọ BỤRỤ ${1:condition} MGBE AHỤ\\\\n\\\\t$0\\\\nNJEDEBE MA\",\n \"Weigh a condition\"),\n (\"NWAA … JIDE … NJEDEBE NWAA\",\n \"NWAA\\\\n\\\\t${1:works}\\\\nJIDE\\\\n\\\\t${2:refuge}$0\\\\nNJEDEBE NWAA\",\n \"Shelter a fragile work\"),\n)\n\n# Nigerian Pidgin (pg) word -> canonical English keyword name. Pidgin\n# shares many words with English (IF, TRY, AND, IN, DO, BLESS, LIFE,\n# TRUE, FALSE, RETURN, PROPHESY), so those simply stay as they are.\n# Checked 2026-10-15 against Faraclas, *Nigerian Pidgin* (1996), through\n# the example sentences quoted in APiCS Online (\"F\" below); Naijalingo\n# could not be reached. Faraclas writes Pidgin phonetically (kò̱mót for\n# comot); the spellings here are everyday written Naija. A \"?\" marks a\n# word these sources do not settle; see docs/TONGUES.md.\n_PG_ALIASES = {\n \"OYA\": \"BEGIN\", # ? come on, let's go\n \"KREASHON\": \"CREATION\", # ? a coined spelling of \"creation\"\n \"FINISH\": \"END\", # F finish, a completion marker ('completely')\n \"TALK\": \"DECLARE\", # ? say it\n \"BE\": \"AS\", # F bì 'be' (copula)\n \"BLOW\": \"BREATHE\", # ? blow (breath)\n \"INSIDE\": \"INTO\", # ? inside\n \"SHOW\": \"REVEAL\", # ? show\n \"COMOT\": \"ASCEND\", # F kò̱mót 'leave'\n \"DEN\": \"THEN\", # ? then\n \"HOLD\": \"CATCH\", # ? hold am\n \"ARRANGE\": \"DEFINE\", # ? arrange, set up\n \"JOB\": \"RITE\", # ? a job of work\n \"CALL\": \"INVOKE\", # ? call\n \"CARRY\": \"IMPORT\", # F kari 'carry, take away'; carry come: bring\n \"NA\": \"IS\", # F nà (Ìm nà ticha 's/he is a teacher')\n \"NO\": \"NOT\", # F no (negation)\n \"ABI\": \"OR\", # abi: 'or'; abi?: 'right?' (F records the question use)\n \"REASON\": \"REFLECT\", # ? reason am: think it over\n \"ROB\": \"ANOINT\", # ? rub on\n \"LOCK\": \"SEAL\", # ? lock\n \"WITNESS\": \"TESTIFY\", # ? bear witness\n \"NOTHING\": \"VOID\", # ? nothing\n \"STOP\": \"BREAK\", # ? stop\n \"MOVE\": \"CONTINUE\", # ? move on\n}\n\n_PG_COMPOUNDS = {\n (\"FINISH\", \"IF\"): \"ENDIF\",\n (\"FINISH\", \"TRY\"): \"ENDTRY\",\n}\n\n_PG_SNIPPETS = (\n (\"OYA KREASHON … FINISH KREASHON\",\n \"OYA KREASHON\\\\n\\\\t$0\\\\nFINISH KREASHON\",\n \"Open a new scroll\"),\n (\"IF … DEN … FINISH IF\",\n \"IF ${1:condition} DEN\\\\n\\\\t$0\\\\nFINISH IF\",\n \"Weigh a condition\"),\n (\"TRY … HOLD … FINISH TRY\",\n \"TRY\\\\n\\\\t${1:works}\\\\nHOLD\\\\n\\\\t${2:refuge}$0\\\\nFINISH TRY\",\n \"Shelter a fragile work\"),\n)\n\nTONGUES: dict[str, dict] = {\n \"tn\": {\n \"name\": \"Setswana\",\n \"aliases\": _TN_ALIASES,\n \"compounds\": _TN_COMPOUNDS,\n \"snippets\": _TN_SNIPPETS,\n },\n \"zu\": {\n \"name\": \"isiZulu\",\n \"aliases\": _ZU_ALIASES,\n \"compounds\": _ZU_COMPOUNDS,\n \"snippets\": _ZU_SNIPPETS,\n },\n \"ig\": {\n \"name\": \"Igbo\",\n \"aliases\": _IG_ALIASES,\n \"compounds\": _IG_COMPOUNDS,\n \"snippets\": _IG_SNIPPETS,\n },\n \"pg\": {\n \"name\": \"Nigerian Pidgin\",\n \"aliases\": _PG_ALIASES,\n \"compounds\": _PG_COMPOUNDS,\n \"snippets\": _PG_SNIPPETS,\n },\n}\n\n# Other codes a scroll may use for a tongue: ``pcm`` is the standard\n# (ISO 639-3) code for Nigerian Pidgin.\n_CODE_ALIASES = {\"pcm\": \"pg\"}\n\n_CANONICAL = {\"en\": {\"name\": \"English\", \"aliases\": {}, \"compounds\": {}}}\n\n\ndef known_tongues() -> dict[str, str]:\n \"\"\"Map of tongue code -> language name, canonical English included.\"\"\"\n return {\"en\": \"English\", **{c: t[\"name\"] for c, t in TONGUES.items()}}\n\n\ndef detect_tongue(source: str) -> str | None:\n \"\"\"Return the tongue code from a ``# tongue: xx`` pragma, or None.\"\"\"\n m = _PRAGMA.search(source)\n return m.group(1).lower() if m else None\n\n\ndef resolve(code: str | None) -> dict:\n \"\"\"Return the tongue table for a code; raises a gentle error if unknown.\"\"\"\n if code is None or code == \"en\":\n return _CANONICAL[\"en\"]\n code = _CODE_ALIASES.get(code, code)\n if code in TONGUES:\n return TONGUES[code]\n from .errors import LexerError\n\n names = \", \".join(f\"{c} ({n})\" for c, n in known_tongues().items())\n raise LexerError(\n f\"The tongue '{code}' is not known yet; no scroll can be read in it. \"\n f\"The tongues God Code speaks are: {names}.\",\n )\n\n\ndef parse_source(source: str, tongue: str | None = None):\n \"\"\"Lex (honouring any ``# tongue:`` pragma) and parse God Code source.\n\n This is the one doorway every tool should use instead of calling the\n Lexer and Parser directly, so tongues work the same in ``run``,\n ``check``, ``lint``, ``fmt``, the debugger, the language server, and\n the agent bridge.\n \"\"\"\n from .lexer import Lexer\n from .parser import Parser\n\n lx = Lexer(source, tongue=tongue)\n return Parser(lx.lex(), tongue=lx.tongue).parse()\n","godcode/tools.py":"\"\"\"Agent tool bridge for God Code v4.0 -- \"Intent & Chain\".\n\nMCP-compatible tool schemas plus a stdio JSON-RPC 2.0 bridge, with no\nthird-party dependencies. ``godcode tools`` prints the schemas;\n``godcode bridge`` speaks the protocol so any MCP-compatible agent host\ncan check, run, consult, resolve intent, and verify chains.\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nfrom pathlib import Path\n\nTOOL_SCHEMAS: list[dict] = [\n {\n \"name\": \"check\",\n \"description\": (\n \"Lex and parse a God Code scroll without running it. \"\n \"Returns ok plus diagnostics with line, column, error code, \"\n \"and a fix hint.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"run\",\n \"description\": (\n \"Run a God Code scroll and capture its output. \"\n \"Runs inside the deny-by-default sandbox unless sandbox is false.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n \"sandbox\": {\"type\": \"boolean\",\n \"description\": \"Use the sandbox (default true)\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"consult\",\n \"description\": (\n \"Ask the Spirit Engine -- the local oracle -- a question. \"\n \"Returns two to three sentences of counsel. No external calls.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"question\": {\"type\": \"string\",\n \"description\": \"The question to lay before the Spirit\"},\n },\n \"required\": [\"question\"],\n },\n },\n {\n \"name\": \"intent\",\n \"description\": (\n \"Resolve the spiritual intent behind words with the Spirit \"\n \"Engine: intent, confidence, spiritual intent, suggestion, \"\n \"keywords, and declared intents the words align with.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\"type\": \"string\",\n \"description\": \"Words to resolve the intent of\"},\n },\n \"required\": [\"text\"],\n },\n },\n {\n \"name\": \"anchor_verify\",\n \"description\": (\n \"Verify a blockchain anchor receipt (as returned by ANCHOR) \"\n \"against its anchor chain.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"receipt\": {\"type\": \"object\",\n \"description\": \"The anchor receipt map\"},\n },\n \"required\": [\"receipt\"],\n },\n },\n {\n \"name\": \"ledger_verify\",\n \"description\": (\n \"Verify the covenant chain and the anchor chain for tampering.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Covenant chain file (default covenant.chain)\"},\n \"anchor_file\": {\"type\": \"string\",\n \"description\": \"Anchor chain file (default anchors.chain)\"},\n },\n \"required\": [],\n },\n },\n {\n \"name\": \"permissions\",\n \"description\": (\n \"Read a God Code scroll's permission manifest without running \"\n \"it. Returns the declared powers: file reads, file writes, \"\n \"network hosts, outer-world speech (ASK), and summoned verbs.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"explain\",\n \"description\": (\n \"Read a God Code scroll without running it and say what it \"\n \"does: tongue, rites and their declared intents, declared \"\n \"names, reveals, seals, summoned verbs, consults, imports, \"\n \"and the permission manifest.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"get_schema\",\n \"description\": (\n \"Fetch one of the dated machine-interface JSON Schemas \"\n \"(check, run, explain, ledger-verify) as parsed JSON, so an \"\n \"agent can parse every command's output without guessing.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\",\n \"description\": \"Schema name: check, run, explain, \"\n \"or ledger-verify\"},\n },\n \"required\": [\"name\"],\n },\n },\n {\n \"name\": \"format\",\n \"description\": (\n \"Re-emit a God Code scroll in canonical form without running \"\n \"it: upper-case keywords, tidy spacing, the shape `godcode \"\n \"fmt` prints. Returns the formatted scroll as text.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\"type\": \"string\",\n \"description\": \"Path to the .god scroll\"},\n },\n \"required\": [\"file\"],\n },\n },\n {\n \"name\": \"list_scrolls\",\n \"description\": (\n \"List the scrolls installed in the local scroll registry, \"\n \"with their versions and locations. Takes no arguments.\"\n ),\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"required\": [],\n },\n },\n]\n\n_TOOLS_BY_NAME = {t[\"name\"]: t for t in TOOL_SCHEMAS}\n\n\n# ---------------------------------------------------------------------------\n# tool implementations (each returns a plain-JSON result dict)\n# ---------------------------------------------------------------------------\ndef tool_check(arguments: dict) -> dict:\n from godcode import agentics\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False, \"error\": \"check needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False, \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n parse_source(source)\n except GodCodeError as err:\n return {\"ok\": False, \"diagnostics\": [agentics.diagnostic(err)]}\n return {\"ok\": True, \"diagnostics\": []}\n\n\ndef tool_run(arguments: dict) -> dict:\n from godcode.errors import GodCodeError\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False, \"error\": \"run needs 'file' as a string path\"}\n sandbox = arguments.get(\"sandbox\", True)\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False, \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n if sandbox:\n # The engine prints notices (intent counsel, warnings) straight\n # to stdout; a tool caller reads stdout as the protocol stream,\n # so those prints would corrupt it. The CLI's --json path does\n # the same: run muted, report only the collected output.\n import contextlib\n import io\n\n from godcode.sandbox import run_sandboxed_with_interpreter\n\n try:\n with contextlib.redirect_stdout(io.StringIO()):\n output, interp = run_sandboxed_with_interpreter(\n source, source_name=file)\n except GodCodeError as err:\n return {\"ok\": False, \"output\": [], \"error\": str(err)}\n manifest = getattr(interp, \"manifest\", None)\n return {\"ok\": True, \"output\": output, \"error\": None,\n \"permissions\": manifest.to_json() if manifest else {}}\n from godcode.cli import _make_interpreter\n import contextlib\n import io\n\n interp = _make_interpreter(None)\n buf = io.StringIO()\n try:\n with contextlib.redirect_stdout(buf):\n interp.run_source(source, source_name=file)\n except GodCodeError as err:\n return {\"ok\": False,\n \"output\": buf.getvalue().splitlines(),\n \"error\": str(err)}\n manifest = getattr(interp, \"manifest\", None)\n return {\"ok\": True, \"output\": buf.getvalue().splitlines(), \"error\": None,\n \"permissions\": manifest.to_json() if manifest else {}}\n\n\ndef tool_consult(arguments: dict) -> dict:\n from godcode.spirit import SpiritEngine\n\n question = arguments.get(\"question\")\n if not isinstance(question, str):\n return {\"ok\": False, \"error\": \"consult needs 'question' as a string\"}\n try:\n counsel = SpiritEngine().counsel(question)\n except Exception as exc: # pragma: no cover - defensive\n return {\"ok\": False, \"error\": f\"the oracle faltered: {exc}\"}\n return {\"ok\": True, \"counsel\": counsel}\n\n\ndef tool_intent(arguments: dict) -> dict:\n from godcode.spirit import SpiritEngine\n\n text = arguments.get(\"text\")\n if not isinstance(text, str):\n return {\"ok\": False, \"error\": \"intent needs 'text' as a string\"}\n try:\n result = SpiritEngine().resolve_intent(text)\n except Exception as exc: # pragma: no cover - defensive\n return {\"ok\": False, \"error\": f\"the Spirit faltered: {exc}\"}\n return {\"ok\": True, \"result\": result}\n\n\ndef tool_anchor_verify(arguments: dict) -> dict:\n from godcode.chain import default_adapters\n\n receipt = arguments.get(\"receipt\")\n if not isinstance(receipt, dict):\n return {\"ok\": False, \"error\": \"anchor_verify needs 'receipt' as an object\"}\n chain_name = receipt.get(\"chain\", \"simulated\")\n adapter = default_adapters().get(chain_name)\n if adapter is None:\n return {\"ok\": False,\n \"error\": f\"unknown chain '{chain_name}'\"}\n valid = adapter.verify(receipt)\n return {\n \"ok\": True,\n \"valid\": valid,\n \"message\": (\"the anchor stands\" if valid\n else \"the anchor does not verify\"),\n }\n\n\ndef tool_permissions(arguments: dict) -> dict:\n \"\"\"Read a scroll's permission manifest without running it.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.permissions import collect_manifest\n from godcode.tongues import parse_source\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False,\n \"error\": \"permissions needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False,\n \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n program = parse_source(source)\n except GodCodeError as err:\n return {\"ok\": False, \"error\": str(err)}\n manifest = collect_manifest(\n program.statements, Path(file).resolve().parent)\n return {\"ok\": True, \"permissions\": manifest.to_json()}\n\n\ndef tool_explain(arguments: dict) -> dict:\n \"\"\"Describe a scroll's static facts without running it.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.explain import explain_facts\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False,\n \"error\": \"explain needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False,\n \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n facts = explain_facts(source, Path(file).resolve().parent)\n except GodCodeError as err:\n return {\"ok\": False, \"error\": str(err)}\n return {\"ok\": True, **facts}\n\n\ndef tool_get_schema(arguments: dict) -> dict:\n \"\"\"Fetch one dated machine-interface schema as parsed JSON.\"\"\"\n name = arguments.get(\"name\")\n if not isinstance(name, str):\n return {\"ok\": False,\n \"error\": \"get_schema needs 'name' as a string\"}\n text, error = read_schema(name)\n if error is not None:\n return {\"ok\": False, \"error\": error}\n return {\"ok\": True, \"schema\": json.loads(text)}\n\n\ndef tool_format(arguments: dict) -> dict:\n \"\"\"Re-emit a scroll in canonical form without running it.\"\"\"\n from godcode.errors import GodCodeError\n from godcode.tongues import parse_source\n\n file = arguments.get(\"file\")\n if not isinstance(file, str):\n return {\"ok\": False, \"error\": \"format needs 'file' as a string path\"}\n try:\n source = Path(file).read_text(encoding=\"utf-8\")\n except OSError as exc:\n return {\"ok\": False, \"error\": f\"cannot read '{file}': {exc.strerror or exc}\"}\n try:\n program = parse_source(source)\n except GodCodeError as err:\n return {\"ok\": False, \"error\": str(err)}\n from godcode.cli import CanonicalFormatter\n\n return {\"ok\": True, \"formatted\": CanonicalFormatter().format(program)}\n\n\ndef tool_list_scrolls(arguments: dict) -> dict:\n \"\"\"List the scrolls installed in the local scroll registry.\"\"\"\n from godcode.registry import ScrollError, ScrollRegistry\n\n try:\n rows = ScrollRegistry().list_installed()\n except ScrollError as exc:\n return {\"ok\": False, \"error\": str(exc)}\n return {\"ok\": True, \"scrolls\": rows}\n\n\ndef tool_ledger_verify(arguments: dict) -> dict:\n from godcode.chain import SimulatedChainAdapter\n from godcode.ledger import CovenantLedger\n\n file = arguments.get(\"file\", \"covenant.chain\")\n anchor_file = arguments.get(\"anchor_file\", \"anchors.chain\")\n cov_ok, cov_msg = CovenantLedger(file).verify()\n anc_ok, anc_msg = SimulatedChainAdapter(anchor_file).verify_chain()\n return {\n \"ok\": True,\n \"covenants\": {\"ok\": cov_ok, \"message\": cov_msg},\n \"anchors\": {\"ok\": anc_ok, \"message\": anc_msg},\n }\n\n\n_TOOL_FUNCS = {\n \"check\": tool_check,\n \"run\": tool_run,\n \"consult\": tool_consult,\n \"intent\": tool_intent,\n \"anchor_verify\": tool_anchor_verify,\n \"ledger_verify\": tool_ledger_verify,\n \"permissions\": tool_permissions,\n \"explain\": tool_explain,\n \"get_schema\": tool_get_schema,\n \"format\": tool_format,\n \"list_scrolls\": tool_list_scrolls,\n}\n\n\n# ---------------------------------------------------------------------------\n# dated machine-interface schemas\n# ---------------------------------------------------------------------------\nSCHEMA_NAMES = (\"check\", \"run\", \"explain\", \"ledger-verify\")\n\nSCHEMA_DESCRIPTIONS = {\n \"check\": \"the shape of godcode check --json\",\n \"run\": \"the shape of godcode run --sandbox --json\",\n \"explain\": \"the shape of godcode explain --json\",\n \"ledger-verify\": \"the shape of godcode ledger verify --json\",\n}\n\n\ndef read_schema(name):\n \"\"\"Return (text, error) for a dated schema.\n\n Resolves through importlib.resources so an installed package serves\n its shipped schemas; falls back to the repository's schemas/\n directory when running from source.\n \"\"\"\n if name not in SCHEMA_NAMES:\n return None, f\"no schema named '{name}'\"\n rel = Path(\"schemas\") / \"2026-10\" / f\"{name}.json\"\n try:\n from importlib.resources import files\n\n candidate = files(\"godcode\").joinpath(\"schemas/2026-10\",\n f\"{name}.json\")\n if candidate.is_file():\n return candidate.read_text(encoding=\"utf-8\"), None\n except Exception:\n pass\n fallback = Path(__file__).resolve().parent / rel\n if fallback.is_file():\n return fallback.read_text(encoding=\"utf-8\"), None\n return None, f\"schema '{name}' is not installed here\"\n\n\ndef call_tool(name: str, arguments: dict) -> dict:\n \"\"\"Run one tool by name; always returns a JSON-safe result dict.\"\"\"\n func = _TOOL_FUNCS.get(name)\n if func is None:\n return {\"ok\": False,\n \"error\": f\"unknown tool '{name}'\",\n \"known_tools\": sorted(_TOOL_FUNCS)}\n if not isinstance(arguments, dict):\n return {\"ok\": False, \"error\": \"arguments must be an object\"}\n try:\n return func(arguments)\n except Exception as exc: # pragma: no cover - defensive\n return {\"ok\": False, \"error\": f\"the tool faltered: {exc!r}\"}\n\n\n# ---------------------------------------------------------------------------\n# `godcode tools`\n# ---------------------------------------------------------------------------\ndef cmd_tools(args) -> int:\n \"\"\"Print the MCP-compatible tool schemas (--json for machines).\"\"\"\n if getattr(args, \"json\", False):\n print(json.dumps({\"tools\": TOOL_SCHEMAS}, ensure_ascii=False, indent=2))\n return 0\n print(\"God Code tools (MCP-compatible):\")\n for tool in TOOL_SCHEMAS:\n required = \", \".join(tool[\"inputSchema\"].get(\"required\", [])) or \"none\"\n print(f\" {tool['name']}({required}): {tool['description']}\")\n print(\"Speak them through `godcode mcp`, the MCP server over stdio,\")\n print(\"or through `godcode bridge`, the plain stdio JSON-RPC loop.\")\n return 0\n\n\n# ---------------------------------------------------------------------------\n# `godcode bridge` -- stdio JSON-RPC 2.0\n# ---------------------------------------------------------------------------\n_PARSE_ERROR = -32700\n_INVALID_REQUEST = -32600\n_METHOD_NOT_FOUND = -32601\n_INVALID_PARAMS = -32602\n_INTERNAL_ERROR = -32603\n\n\ndef _response_ok(req_id, result: dict) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id, \"result\": result}\n\n\ndef _response_err(req_id, code: int, message: str) -> dict:\n return {\"jsonrpc\": \"2.0\", \"id\": req_id,\n \"error\": {\"code\": code, \"message\": message}}\n\n\ndef _handle_initialize(params: dict) -> dict:\n from godcode import __version__\n\n return {\n \"protocolVersion\": \"2024-11-05\",\n \"capabilities\": {\"tools\": {}},\n \"serverInfo\": {\"name\": \"godcode-bridge\", \"version\": __version__},\n }\n\n\ndef _handle_tools_call(params: dict) -> dict:\n name = params.get(\"name\")\n arguments = params.get(\"arguments\", {})\n if not isinstance(name, str):\n raise _BridgeError(_INVALID_PARAMS, \"tools/call needs 'name' as a string\")\n result = call_tool(name, arguments if isinstance(arguments, dict) else {})\n content = [{\"type\": \"text\",\n \"text\": json.dumps(result, ensure_ascii=False)}]\n payload = {\"content\": content}\n if not result.get(\"ok\", True):\n payload[\"isError\"] = True\n return payload\n\n\nclass _BridgeError(Exception):\n def __init__(self, code: int, message: str) -> None:\n super().__init__(message)\n self.code = code\n self.message = message\n\n\ndef _dispatch(method: str, params: dict):\n if method == \"initialize\":\n return _handle_initialize(params)\n if method == \"ping\":\n return {}\n if method == \"tools/list\":\n return {\"tools\": TOOL_SCHEMAS}\n if method == \"tools/call\":\n return _handle_tools_call(params)\n raise _BridgeError(_METHOD_NOT_FOUND, f\"no such method '{method}'\")\n\n\ndef cmd_bridge(args) -> int: # noqa: ARG001\n \"\"\"Serve the tool bridge: JSON-RPC 2.0 over stdio, one request per line.\"\"\"\n import sys\n\n stdin, stdout = sys.stdin, sys.stdout\n for line in stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n stdout.write(json.dumps(_response_err(None, _PARSE_ERROR,\n \"the request was not JSON\"))\n + \"\\n\")\n stdout.flush()\n continue\n req_id = request.get(\"id\") if isinstance(request, dict) else None\n # Notifications carry no id and get no answer.\n is_notification = isinstance(request, dict) and \"id\" not in request\n try:\n if not isinstance(request, dict) or \"method\" not in request:\n raise _BridgeError(_INVALID_REQUEST,\n \"a request needs a 'method'\")\n params = request.get(\"params\", {})\n if not isinstance(params, dict):\n raise _BridgeError(_INVALID_PARAMS,\n \"'params' must be an object\")\n result = _dispatch(request[\"method\"], params)\n except _BridgeError as err:\n response = _response_err(req_id, err.code, err.message)\n except Exception as exc: # pragma: no cover - defensive\n response = _response_err(req_id, _INTERNAL_ERROR,\n f\"the bridge faltered: {exc!r}\")\n else:\n if is_notification:\n continue\n response = _response_ok(req_id, result)\n if is_notification:\n continue\n stdout.write(json.dumps(response, ensure_ascii=False) + \"\\n\")\n stdout.flush()\n return 0\n","godcode/values.py":"\"\"\"Divine value types for God Code.\n\nIn God Code, every unnamed thing is still a named spirit: a bare word with\nno binding evaluates to a Symbol rather than raising an error.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass, field\nfrom typing import Any\n\n\nclass Symbol(str):\n \"\"\"A bare word with no binding — a named spirit.\n\n A str subclass, so Symbol(\"worthy\") compares equal to \"worthy\" by text\n and behaves like a string everywhere, while remaining distinguishable\n via isinstance checks (e.g. FOR loops refuse to iterate a mere Symbol).\n Symbols are always truthy.\n \"\"\"\n\n def __new__(cls, name: str) -> \"Symbol\":\n return super().__new__(cls, name)\n\n def __repr__(self) -> str: # pragma: no cover - cosmetic\n return f\"Symbol({str(self)!r})\"\n\n\n@dataclass\nclass Contract:\n \"\"\"A covenant created by the `contract(name)` rite.\n\n Contracts can be breathed into (alive), blessed, and anointed; SEAL\n records their state in the covenant ledger.\n \"\"\"\n\n name: str\n alive: bool = False\n blessed: bool = False\n anointed: bool = False\n\n def __str__(self) -> str:\n return f'contract(\"{self.name}\")'\n\n\n@dataclass\nclass RiteFunction:\n \"\"\"A user-defined rite: name, parameter names, body, and closure env.\"\"\"\n\n name: str\n params: list[str] = field(default_factory=list)\n body: list[Any] = field(default_factory=list)\n closure_env: Any = None # godcode.environment.Environment (Any avoids a cycle)\n\n def __str__(self) -> str: # pragma: no cover - cosmetic\n return f\"rite {self.name}\"\n","godcode/webrun.py":"\"\"\"The web door: run and check God Code for the browser playground.\n\nThe playground loads this very engine into the browser (through Pyodide,\nPython compiled to WebAssembly) and calls the two functions below. Each\nreturns one JSON-ready dict, shaped like the ``run --json`` and\n``check --json`` payloads of :mod:`godcode.agentics`, so the page and an\nagent read the same answers.\n\nEvery run is sandboxed under the strict policy: no files, no network, no\nsubprocesses, no stdin, a wall-clock grant and a step budget. Scroll\nimports are blessed from the bundled stdlib and from ``library_dir``,\nwhere the playground lays the registry scrolls, so ``IMPORT \"blessings\"``\nworks in the browser as it does after ``godcode scroll install``.\n\nNothing here is browser-only. It is plain Python, kept honest by\n``tests/test_webrun.py``, and any host may call it.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nimport os\nimport time\nfrom pathlib import Path\n\nfrom godcode import __version__\nfrom godcode.agentics import TOOL_NAME, diagnostic, error_trace\n\n#: The name the creation carries in the playground's error messages.\nCREATION_NAME = \"creation.god\"\n\n\ndef _finding(f) -> dict:\n return {\n \"line\": f.line,\n \"col\": f.col,\n \"code\": f.rule,\n \"severity\": \"warning\",\n \"message\": f.message,\n \"hint\": None,\n }\n\n\ndef check_creation(source: str) -> dict:\n \"\"\"Parse and lint ``source``; return a ``check`` payload.\n\n A parse error is one ``error`` diagnostic and the creation is impure.\n A clean parse adds the linter's gentle counsel as ``warning``\n diagnostics; counsel never makes the creation impure.\n \"\"\"\n from godcode.errors import GodCodeError\n from godcode.linter import lint_source\n\n diagnostics: list[dict] = []\n ok = True\n try:\n findings = lint_source(source, source_name=CREATION_NAME)\n except GodCodeError as err:\n diagnostics.append(diagnostic(err))\n ok = False\n else:\n diagnostics.extend(_finding(f) for f in findings)\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"check\",\n \"file\": CREATION_NAME,\n \"version\": __version__,\n \"ok\": ok,\n \"diagnostics\": diagnostics,\n }\n\n\ndef run_creation(\n source: str,\n *,\n library_dir: str | os.PathLike | None = None,\n timeout_seconds: float = 5.0,\n max_steps: int | None = None,\n) -> dict:\n \"\"\"Run ``source`` under the strict sandbox; return a ``run`` payload.\n\n ``output`` holds every line the creation spoke, REVEAL lines and\n engine notices (``🕊 Creation ascended in peace.``) alike. On failure\n it holds the lines spoken before the error, and ``error`` carries the\n diagnostic plus the rite ``trace``. A failure outside the divine\n errors is reported, never raised, so the page always has an answer.\n \"\"\"\n from godcode.errors import GodCodeError\n from godcode.sandbox import SandboxPolicy, run_sandboxed_with_interpreter\n\n source_name = \"\"\n if library_dir is not None:\n # The creation rests beside the library so bare-name imports\n # resolve there, and the strict policy blesses that directory.\n library = Path(library_dir)\n library.mkdir(parents=True, exist_ok=True)\n creation = library / CREATION_NAME\n creation.write_text(source, encoding=\"utf-8\")\n source_name = str(creation)\n policy = SandboxPolicy.strict(\n source_dir=str(library_dir) if library_dir is not None else None,\n timeout_seconds=timeout_seconds,\n )\n if max_steps is not None:\n policy.max_steps = max_steps\n\n buf = io.StringIO()\n error: dict | None = None\n intents: list[dict] = []\n start = time.perf_counter()\n with contextlib.redirect_stdout(buf):\n try:\n _, interp = run_sandboxed_with_interpreter(\n source, policy, source_name=source_name)\n intents = list(getattr(interp, \"intent_checks\", []) or [])\n except GodCodeError as err:\n error = diagnostic(err)\n error[\"trace\"] = error_trace(err)\n except Exception as exc: # a host failure outside the divine errors\n error = {\n \"line\": None,\n \"col\": None,\n \"code\": \"HOST_ERROR\",\n \"severity\": \"error\",\n \"message\": f\"the outer world faltered: {exc!r}\",\n \"hint\": None,\n \"trace\": [],\n }\n ms = int((time.perf_counter() - start) * 1000)\n return {\n \"tool\": TOOL_NAME,\n \"command\": \"run\",\n \"file\": CREATION_NAME,\n \"version\": __version__,\n \"ok\": error is None,\n \"output\": buf.getvalue().splitlines(),\n \"intents\": intents,\n \"error\": error,\n \"stats\": {\"ms\": ms},\n }\n\n\n__all__ = [\"CREATION_NAME\", \"check_creation\", \"run_creation\"]\n"},"library":{"blessings.god":"# The Scroll of Blessings -- words of favor for the children of creation.\n# A community content pack: the BLESSINGS list and rites to reveal them.\n# Rites: REVEAL_BLESSING, BLESSING_COUNT, BLESS_AT.\n\nDECLARE BLESSINGS AS [\"May your code compile on the first breath.\", \"May your loops find rest and your rites return in peace.\", \"May no scroll be lost, and no promise broken.\", \"May your errors be loud, your fixes swift, and your tests ever green.\", \"Blessed are the debuggers, for they shall find the light.\", \"May your merges be clean and your conflicts few.\", \"May the Spirit guide your keystrokes and guard your deploys.\", \"May your data be backed up and your restores untested-never.\", \"May every edge case be foreseen, and every null be void indeed.\", \"Go in peace; your creation is good.\"]\n\nDEFINE RITE REVEAL_BLESSING()\nDECLARE i AS RANDOM(LEN(BLESSINGS))\nRETURN BLESSINGS[i]\nEND RITE\n\nDEFINE RITE BLESSING_COUNT()\nRETURN LEN(BLESSINGS)\nEND RITE\n\nDEFINE RITE BLESS_AT(n)\nRETURN BLESSINGS[n]\nEND RITE\n","covenant.god":"# The Scroll of the Covenant -- making and sealing binding promises.\n# Rites: NEW_COVENANT, SEAL_COVENANT.\n\nDEFINE RITE NEW_COVENANT(name)\nRETURN contract(name)\nEND RITE\n\nDEFINE RITE SEAL_COVENANT(c)\nSEAL c\nEND RITE\n","hashes.god":"# The Scroll of Hashes -- fingerprints of words, sealed signatures, and veils.\n# Rites: FINGERPRINT, SIGN, VERIFY_SIGNATURE, VEIL, UNVEIL.\n\nDEFINE RITE FINGERPRINT(word)\n RETURN SHA256(word)\nEND RITE\n\nDEFINE RITE SIGN(message, key)\n RETURN HMAC(key, message)\nEND RITE\n\nDEFINE RITE VERIFY_SIGNATURE(message, key, sig)\n RETURN SIGN(message, key) IS sig\nEND RITE\n\nDEFINE RITE VEIL(word)\n RETURN BASE64_ENCODE(word)\nEND RITE\n\nDEFINE RITE UNVEIL(veiled)\n RETURN BASE64_DECODE(veiled)\nEND RITE\n","json-tools.god":"# The Scroll of JSON -- encoding and decoding the tongue of machines.\n# Written in pure God Code (stdlib builtins only); a community scroll.\n# Rites: JSON_ENCODE, JSON_DECODE, JSON_ESCAPE.\n# Objects decode into lists of [key, value] pairs, for the tongue of\n# God Code knows no dictionaries.\n\nDEFINE RITE JSON_ESCAPE(s)\nDECLARE out AS \"\"\nDECLARE i AS 0\nWHILE i < LEN(s) DO\nDECLARE c AS s[i]\nIF c == \"\\\"\" THEN\nDECLARE out AS out + \"\\\\\\\"\"\nELSE\nIF c == \"\\\\\" THEN\nDECLARE out AS out + \"\\\\\\\\\"\nELSE\nIF c == \"\\n\" THEN\nDECLARE out AS out + \"\\\\n\"\nELSE\nIF c == \"\\t\" THEN\nDECLARE out AS out + \"\\\\t\"\nELSE\nDECLARE out AS out + c\nENDIF\nENDIF\nENDIF\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN out\nEND RITE\n\nDEFINE RITE JSON_ENCODE(value)\nDECLARE t AS TYPE(value)\nIF t == \"string\" THEN\nRETURN \"\\\"\" + JSON_ESCAPE(value) + \"\\\"\"\nENDIF\nIF t == \"list\" THEN\nDECLARE parts AS []\nDECLARE i AS 0\nWHILE i < LEN(value) DO\nDECLARE parts AS PUSH(parts, JSON_ENCODE(value[i]))\nDECLARE i AS i + 1\nENDWHILE\nRETURN \"[\" + JOIN(parts, \",\") + \"]\"\nENDIF\nIF t == \"boolean\" THEN\nIF value THEN\nRETURN \"true\"\nENDIF\nRETURN \"false\"\nENDIF\nIF t == \"void\" THEN\nRETURN \"null\"\nENDIF\nRETURN STR(value)\nEND RITE\n\nDEFINE RITE JSON_SKIP(text, pos)\nDECLARE n AS LEN(text)\nWHILE pos < n DO\nDECLARE c AS text[pos]\nIF c == \" \" THEN\nDECLARE pos AS pos + 1\nELSE\nIF c == \"\\n\" THEN\nDECLARE pos AS pos + 1\nELSE\nIF c == \"\\t\" THEN\nDECLARE pos AS pos + 1\nELSE\nRETURN pos\nENDIF\nENDIF\nENDIF\nENDWHILE\nRETURN pos\nEND RITE\n\nDEFINE RITE JSON_IS_DIGIT(c)\nIF c == \"0\" OR c == \"1\" OR c == \"2\" OR c == \"3\" OR c == \"4\" OR c == \"5\" OR c == \"6\" OR c == \"7\" OR c == \"8\" OR c == \"9\" THEN\nRETURN true\nENDIF\nRETURN false\nEND RITE\n\nDEFINE RITE JSON_PARSE_STRING(text, pos)\nDECLARE out AS \"\"\nDECLARE i AS pos + 1\nDECLARE n AS LEN(text)\nWHILE i < n DO\nDECLARE c AS text[i]\nIF c == \"\\\"\" THEN\nRETURN [out, i + 1]\nENDIF\nIF c == \"\\\\\" THEN\nDECLARE e AS text[i + 1]\nIF e == \"\\\"\" THEN\nDECLARE out AS out + \"\\\"\"\nELSE\nIF e == \"\\\\\" THEN\nDECLARE out AS out + \"\\\\\"\nELSE\nIF e == \"n\" THEN\nDECLARE out AS out + \"\\n\"\nELSE\nIF e == \"t\" THEN\nDECLARE out AS out + \"\\t\"\nELSE\nDECLARE out AS out + e\nENDIF\nENDIF\nENDIF\nENDIF\nDECLARE i AS i + 2\nELSE\nDECLARE out AS out + c\nDECLARE i AS i + 1\nENDIF\nENDWHILE\nRETURN [out, i]\nEND RITE\n\nDEFINE RITE JSON_SLICE(text, start, stop)\nDECLARE out AS \"\"\nDECLARE i AS start\nWHILE i < stop DO\nDECLARE out AS out + text[i]\nDECLARE i AS i + 1\nENDWHILE\nRETURN out\nEND RITE\n\nDEFINE RITE JSON_PARSE_NUMBER(text, pos)\nDECLARE i AS pos\nDECLARE n AS LEN(text)\nWHILE i < n DO\nDECLARE c AS text[i]\nIF JSON_IS_DIGIT(c) THEN\nDECLARE i AS i + 1\nELSE\nIF c == \".\" OR c == \"-\" OR c == \"+\" OR c == \"e\" OR c == \"E\" THEN\nDECLARE i AS i + 1\nELSE\nRETURN [NUM(JSON_SLICE(text, pos, i)), i]\nENDIF\nENDIF\nENDWHILE\nRETURN [NUM(JSON_SLICE(text, pos, i)), i]\nEND RITE\n\nDEFINE RITE JSON_EXPECT(text, pos, word)\nDECLARE i AS 0\nWHILE i < LEN(word) DO\nIF text[pos + i] == word[i] THEN\nDECLARE i AS i + 1\nELSE\nRETURN -1\nENDIF\nENDWHILE\nRETURN pos + LEN(word)\nEND RITE\n\nDEFINE RITE JSON_PARSE_VALUE(text, pos)\nDECLARE i AS JSON_SKIP(text, pos)\nDECLARE c AS text[i]\nIF c == \"\\\"\" THEN\nRETURN JSON_PARSE_STRING(text, i)\nENDIF\nIF c == \"[\" THEN\nRETURN JSON_PARSE_ARRAY(text, i)\nENDIF\nIF c == \"{{\" THEN\nRETURN JSON_PARSE_OBJECT(text, i)\nENDIF\nIF c == \"t\" THEN\nRETURN [true, JSON_EXPECT(text, i, \"true\")]\nENDIF\nIF c == \"f\" THEN\nRETURN [false, JSON_EXPECT(text, i, \"false\")]\nENDIF\nIF c == \"n\" THEN\nRETURN [void, JSON_EXPECT(text, i, \"null\")]\nENDIF\nRETURN JSON_PARSE_NUMBER(text, i)\nEND RITE\n\nDEFINE RITE JSON_PARSE_ARRAY(text, pos)\nDECLARE items AS []\nDECLARE i AS JSON_SKIP(text, pos + 1)\nIF text[i] == \"]\" THEN\nRETURN [items, i + 1]\nENDIF\nWHILE true DO\nDECLARE valres AS JSON_PARSE_VALUE(text, i)\nDECLARE items AS PUSH(items, valres[0])\nDECLARE i AS JSON_SKIP(text, valres[1])\nIF text[i] == \",\" THEN\nDECLARE i AS i + 1\nELSE\nRETURN [items, i + 1]\nENDIF\nENDWHILE\nEND RITE\n\nDEFINE RITE JSON_PARSE_OBJECT(text, pos)\nDECLARE pairs AS []\nDECLARE i AS JSON_SKIP(text, pos + 1)\nIF text[i] == \"}\" THEN\nRETURN [pairs, i + 1]\nENDIF\nWHILE true DO\nDECLARE i AS JSON_SKIP(text, i)\nDECLARE keyres AS JSON_PARSE_STRING(text, i)\nDECLARE key AS keyres[0]\nDECLARE i AS JSON_SKIP(text, keyres[1] + 1)\nDECLARE valres AS JSON_PARSE_VALUE(text, i)\nDECLARE pairs AS PUSH(pairs, [key, valres[0]])\nDECLARE i AS JSON_SKIP(text, valres[1])\nIF text[i] == \",\" THEN\nDECLARE i AS i + 1\nELSE\nRETURN [pairs, i + 1]\nENDIF\nENDWHILE\nEND RITE\n\nDEFINE RITE JSON_DECODE(text)\nDECLARE res AS JSON_PARSE_VALUE(text, 0)\nRETURN res[0]\nEND RITE\n","lists.god":"# The Scroll of Multitudes -- reckonings over gathered lists.\n# Rites: SUM, AVG, CONTAINS, SECOND, TAIL, COUNT.\n\nDEFINE RITE SUM(xs)\nDECLARE total AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nDECLARE total AS total + xs[i]\nDECLARE i AS i + 1\nENDWHILE\nRETURN total\nEND RITE\n\nDEFINE RITE AVG(xs)\nRETURN SUM(xs) / LEN(xs)\nEND RITE\n\nDEFINE RITE CONTAINS(xs, x)\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nRETURN 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN 0\nEND RITE\n\nDEFINE RITE SECOND(xs)\nRETURN xs[1]\nEND RITE\n\nDEFINE RITE TAIL(xs)\nDECLARE tail AS []\nDECLARE i AS 1\nWHILE i < LEN(xs) DO\nDECLARE tail AS PUSH(tail, xs[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN tail\nEND RITE\n\nDEFINE RITE COUNT(xs, x)\nDECLARE n AS 0\nDECLARE i AS 0\nWHILE i < LEN(xs) DO\nIF xs[i] IS x THEN\nDECLARE n AS n + 1\nENDIF\nDECLARE i AS i + 1\nENDWHILE\nRETURN n\nEND RITE\n","math.god":"# The Scroll of Numbers -- divine arithmetic for the children of creation.\n# Rites: SQRT, POW, ABS, MIN, MAX, FACTORIAL, IS_EVEN.\n\nDEFINE RITE SQRT(x)\nIF x IS 0 THEN\nRETURN 0\nENDIF\nIF x < 0 THEN\nRETURN 0\nENDIF\nDECLARE guess AS x\nWHILE ABS(guess * guess - x) > 0.000000001 DO\nDECLARE guess AS guess - (guess * guess - x) / (2 * guess)\nENDWHILE\nRETURN guess\nEND RITE\n\nDEFINE RITE POW(b, e)\nDECLARE result AS 1\nDECLARE i AS 0\nWHILE i < e DO\nDECLARE result AS result * b\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE ABS(x)\nIF x < 0 THEN\nRETURN 0 - x\nENDIF\nRETURN x\nEND RITE\n\nDEFINE RITE MIN(a, b)\nIF a < b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE MAX(a, b)\nIF a > b THEN\nRETURN a\nENDIF\nRETURN b\nEND RITE\n\nDEFINE RITE FACTORIAL(n)\nDECLARE result AS 1\nDECLARE i AS 1\nWHILE i <= n DO\nDECLARE result AS result * i\nDECLARE i AS i + 1\nENDWHILE\nRETURN result\nEND RITE\n\nDEFINE RITE IS_EVEN(n)\nIF n % 2 IS 0 THEN\nRETURN 1\nENDIF\nRETURN 0\nEND RITE\n","my-blessing.god":"# my-blessing, a newborn scroll.\n# Run it with: godcode run main.god\n# Test it with: godcode test .\n\nBEGIN CREATION\n\n DECLARE INTENT \"speak a blessing of peace over the household\" ON evening_blessing\n\n DEFINE RITE evening_blessing()\n REVEAL(\"Peace be upon this house.\")\n REVEAL(\"May the morning bring grace and the evening bring rest.\")\n END RITE\n\n DECLARE day AS \"a new day\"\n evening_blessing()\n REVEAL(\"Walk into {day} with courage.\")\n\nEND CREATION\n","prophecy.god":"# The Scroll of Lots -- discerning choice by sacred chance.\n# Rites: PROPHESY_NUMBER, CAST_LOTS, CHOOSE.\n\nDEFINE RITE PROPHESY_NUMBER(n)\nRETURN RANDOM(n)\nEND RITE\n\nDEFINE RITE CAST_LOTS()\nRETURN RANDOM(2)\nEND RITE\n\nDEFINE RITE CHOOSE(xs)\nRETURN xs[RANDOM(LEN(xs))]\nEND RITE\n","strings.god":"# The Scroll of Tongues -- words shaped, lifted up, and proclaimed.\n# Rites: SHOUT, WHISPER, WORDS, CHARS, FIRST, LAST.\n\nDEFINE RITE SHOUT(s)\nRETURN UPPER(s) + \"!\"\nEND RITE\n\nDEFINE RITE WHISPER(s)\nRETURN LOWER(s)\nEND RITE\n\nDEFINE RITE WORDS(s)\nRETURN SPLIT(s, \" \")\nEND RITE\n\nDEFINE RITE CHARS(s)\nDECLARE chars AS []\nDECLARE i AS 0\nWHILE i < LEN(s) DO\nDECLARE chars AS PUSH(chars, s[i])\nDECLARE i AS i + 1\nENDWHILE\nRETURN chars\nEND RITE\n\nDEFINE RITE FIRST(s)\nRETURN s[0]\nEND RITE\n\nDEFINE RITE LAST(s)\nRETURN s[LEN(s) - 1]\nEND RITE\n","time.god":"# The Scroll of Appointed Times -- beholding the hour and the day.\n# Rites: NOW, TODAY.\n\nDEFINE RITE NOW()\nRETURN BEHOLD()\nEND RITE\n\nDEFINE RITE TODAY()\nRETURN SPLIT(BEHOLD(), \"T\")[0]\nEND RITE\n"},"samples":[{"code":"# The commons at work: everyday tools for words, lists, maps, and numbers.\n# Twenty-six small builtins, always present, no import needed.\n\nBEGIN CREATION\n # Words: trim the edges, renew a name, ask what it holds\n DECLARE raw AS \" manna, manna, honey \"\n REVEAL(TRIM(raw)) # \"manna, manna, honey\"\n REVEAL(REPLACE(TRIM(raw), \"manna\", \"bread\")) # \"bread, bread, honey\"\n REVEAL(REPEAT(\"Pula! \", 3)) # \"Pula! Pula! Pula! \"\n REVEAL(STARTS_WITH(\"dawn breaks\", \"dawn\")) # true\n REVEAL(ENDS_WITH(\"dawn breaks\", \"breaks\")) # true\n REVEAL(SUBSTRING(\"blessing\", 2, 6)) # \"essi\"\n REVEAL(COUNT(\"banana bread\", \"an\")) # 2\n\n # Lists: order them, weigh them, find their members\n DECLARE harvest AS [12, 7, 19, 7, 12, 4]\n REVEAL(SORT(harvest)) # [4, 7, 7, 12, 12, 19]\n REVEAL(harvest) # untouched: [12, 7, 19, 7, 12, 4]\n REVEAL(SUM_OF(harvest)) # 61\n REVEAL(MIN_OF(harvest)) # 4\n REVEAL(MAX_OF(harvest)) # 19\n REVEAL(UNIQUE(harvest)) # [12, 7, 19, 4]\n REVEAL(INDEX_OF(SORT(harvest), 19)) # 5\n REVEAL(FIRST(SORT(harvest))) # 4\n REVEAL(LAST(SORT(harvest))) # 19\n\n # Maps: read their keys, weave them together\n DECLARE store AS JSON_PARSE(\"{{\\\"bread\\\": 30, \\\"honey\\\": 12}}\")\n REVEAL(KEYS(store)) # [bread, honey]\n REVEAL(VALUES(store)) # [30, 12]\n REVEAL(HAS_KEY(store, \"bread\")) # true\n DECLARE fuller AS MERGE(store, JSON_PARSE(\"{{\\\"milk\\\": 8}}\"))\n REVEAL(fuller) # {bread: 30, honey: 12, milk: 8}\n\n # Numbers: round them kindly, root them, raise them\n REVEAL(ROUND(2.5)) # 3\n REVEAL(ROUND(19.995, 2)) # 20\n REVEAL(FLOOR(3.9)) # 3\n REVEAL(CEIL(3.1)) # 4\n REVEAL(SQRT(144)) # 12\n REVEAL(POW(2, 10)) # 1024\n REVEAL(ABS(4 - 9)) # 5\nEND CREATION\n","file":"commons_demo.god","label":"The Commons (everyday builtins)"},{"code":"# Strings Demo — the scroll of strings: SHOUT, WHISPER, WORDS.\nBEGIN CREATION\n IMPORT \"strings\"\n DECLARE greeting AS \"peace be with you\"\n REVEAL(SHOUT(greeting))\n REVEAL(WHISPER(\"LOUD PRAISE\"))\n REVEAL(WORDS(greeting))\n ASCEND\nEND CREATION\n","file":"strings_demo.god","label":"The Scroll of Strings"},{"code":"# Time Demo — the scroll of hours: NOW and TODAY.\nBEGIN CREATION\n IMPORT \"time\"\n REVEAL(NOW())\n REVEAL(TODAY())\n ASCEND\nEND CREATION\n","file":"time_demo.god","label":"The Scroll of Hours (NOW, TODAY)"},{"code":"# Intent demo — DECLARE INTENT names a rite's purpose in plain words.\n# When the rite is invoked, the Spirit discerns whether its words still\n# walk in the declared intent: alignment is blessed, drift is counseled.\n# Nothing here can fail the run; the Spirit counsels, it does not condemn.\nBEGIN CREATION\n DECLARE INTENT \"bring peace to the household\" ON evening_blessing\n DECLARE INTENT \"bring peace to the household\" ON war_drum\n\n DEFINE RITE evening_blessing()\n REVEAL(\"peace upon this house\")\n END RITE\n\n DEFINE RITE war_drum()\n DECLARE tally AS 1 + 2\n REVEAL(tally)\n END RITE\n\n INVOKE evening_blessing()\n INVOKE war_drum()\nEND CREATION\n","file":"intent_demo.god","label":"Declared Intent"},{"code":"# Anchor demo — ANCHOR writes a value's hash to the chain and returns a\n# receipt map: {chain, anchor_hash, height, timestamp, payload_hash}.\n# Run `godcode ledger verify` afterward to see both chains attested.\nBEGIN CREATION\n DECLARE covenant AS contract(\"everlasting\")\n BREATHE LIFE INTO covenant\n BLESS covenant\n DECLARE receipt AS ANCHOR(covenant)\n REVEAL(receipt)\n REVEAL(\"chain: \" + receipt[\"chain\"])\n REVEAL(\"height: \" + STR(receipt[\"height\"]))\n REVEAL(\"anchor hash: \" + receipt[\"anchor_hash\"])\nEND CREATION\n","file":"anchor_demo.god","label":"Anchored Seals (ANCHOR)"},{"code":"# Consult demo — CONSULT lays a question before the local Spirit oracle\n# and receives two to three sentences of counsel. No external calls;\n# the oracle lives inside the engine.\nBEGIN CREATION\n REVEAL(CONSULT(\"How should I structure this covenant?\"))\n REVEAL(CONSULT(\"What is the wisest next step for this work?\"))\nEND CREATION\n","file":"consult_demo.god","label":"Consult the Oracle"},{"code":"# Scroll Blessings Demo — borrow a blessing from the scroll registry.\n#\n# Install the scroll first:\n# godcode scroll install blessings\n# (installs from the local registry into ~/.godcode/scrolls/).\n# IMPORT then finds it through the normal resolution order —\n# stdlib first, then installed registry scrolls.\n\nBEGIN CREATION\n IMPORT \"blessings\"\n REVEAL(\"the registry bestows this blessing\")\n REVEAL(REVEAL_BLESSING())\n ASCEND\nEND CREATION\n","file":"scroll_blessings_demo.god","label":"Scroll Registry (IMPORT \"blessings\")"},{"code":"# Rites Demo — define a named blessing with parameters,\n# RETURN a value from it, and INVOKE it.\nBEGIN CREATION\n DEFINE RITE BLESSING(name)\n RETURN \"grace upon \" + name\n END RITE\n INVOKE BLESSING(\"seeker\")\n DECLARE word AS BLESSING(\"seeker\")\n REVEAL(word)\n ASCEND\nEND CREATION\n","file":"rites_demo.god","label":"Rites and Closures"},{"code":"# Casting Lots — the scroll of prophecy: let the Spirit choose.\nBEGIN CREATION\n IMPORT \"prophecy\"\n DECLARE tribes AS [Judah, Reuben, Gad, Asher]\n REVEAL(CHOOSE(tribes))\n REVEAL(CAST_LOTS())\n ASCEND\nEND CREATION\n","file":"lots.god","label":"Casting Lots"},{"code":"# tongue: ig\n# Ndewo. The first blessing spoken in Igbo.\n# Run it: godcode run examples/first_blessing_ig.god\n# Dotted vowels are optional: DỊKA and DIKA both speak.\nBIDO OKIKE\nKWUSAA aha DỊKA \"enyi m\"\nGOSI(\"Ndewo, {aha}.\")\n\nKWUSAA ubochi DỊKA [\"Eke\", \"Orie\", \"Afọ\", \"Nkwọ\"]\nGOSI(\"Ụbọchị ahịa anọ: {ubochi}\")\n\nỌ BỤRỤ LEN(ubochi) BỤ 0 MGBE AHỤ\n GOSI(\"Enweghị ụbọchị\")\nELSE\n GOSI(\"Ụbọchị ahịa dị {LEN(ubochi)}\")\nNJEDEBE MA\n\nNWAA\n KWUSAA oke DỊKA 10 / 0\nJIDE\n GOSI(\"E jidere njehie, mana ọrụ ka na-aga n'ihu\")\nNJEDEBE NWAA\n\nGOSI(\"Daalụ.\")\nNJEDEBE OKIKE\n","file":"first_blessing_ig.god","label":"Ndewo (Igbo)"},{"code":"# tongue: pg\n# How far! The first blessing spoken in Nigerian Pidgin.\n# Run it: godcode run examples/first_blessing_pg.god\n# Pidgin shares many words with English (IF, TRY, ELSE), so they stay.\nOYA KREASHON\nTALK name BE \"my padi\"\nSHOW(\"How far, {name}?\")\n\nTALK days BE [\"Monday\", \"Tuesday\", \"Wednesday\"]\nSHOW(\"Three days for the week: {days}\")\n\nIF LEN(days) NA 0 DEN\n SHOW(\"No day dey\")\nELSE\n SHOW(\"We get {LEN(days)} days\")\nFINISH IF\n\nTRY\n TALK share BE 10 / 0\nHOLD\n SHOW(\"Wahala don happen, but the work still dey go\")\nFINISH TRY\n\nSHOW(\"God dey.\")\nFINISH KREASHON\n","file":"first_blessing_pg.god","label":"How far (Nigerian Pidgin)"}],"version":"4.1.0"} diff --git a/tests/test_accountable_agent.py b/tests/test_accountable_agent.py new file mode 100644 index 0000000..a7b3cd6 --- /dev/null +++ b/tests/test_accountable_agent.py @@ -0,0 +1,137 @@ +"""Tests for the accountable agent flagship demo. + +The demo is an agent given exactly one folder: it declares a single +read permission, the invoker grants the host read for that folder +only, and the run is sandboxed. Either layer refusing stops the run. +Everything runs inside a copied examples/ tree, so no real folder +outside the fixture is ever touched. +""" + +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from godcode.sandbox import SandboxPolicy + +REPO = Path(__file__).resolve().parent.parent +DATA = "examples/accountable_agent_data" +SCROLL = "examples/accountable_agent.god" + + +@pytest.fixture() +def examples_tree(tmp_path): + """Copy the whole examples/ tree into tmp_path; return tmp_path.""" + shutil.copytree(REPO / "examples", tmp_path / "examples") + return tmp_path + + +def _run_cli(*argv, cwd): + env = dict(os.environ) + env["PYTHONPATH"] = str(REPO) + os.pathsep + env.get("PYTHONPATH", "") + return subprocess.run( + [sys.executable, "-m", "godcode", *argv], + cwd=str(cwd), + env=env, + capture_output=True, + text=True, + timeout=120, + ) + + +def _expected_fingerprint(tree): + """The report fingerprint the demo must reveal, from first principles.""" + folder = tree / DATA + ledger = "" + for name in sorted(os.listdir(folder)): + text = (folder / name).read_text(encoding="utf-8") + ledger += name + "=" + hashlib.sha256(text.encode()).hexdigest() + ";" + return hashlib.sha256(ledger.encode()).hexdigest() + + +def test_runs_sandboxed_with_one_grant(examples_tree): + proc = _run_cli("run", "--sandbox", "--allow-read", DATA, SCROLL, + cwd=examples_tree) + assert proc.returncode == 0, proc.stderr + out = proc.stdout + for name in ("field-notes-1.txt", "field-notes-2.txt", + "market-prices.txt"): + assert name in out + assert "Files counted: 3" in out + assert "Total characters: 307" in out + assert re.search(r"fingerprinted [0-9a-f]{64}\.", out) + assert _expected_fingerprint(examples_tree) in out + + +def test_sandboxed_report_is_deterministic(examples_tree): + """Two sandboxed runs reveal exactly the same lines: re-runnable proof.""" + argv = ["run", "--sandbox", "--allow-read", DATA, "--json", SCROLL] + first = _run_cli(*argv, cwd=examples_tree) + second = _run_cli(*argv, cwd=examples_tree) + assert first.returncode == 0, first.stderr + assert second.returncode == 0, second.stderr + assert json.loads(first.stdout)["output"] == \ + json.loads(second.stdout)["output"] + + +def test_permissions_show_a_single_read_grant(examples_tree): + proc = _run_cli("permissions", "--json", SCROLL, cwd=examples_tree) + assert proc.returncode == 0, proc.stderr + manifest = json.loads(proc.stdout)["manifest"] + assert len(manifest["read"]) == 1 + assert manifest["read"][0].endswith("accountable_agent_data") + assert manifest["write"] == [] + assert manifest["network"] == [] + assert manifest["stdin"] is False + assert manifest["summon"] == [] + + +def test_sandbox_without_grant_is_refused(examples_tree): + proc = _run_cli("run", "--sandbox", SCROLL, cwd=examples_tree) + assert proc.returncode == 1 + assert "withholds" in proc.stderr or "not granted" in proc.stderr + + +def test_reaching_outside_the_grant_is_refused(examples_tree): + """A scroll that reaches past the granted folder is stopped.""" + scroll = examples_tree / SCROLL + text = scroll.read_text(encoding="utf-8") + text = text.replace( + 'DECLARE data_dir AS "examples/accountable_agent_data"', + 'DECLARE data_dir AS "examples/data"') + scroll.write_text(text, encoding="utf-8") + proc = _run_cli("run", "--sandbox", "--allow-read", DATA, SCROLL, + cwd=examples_tree) + assert proc.returncode == 1 + assert "withholds" in proc.stderr or "did not declare" in proc.stderr + + +def test_manifest_alone_refuses_on_a_plain_run(examples_tree): + """Even with an open host, the declared manifest narrows the run.""" + scroll = examples_tree / SCROLL + text = scroll.read_text(encoding="utf-8") + text = text.replace( + 'DECLARE data_dir AS "examples/accountable_agent_data"', + 'DECLARE data_dir AS "examples/data"') + scroll.write_text(text, encoding="utf-8") + proc = _run_cli("run", SCROLL, cwd=examples_tree) + assert proc.returncode == 1 + assert "did not declare" in proc.stderr + + +def test_allow_read_without_sandbox_is_a_usage_error(examples_tree): + proc = _run_cli("run", "--allow-read", DATA, SCROLL, cwd=examples_tree) + assert proc.returncode == 2 + assert "--sandbox" in proc.stderr + + +def test_strict_policy_read_grant_defaults_to_denied(): + assert SandboxPolicy.strict().allow_read_paths is None + policy = SandboxPolicy.strict(allow_read_paths=("some/folder",)) + assert policy.allow_read_paths == ("some/folder",)