A contract-first, content-addressed language and toolchain for human ↔ AI coding. Intent is code. Effects are visible. Edits are patches. And nothing is called done until verification says so.
The explainer below runs live in your browser (same scenes as the Remotion clip in
video/). Once you render the MP4 (cd video && npm i && npm run render) this
player upgrades to the video automatically.
v1 made Python code verifiable. v2 makes the model language-neutral and the contracts richer. Every line below ships in v2.0.1 — see the Changelog.
Lifted code now hashes to a neutral IR, not Python AST tuples — so a second frontend
could land without touching the store. The first one did: sigil lift script.R,
plus sigil check-r reproducibility contracts (analyze(seed=42) ≡ #hash),
the scientific wedge pytest can't reach.
invariant round_trip { over: enc, dec verify: dec(enc(x)) == x } — a property
across two functions. Patch either one and the invariant re-verifies automatically.
One broken edit can't slip through.
!fs.read vs !fs.write, first-class !db, and a
whole-module fx: budget every function must satisfy. "This module reads config,
never writes, never hits the network" is now a checkable contract.
@sigil.bind — write plain PythonDecorate an ordinary function; Sigil lifts it on import, checks its declared budget
statically, and verifies through the same runner. The .sg language stays for
advanced cases — it's no longer the price of entry.
sigil check --against origin/main fails the build if a bound contract
regressed or silently vanished — one line in Actions. sigil watch re-verifies
on every save. The seatbelt is always on.
Your agent propose_contracts verify clauses; Sigil validates them against
independently generated inputs (not the agent's own example) and binds only on zero
counterexamples over many cases — guesses can't launder into specs. sigil from-pytest
turns parametrize tables into reviewable goal drafts.
Mainstream languages throw away intent; prompts can't be verified. Sigil makes the contract the source of truth and the toolchain its enforcer.
Every definition is named by the sha256 of its canonical AST. Reformatting, comments,
docstrings — hash unchanged (proven by property tests, 200 random mutations a run); but they
aren't discarded — the original source is kept verbatim and returned by expand,
so an agent reads the author's actual docstring, not a re-print (v2.0.3).
Any semantic change — hash moves. "Did the AI change the logic?" is a string compare.
Every function carries its effect row: !net !fs !rand !clock !env… A goal's
budget is checked statically; a sneaked-in write fails the build naming the exact
call chain. When analysis can't see through dynamic code it says !unsafe? —
uncertainty is never silenced.
Goals declare executable verify: clauses. Implementations run them
subprocess-isolated with timeouts; a pass binds goal↔impl in the store, anything else
stays provisional. Patches are auto-verified before success is ever shown.
Real output — sigil lift examples/lift-legacy/webapp.py, a deliberately
effect-rich legacy module. One line per definition; the AI reads this, not your files.
#705b get_config(key, default) !env #d939 read_cache(name, ttl_seconds) !clock !fs #d4b8 fetch_user(user_id) !clock !fs !net #9b4e order_totals(orders) pure? #f574 jitter_sleep(attempt) !clock !rand #e70b dispatch(event) !unsafe? ← dynamic dispatch: flagged, not guessed ; '?' marks static guesses — Tier 2 over-approximates, never trusts.
From the scripted agent-session transcript (examples/agent-session/):
a seeded bug fixed with zero file reads, zero file writes, one patch.
-- verify reports the failure, with values: verify triple: fail — out == n * 3 with out=8 inputs={'n': 4} -- the agent expands only the 11-token implementation, not the file: fn triple(n Int) -> Int { ret n * 2 } -- one 18-token patch op, auto-verified before display (R3): patch #6e01 { body.stmts.0.value.right.val := "3" } ⇒ #a4c2 · verify: pass · goal triple: verified -- the sheet only ever grew (R1, property-tested): #6e01 -> #a4c2 triple
The digest sheet never rewrites history — your cached prompt prefix stays byte-stable. Proven with a hypothesis property over arbitrary op sequences.
expand(#hash) is byte-identical forever. Re-reading code is cheap cached input; re-emitting it from memory is expensive output.
Failures return the failing clause, observed values, and the subtree hash to patch — never “try again from scratch”. The retry term is the one that dominates cost.
Real production BPE tokenizer, real artifacts, reproducible via
scripts/benchmark.py (full report in docs/benchmarks.md). Where
measurement contradicted the spec's estimates, the measured number won.
| source | full source | digest sheet | reduction |
|---|---|---|---|
| demo_module.py (4 fns) | 319 tok | 133 tok | 2.4× |
| lift-legacy webapp.py (15 fns) | 768 tok | 306 tok | 2.5× |
| requests 2.34.2 — 6,385 lines, 302 definitions | 52,464 tok | 8,812 tok | 6.0× |
Honest note: the spec guessed "10×+ at first contact" — measurement says 6.0× on a real repo (the neutral IR is marginally tighter than v1). The bigger win is per iteration: that 8.8k-token sheet is cache-eligible (R1), an edit expands ~19 tokens and a patch costs ~29 output tokens — versus re-reading 52k fresh tokens.
~0.15 ms
median cached hit on unchanged code —
78× faster than a ~12 ms cold run. Content-addressed: a file read + parse. Timeouts/errors never cached.
0
under-reports across 39 labeled
functions (35 fixtures), 2.4% over-report. The security-critical metric — a missed effect is a bug, an extra one is noise.
~3,800
definitions/sec
(~79k lines/s) — all of requests lifts in under 0.1 s. Parse + hash only; no code runs.
29 tok
to emit a verified
patch — sheet 19 (cached) + expand 19 + patch 29 out, vs 60 to re-read even a tiny module. Output scales with the change.
100%
of the 19 requests modules are
hash-stable through lower → render → re-lower — the property that lets patches and expand ride on the neutral IR.
191
tests green · 92% coverage on
core/lift/transpile · ruff clean · property-tested hashing, round-trips, patch≡re-lift, R1 · CI on Linux 3.11–3.13 + Windows.
The same v2.0.1 numbers as plots, each with what it measures and how it moved
across versions. Reproduce any of them with python3 scripts/benchmark.py.
How much smaller the digest sheet an agent reads is than the raw file. Bar = the sheet as a fraction of the full source; shorter is better.
What it means: the agent references hashes, not bodies — a 10k-line repo becomes a one-page sheet. v1 5.9× → v2.0.1 6.0× on requests (the neutral IR sheets are marginally tighter).
The actual cost of one fix: read the sheet, expand only the target, emit a patch — versus re-reading the whole module. Output (the expensive side) scales with the change.
What it means: R1 keeps the sheet cache-eligible, R2 expands on demand, R3 emits a patch not a file. At repo scale that's an 8.8k cached-token sheet vs 52k fresh per turn — where the >10× compounding lives.
A goal's contracts run subprocess-isolated once (cold); an unchanged re-verify is a content-addressed cache hit. Log scale — the cached bar is genuinely that small.
What it means: re-checking unchanged code is effectively free, so the loop stays fast. v1 gate was <50 ms → v2.0.1 measures ~0.15 ms (78× vs cold).
The security metric. A missed effect is a bug; an over-reported one is acceptable noise. Bars = hand-labeled fixtures; the line that matters is flat at zero.
What it means: 0 under-reports, every version, even as fixtures grew
30→35 (read/write modes + !db added in v1.1). Over-report 2.6% → 2.4%.
Each release shipped with the full suite passing and tagged. Each exit gate was written as a failing test before the feature it gates.
What it means: coverage of behavior grew with capability, never traded away. 130 → 191 tests across seven releases; + R, invariants, IR round-trip property tests in v2.
A proposed rule is checked against independently generated inputs, not the
witness the agent chose. Measured on the report's clamp exploit.
What it means: the false rule out == x that earned a lucky
verified before is now refuted by a generated counterexample and stays provisional;
a genuinely true rule still verifies over 40 cases. Hardened in v2.0.2.
v1 was a Python verifier; v2 made the model language-neutral and the contracts richer. New capabilities, measured where measurable.
What it means: a second language (R) lands without touching the store; lifted modules round-trip the neutral IR at 100%; lift runs at ~3,800 defs/s. All new in v2.
Every phase exit gate was written as a failing test before its implementation.
Then a real first user filed a report (a true bug, fixed) and a roadmap. Three more releases shipped — depth, then width — same discipline: failing test first, suite green at every commit.
@sigil.bind · patch-by-snippet · unbind/diff✓ shippedsigil check CI gate · sigil watch · property generation✓ shippedFrom zero to a verifying, patch-driven codebase — for humans first, then for
your agents. Everything here is copy-paste real; full docs live in docs/.
1 · Setup
sigil-build/ repo root:pip install -e ".[dev,harness]" # core + tests + MCP server sigil --version # sigil 2.0.3
Core installs are lean: stdlib + cbor2. The [harness] extra adds the
mcp package for sigil serve; [dev] adds pytest/hypothesis/ruff.
2 · Everyday CLI
sigil lift path/to/your/code ; one line per definition: #d4b8 fetch_user(user_id) -> ? !clock !fs !net
.sigil/ store.sigil build prices.sg --store . --json
# writes prices.py + test_fetch_prices.py; prints goal hashesin: parameters need an inputs file.echo '{"tickers": ["AAPL"], "start": "a", "end": "b"}' > inputs.json
sigil verify '#a1b2c3d4' --store . --inputs inputs.json
# verify fetch_prices: pass (140ms) → goal status: verified · re-runs are <50ms cache hitsExit codes: 0 ok / verify pass · 1 verify fail · 2 usage or build rejection · 3 unexpected (never a traceback). Set SIGIL_RELEASE=1 to strip contract assertions from transpiled code in production.
2b · New in v2 — modes, R, invariants, CI
@sigil.bind lifts on import and checks the budget statically.import sigil
@sigil.bind(verify=["out == n * 3"], fx="pure", inputs={"n": 4})
def triple(n):
return n * 3
# importing registers goal+impl; sigil verify (or check) binds on passmodule config_io
fx: !fs.read -- every fn may read files, never write, never net
fn load(p Str) -> Map
!fs.read
{ ret parse(open(p).read()) }invariant round_trip {
in: x Int
over: enc, dec
verify:
dec(enc(x)) == x
}check-r needs Rscript).sigil lift analysis.R # tokenizer-canonical; library() → !unsafe?
sigil check-r analysis.R --fn analyze --args "[42]" --expect '#a1b2c3d4'sigil check --against origin/main # exit 1 if a bound goal regressed or vanished sigil watch . # save → re-lift → re-verify, continuously
Migrating a v1 store? sigil migrate bumps its format — old objects stay readable, re-lift at leisure. Bridge existing tests with sigil from-pytest tests/ → reviewable goal drafts (never auto-registered).
3 · MCP — wire your agent in
claude mcp add sigil -- sigil serve --root /path/to/your/repo
{
"mcpServers": {
"sigil": { "command": "sigil", "args": ["serve", "--root", "/path/to/your/repo"] }
}
}| tool | what it does |
|---|---|
| lift(path) | Python → digest sheet; idempotent; changes append #old → #new |
| sheet() | the append-only session sheet (R1) — agents read this, not files |
| expand(hash, form?) | readable source (default) or form="canonical" — the patchable data form; derive patch paths from it (R2) |
| load_module(source) | create goals over pure MCP: registers a Sigil module's goals + fns in the store (v1.0.1) |
| patch(hash, ops, inputs?) | AST edit → new hash, auto-verified before success (R3) |
| patch_snippet(hash, snippet, inputs?) | send the corrected source; Sigil tree-diffs to minimal ops — no path authoring (v1.1) |
| verify(goal, inputs?) | run verify clauses; subprocess + timeout; cached by (goal, impl, inputs); pass ⇒ binds |
| verify_invariant(hash, inputs?) | check a multi-fn invariant; patching any fn it covers re-verifies it (v2.0) |
| propose_contract(fn_hash, clauses, inputs?) | Tier 3: agent proposes verify clauses; binds only by passing (v2.0) |
| session_close() | stats + compacted sheet for the next session |
sheet() → read digests, pick the failing goal expand(#6e01) → see only the code you'll change patch(#6e01, [{"path": "body.stmts.0.value.right.val", "op": "replace", "value": "3"}], inputs={"n": 4}) → {"new_hash": "#a4c2", "verify": {"status": "pass"}} — verified before you ever see "done"
4 · Patch ops in 30 seconds
Ops address the canonical form shown by expand. Path tokens are dict keys,
list indices, or host-AST field names; op ∈ replace insert delete.
Literals end in .val. Malformed ops fail with the op index + failing token (code: bad_path) —
re-expand and re-derive, don't guess twice.
-- Sigil-written fn: change a constant {"path": "body.stmts.0.value.right.val", "op": "replace", "value": "3"} -- lifted code: a neutral IR sits under body.data (v2.0). A def is ["def", name, args, [body]...]; -- derive paths from expand(hash, form="canonical"), or skip path authoring with patch_snippet {"path": "body.data.3.0.1.2", "op": "replace", "value": "30.0"}
Easiest of all — patch_snippet: send the whole corrected definition and Sigil computes the minimal ops for you (snippet ≡ re-lift, by hash).
patch_snippet("#6e01", "fn triple(n Int) -> Int\n pure\n{\n ret n * 3\n}", {"n": 4})
-- grow / shrink statement lists
{"path": "body.stmts.1", "op": "insert", "value": { ...stmt data... }}
{"path": "body.stmts.1", "op": "delete"}5 · Skills — teach your agent the house rules
The repo ships agent skills in .claude/skills/ — Claude Code picks them up
automatically when working in this repo (Cowork: add the folder's skills via Settings → Capabilities).
One is for using Sigil; five govern developing Sigil itself.
| skill | consult when… |
|---|---|
| sigil-agent-workflow ★ for users | connected to any sigil serve server — the sheet→expand→patch→verify discipline, real patch-path shapes, failure playbook |
| sigil-canonical-hashing | touching core AST, canonicalization, or anything hash-stability |
| sigil-effect-inference | touching the effect analyzer, fixtures, or chasing a wrong effect row |
| sigil-transpile-verify | parser/printer, transpiler, grammar, or verify-runner work |
| sigil-harness-rules | harness/server work — the frozen tool contract and R1–R3 |
| sigil-quality-gates | before claiming a phase done or cutting a release |
6 · Troubleshooting
| symptom | meaning → remedy |
|---|---|
| build: "effect budget exceeded" | implementation uses an effect the goal doesn't budget — the message names the call chain; remove the call or extend fx: |
| build: "!unsafe without an ack:" | unsafe budgets must be acknowledged — add ack: "reason" to the goal |
| verify: "needs inputs" | goal declares in: params — pass --inputs file.json keyed by param names |
| verify: timeout | implementation or clause ran > 10s — raise --timeout or fix the loop; timeouts never bind and are never cached |
| patch: code "bad_path" | path token doesn't exist — expand the hash and rebuild the path from what you see |
| verify hangs/times out via serve | fixed in v1.0.1 (verify child inherited the MCP stdin pipe) — upgrade; verdicts now return in ms |
| sigil --version shows 1.27.x | that's an unrelated PyPI package named "sigil" shadowing this one — pip uninstall sigil, then install this repo (dist name sigil-lang) |
| serve: "mcp not installed" | pip install "sigil[harness]" |
| a row says !unsafe? | not an error — the analyzer refuses to guess about dynamic code; treat as effectful until verified |
| check-r: "Rscript not on PATH" | install R to run reproducibility checks — lifting .R files needs no R runtime |
| old hashes after upgrade to v2 | lifted digests moved to the neutral IR once — run sigil migrate; old objects stay readable, re-lift when convenient |
sigil lift crashes on Windows (charmap/cp1252) | fixed in v2.0.1 — output is pinned to UTF-8 and the sheet footer is ASCII; upgrade (older: set PYTHONUTF8=1) |
| verify_invariant disagrees with a patch's verdict | fixed in v2.0.1 — the invariant binding is now persisted to the patched module on pass |
| build: "module budget exceeded" | a fn exceeds the module-wide fx: (or __sigil_fx__) budget — the message names the call chain |
Deeper dives: docs/quickstart.md · docs/language-guide.md ·
docs/harness-guide.md · docs/lifting-guide.md · docs/cost-model.md · docs/benchmarks.md · docs/limitations.md
Six releases, every one shipped with the suite green and tagged in git
(v1.0.0 → v2.0.3). Newest first.
expand returned a de-commented projection — it dropped the
docstring and every comment. Now the store keeps the original source (keyed by the node's
hash, never hashed, so identity is unchanged) and expand returns it verbatim
for lifted, unedited functions; a patched-only AST returns a clearly-labeled projection.and <= !=) by default;
glyphs (∧ ≤ ≠) are opt-in — they cost an extra BPE token each. No hashes change.propose_contract proposer-graded validation — proposals now validate against independently generated inputs (typed generator, or edge-biased probes for untyped lifted params), not the one witness the agent chose. A false rule that passed on a lucky input is now refuted by a generated counterexample.provisional.tier-3 verified (40 cases) vs rejected (counterexample) — so a proven rule reads differently from a lucky one.lift shouldn't crash.sigil lift.verify_invariant now agrees with the patch's verdict (was contradictory).from-pytest reads any expected column · migrate --store · rejected proposals labelled on the sheet · Windows + 3.13 CI lanes; goldens pinned to their Python minor.sigil migrate surveys + bumps format.sigil lift script.R: tokenizer-canonical Tier-1 hashing + token-rule effects (library()/eval → !unsafe?). sigil check-r result-hash reproducibility contracts.invariant { over: enc, dec verify: dec(enc(x)) == x }; patching either fn re-verifies automatically; passing binds the invariant to all impl hashes.propose_contract MCP tool registers provisional, binds only by passing. sigil from-pytest extracts parametrize tables into reviewable drafts.inputs: "file.json"; the verdict cache key now includes the inputs digest (a real v1.0 flaw: different inputs shared an entry).[--against REF] — rebuilds every .sg, re-verifies every goal; fails CI on a regression or a contract dropped without a tombstone. One line in Actions.!fs.read / !fs.write, first-class !db, and whole-module fx: budgets in both .sg and __sigil_fx__.sigil serve and risking a traffic-read leak. Now stdin=DEVNULL; regression-tested through a real stdio client.expand(hash, form="canonical") exposes the patch-path schema; patch returns the display hash; __sigil_* scaffolding filtered from sheets.sigil-lang — the PyPI name "sigil" was taken (and shadowing the test install). Import + CLI stay sigil.Full detail with rationale lives in CHANGELOG.md and the running decision log
docs/decisions.md (D-001 … D-038). Every release is a git tag; git push origin main --tags
publishes them.