{"description": "Verified Soma programs. Every entry passed `soma check` (and `soma test` / `soma verify` where applicable) on the soma version below, re-run when this index was generated. Fetch `url` for the source. Filter by `domain` or `features` to find a working example of what you are about to write.", "soma_version": "2.5.0", "count": 319, "domains": {"aerospace": 15, "agents": 15, "algorithms": 18, "civic": 14, "data": 17, "devops": 14, "energy": 15, "escrow_finance": 15, "finance": 17, "games": 19, "games_economy": 16, "governance": 16, "logistics": 15, "math": 17, "medical": 14, "records": 17, "safety_interlocks": 14, "services": 3, "state_machines": 14, "text": 18, "web": 16}, "features": ["agent", "cost", "fail", "guard", "http", "invariant", "lambda", "match", "multi_cell", "native", "pipeline", "service", "state_machine", "sum_type", "think", "tools", "try"], "programs": [{"id": "aerospace/autopilot_authority", "domain": "aerospace", "title": "AUTOPILOT AUTHORITY — Aeroflot 593: the half-disconnected autopilot", "summary": "AUTOPILOT AUTHORITY — Aeroflot 593: the half-disconnected autopilot On 23 March 1994, Aeroflot Flight 593 (an A310) crashed into a Siberian hillside, killing 75. The captain's children were at the controls; the boy's yoke force partially overrode the autopilot — it silently dropped the AILERON channel while the rest stayed engaged. No light, no horn. The crew flew for crucial seconds believing the autopilot had the aircraft. Nobody had authority, and nobody knew. The defect was authority as PER-AXIS FLAGS that could disagree. Here authority is ONE state. Yoke force past the breakout threshold drives the machine to override_latched — fully, loudly, all axes — and the only exit is an explicit crew acknowledgment. There is no edge from override_latched back to engaged: a fought autopilot can never silently take the aircraft back. A memory invariant caps servo torque so the actuator can never be commanded past its breakout rating.", "url": "https://soma-lang.dev/corpus/aerospace/autopilot_authority.cell", "repo_path": "examples/corpus/aerospace/autopilot_authority.cell", "lines": 108, "features": ["state_machine", "invariant", "try"], "cells": ["AutopilotAuthority", "AuthorityTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/cabin_pressurization", "domain": "aerospace", "title": "CABIN PRESSURIZATION — Helios 522: the manual-mode takeoff, unrepresentable", "summary": "CABIN PRESSURIZATION — Helios 522: the manual-mode takeoff, unrepresentable On 14 August 2005, Helios Airways Flight 522 took off from Larnaca with the pressurization mode selector still in MANUAL — left there after an overnight maintenance leak check. The cabin never pressurized. As the 737 climbed, the cabin altitude climbed with it; the warning horn was mistaken for the takeoff-config horn; the crew lost consciousness from hypoxia, and 121 people died when the aircraft ran out of fuel. The failure was a MODE that survived a phase change: maintenance state leaked into flight state. Here those phases are one machine. The only path to airborne goes THROUGH auto_verified — the checklist step where the selector is confirmed in AUTO. From manual_maint there is no edge to airborne at all. And the cabin-altitude ledger refuses to record a hypoxic cabin: the controller's setpoint cannot leave the safe band.", "url": "https://soma-lang.dev/corpus/aerospace/cabin_pressurization.cell", "repo_path": "examples/corpus/aerospace/cabin_pressurization.cell", "lines": 106, "features": ["state_machine", "invariant", "try"], "cells": ["CabinPressure", "PressurizationTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "6 passed, 5 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/cargo_door", "domain": "aerospace", "title": "CARGO DOOR — Turkish Airlines 981: \"indicated locked\" is not LOCKED", "summary": "CARGO DOOR — Turkish Airlines 981: \"indicated locked\" is not LOCKED On 3 March 1974, Turkish Airlines Flight 981 — a DC-10 climbing out of Paris — lost its aft cargo door at 11,500 feet. The latch cams had never gone over-center; a baggage handler had forced the handle and the indicator showed LOCKED anyway. The door blew, the cabin floor collapsed into the cargo hold, and the control cables running through it were severed. All 346 aboard died. Two years earlier the SAME failure over Windsor, Ontario had been survivable — and the fix was made optional. The defect: \"locked\" was an INDICATION derived from handle position, not a verified state. Here lock verification is a state you can only REACH by actually doing it — the vent-door visual check is the only edge into locked_verified, and pressurization is only reachable FROM locked_verified. A latched-but-unverified door cannot be pressurized: the edge does not exist. Differential pressure is bounded in memory.", "url": "https://soma-lang.dev/corpus/aerospace/cargo_door.cell", "repo_path": "examples/corpus/aerospace/cargo_door.cell", "lines": 116, "features": ["state_machine", "invariant", "try"], "cells": ["CargoDoor", "DoorTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "6 passed, 5 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/docking_approach", "domain": "aerospace", "title": "DOCKING APPROACH — Progress / Mir 1997: abort means ABORT", "summary": "DOCKING APPROACH — Progress / Mir 1997: abort means ABORT On 25 June 1997 the uncrewed Progress M-34 freighter, under manual TORU control, came in on Mir too fast and off-axis. The crew saw it late, the braking command came late, and Progress struck the Spektr module — puncturing the station and depressurizing a wing of it. The crew survived by sealing the hatch. The lesson every rendezvous system learned: a bad approach is not \"salvaged\", it is killed, and the vehicle retreats. You re-plan from scratch. Here the approach is a state machine where ABORTED IS TERMINAL: once an abort fires, there is no edge back to any approach state — a new rendezvous is a new machine instance, with new ground review. The final-approach gate is also a memory invariant: a closing rate above the structural capture limit cannot even be recorded as commanded.", "url": "https://soma-lang.dev/corpus/aerospace/docking_approach.cell", "repo_path": "examples/corpus/aerospace/docking_approach.cell", "lines": 116, "features": ["state_machine", "invariant", "try"], "cells": ["DockingApproach", "DockingTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/fire_bottle", "domain": "aerospace", "title": "ENGINE FIRE BOTTLE — one-shot suppression, fuel off FIRST An engine fire bottle is halon under pressure, and it is ONE-SHOT", "summary": "ENGINE FIRE BOTTLE — one-shot suppression, fuel off FIRST An engine fire bottle is halon under pressure, and it is ONE-SHOT. Twin-engine ETOPS aircraft carry exactly two per engine; when they are gone, the crew's remaining option is to land. Two procedural truths are written in blood across decades of engine-fire accidents: 1. Pull the fire handle (cut fuel and hydraulics) BEFORE firing the bottle. Halon discharged into a fuel-fed fire is wasted — the fire relights, and now you have one bottle and a burning wing. 2. Never let the controller believe a discharged bottle can fire again. A \"suppression available\" indication backed by an empty bottle is how crews delay the diversion that would have saved them. Here both rules are the machine's shape: the bottle states are reachable only THROUGH fuel_shutoff, and bottles_exhausted is TERMINAL — soma verify proves no path refills a fired bottle.", "url": "https://soma-lang.dev/corpus/aerospace/fire_bottle.cell", "repo_path": "examples/corpus/aerospace/fire_bottle.cell", "lines": 117, "features": ["state_machine", "invariant", "try"], "cells": ["FireSuppression", "BottleTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/fuel_crossfeed", "domain": "aerospace", "title": "FUEL CROSSFEED — Air Transat 236: never feed a leak from the good tank", "summary": "FUEL CROSSFEED — Air Transat 236: never feed a leak from the good tank On 24 August 2001, Air Transat Flight 236 (an A330 over the Atlantic) developed a fuel leak in the right engine's feed line. Following the imbalance checklist, the crew opened the crossfeed valve — and pumped the LEFT tank's fuel into the leak too. Both engines flamed out; the aircraft glided 75 miles, dead-stick, to a runway in the Azores. 306 people survived on the captain's gliding skill, not on the system. The procedure trap: crossfeed is the correct response to an imbalance and the catastrophic response to a leak — and the two look identical on the gauges unless you check totals. Here that check is structural: opening crossfeed REQUIRES a fuel-total reconciliation, a detected leak drives the machine to leak_isolated — a TERMINAL state with no edge to crossfeed_open, ever — and the tank ledger refuses negative or overfull quantities outright.", "url": "https://soma-lang.dev/corpus/aerospace/fuel_crossfeed.cell", "repo_path": "examples/corpus/aerospace/fuel_crossfeed.cell", "lines": 118, "features": ["state_machine", "invariant", "try"], "cells": ["FuelCrossfeed", "CrossfeedTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/gear_interlock", "domain": "aerospace", "title": "LANDING GEAR — weight-on-wheels interlock, made unrepresentable", "summary": "LANDING GEAR — weight-on-wheels interlock, made unrepresentable Gear-retraction-on-the-ground is an old, recurring accident: a crew or mechanic commands \"gear up\" while the aircraft is sitting on its wheels, the squat-switch wiring is faulted or bypassed, and the airframe drops onto its belly — people under the wings die. The classic fix is a weight-on-wheels (WoW) microswitch that an interlock relay reads. The classic failure is that the switch and the gear lever are TWO separate signals that can disagree. Here ground contact and gear position are ONE state. There is no edge from ground_down to airborne_up: retraction on the ground is not a guarded command, it is a transition that does not exist. The symmetric hazard — calling a gear-up arrival a normal touchdown — is equally absent. A memory invariant keeps the hydraulic system inside its burst rating no matter what the pump controller writes.", "url": "https://soma-lang.dev/corpus/aerospace/gear_interlock.cell", "repo_path": "examples/corpus/aerospace/gear_interlock.cell", "lines": 99, "features": ["state_machine", "invariant", "try"], "cells": ["GearInterlock", "GearTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "7 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/launch_commit", "domain": "aerospace", "title": "LAUNCH COMMIT CRITERIA — Challenger: no waiver path to ignition", "summary": "LAUNCH COMMIT CRITERIA — Challenger: no waiver path to ignition On 28 January 1986, Challenger launched at 36°F — far below the SRB O-ring qualification temperature. Engineers argued against the launch the night before; the criterion was effectively waived under schedule pressure. 73 seconds later the right SRB field joint failed and seven astronauts died. The Rogers Commission's finding was procedural: the system ALLOWED a red criterion to be argued green. Here the launch commit criteria are a ledger, and ignition is a transition whose handler refuses unless EVERY criterion reads green. There is no waiver argument to have: a red board cannot ignite because the committed state is only entered through the all-green gate, and once SRBs light, liftoff is TERMINAL — solids cannot be shut down, and the machine says so: there is no edge out.", "url": "https://soma-lang.dev/corpus/aerospace/launch_commit.cell", "repo_path": "examples/corpus/aerospace/launch_commit.cell", "lines": 127, "features": ["state_machine", "invariant", "try"], "cells": ["LaunchCommit", "CommitTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/oxygen_tank_heater", "domain": "aerospace", "title": "CRYO TANK HEATER — Apollo 13: the thermostat that welded shut", "summary": "CRYO TANK HEATER — Apollo 13: the thermostat that welded shut Apollo 13's oxygen tank 2 exploded 200,000 miles from Earth because of a heater interlock that failed YEARS earlier, on the ground. The tank heaters had thermostatic switches rated for 28 volts; a pre-flight detanking test ran them at 65 volts. The contacts welded closed. With the cutoff fused shut, a heater cycle that should have stopped at 80°F ran the tank interior to an estimated 1000°F, baking the Teflon off the fan wiring. In flight, a routine cryo stir sparked the bare wires and the tank blew — \"Houston, we've had a problem.\" The defect was a LIMIT that lived in a relay that could fail welded. Here the limit lives in memory itself: the tank-temperature ledger refuses any write above the thermostat ceiling, so the 1000°F state is unrepresentable no matter what the heater controller commands. An overtemp ATTEMPT trips the heater machine to thermal_lockout — a terminal state that only maintenance (a new instance) escapes.", "url": "https://soma-lang.dev/corpus/aerospace/oxygen_tank_heater.cell", "repo_path": "examples/corpus/aerospace/oxygen_tank_heater.cell", "lines": 110, "features": ["state_machine", "invariant", "try"], "cells": ["CryoHeater", "HeaterTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/parachute_sequence", "domain": "aerospace", "title": "PARACHUTE SEQUENCE — Genesis: the drogue that never fired On 8 September 2004 the Genesis sample-return capsule hit the Utah desert at 311 km/h", "summary": "PARACHUTE SEQUENCE — Genesis: the drogue that never fired On 8 September 2004 the Genesis sample-return capsule hit the Utah desert at 311 km/h. The G-switch that should have sensed deceleration and started the parachute sequence had been installed BACKWARDS — a drawing error that sailed through review. No drogue, no main, just a crater and three years of solar-wind samples shattered. (Its sister design on Stardust, wired correctly, landed perfectly.) The deeper defect: the deploy sequence lived in event timers keyed off one sensor, with nothing structural forcing the order. Here descent is a LINEAR machine — drogue, then main, then touchdown, terminal. Main deployment from entry (a chute shredded at Mach 1.4) does not exist as a transition, touchdown without chutes does not exist as a transition, and the deploy-altitude ledger refuses values outside the corridor.", "url": "https://soma-lang.dev/corpus/aerospace/parachute_sequence.cell", "repo_path": "examples/corpus/aerospace/parachute_sequence.cell", "lines": 105, "features": ["state_machine", "invariant", "try"], "cells": ["ParachuteSequence", "SequenceTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/range_safety", "domain": "aerospace", "title": "RANGE SAFETY — the flight termination system's three one-way doors", "summary": "RANGE SAFETY — the flight termination system's three one-way doors A flight termination system (FTS) is the explosive last resort that destroys a rocket veering toward people. Its safety logic cuts both ways. In 1996 a Long March 3B went off course two seconds after liftoff and flew into a village near Xichang; an off-course vehicle that is NOT terminated kills on the ground. But the inverse hazard is just as real: a destruct system that can fire while technicians are torquing bolts on a \"safed\" pad vehicle, or that can be re-armed after a nominal flight ends, is itself the accident. Here the FTS has exactly three one-way doors. SAFED cannot terminate — the edge is absent, so no stray command, test signal, or RF hit can blow a pad vehicle. ARMED can either fire (terminated, terminal) or stand down after orbit (safed_orbital, terminal). Nothing exits the terminal states: a fired FTS is gone, a flown-out FTS can never be re-armed. The deviation ledger that justifies a destruct is bounded.", "url": "https://soma-lang.dev/corpus/aerospace/range_safety.cell", "repo_path": "examples/corpus/aerospace/range_safety.cell", "lines": 114, "features": ["state_machine", "invariant", "try"], "cells": ["RangeSafety", "FtsTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/stage_separation", "domain": "aerospace", "title": "STAGE SEPARATION — the ascent sequence as a proven order", "summary": "STAGE SEPARATION — the ascent sequence as a proven order Launch vehicle staging has exactly one correct order: first-stage cutoff, THEN separation, THEN second-stage ignition. Every permutation is a lost vehicle. Igniting stage 2 while still bolted to stage 1 fires an engine into a full propellant tank. Separating under thrust drives the stages into each other (recontact has ended real flights). Lighting stage 2 before separation completes burns the interstage. In flight software these are timer-sequenced events that a dropped packet or a stuck sensor can reorder. Here the sequence is a LINEAR state machine: each event is reachable only from its predecessor, and orbit_insertion is terminal — soma verify proves there is no path that skips, repeats, or reverses a staging event.", "url": "https://soma-lang.dev/corpus/aerospace/stage_separation.cell", "repo_path": "examples/corpus/aerospace/stage_separation.cell", "lines": 90, "features": ["state_machine", "invariant", "try"], "cells": ["StageSequencer", "SequenceTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "7 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/tcas_ra", "domain": "aerospace", "title": "TCAS RESOLUTION ADVISORY — Überlingen: the opposite maneuver is no state", "summary": "TCAS RESOLUTION ADVISORY — Überlingen: the opposite maneuver is no state On 1 July 2002, over Überlingen, a Tu-154 and a DHL 757 were converging at the same level. TCAS told the Tupolev crew CLIMB and the 757 crew DESCEND — a coordinated, deconflicted pair. Then the ground controller, working two stations alone, told the Tupolev to descend. The crew followed the human voice instead of the RA. Both aircraft descended into each other. 71 people died, most of them children. The rule written after that night: once a resolution advisory is active, the RA has authority — an ATC instruction in the opposite sense must not be flown. Here that rule is the machine's shape: from ra_climb the ONLY pilot response state is complying_climb. Flying a descend against a climb RA is not a violation to detect — it is a transition that does not exist. Altitude commands are bounded by the envelope ledger.", "url": "https://soma-lang.dev/corpus/aerospace/tcas_ra.cell", "repo_path": "examples/corpus/aerospace/tcas_ra.cell", "lines": 121, "features": ["state_machine", "invariant", "try"], "cells": ["TcasAdvisory", "RaTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "7 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/thrust_reverser", "domain": "aerospace", "title": "THRUST REVERSER — Lauda Air 004: in-flight deployment, made structural", "summary": "THRUST REVERSER — Lauda Air 004: in-flight deployment, made structural On 26 May 1991, Lauda Air Flight 004 — a Boeing 767 climbing out of Bangkok — lost 223 people when the left engine's thrust reverser deployed IN FLIGHT. Reverse thrust at climb power tore the airflow off the wing; the aircraft broke up in seconds. The reverser system had interlocks, but they were plumbing and relays guarding a hydraulic valve — and a fault sequence got past them. Here flight phase and reverser position are ONE state machine. The state {in flight, reverser deployed} is not guarded against — it is not a state. Deployment is reachable only from on_ground (weight on wheels), and the only exit from reverse thrust is stowing: you cannot rotate back into the air with the buckets out either.", "url": "https://soma-lang.dev/corpus/aerospace/thrust_reverser.cell", "repo_path": "examples/corpus/aerospace/thrust_reverser.cell", "lines": 100, "features": ["state_machine", "invariant", "try"], "cells": ["ThrustReverser", "ReverserTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "aerospace/unreliable_airspeed", "domain": "aerospace", "title": "UNRELIABLE AIRSPEED — AF447: the autopilot never flies on bad data On 1 June 2009, Air France 447's pitot tubes iced over in a storm over the Atlantic", "summary": "UNRELIABLE AIRSPEED — AF447: the autopilot never flies on bad data On 1 June 2009, Air France 447's pitot tubes iced over in a storm over the Atlantic. The three airspeed channels disagreed; the autopilot dropped out and the flight control law degraded to alternate — with stall protection gone. In the confusion of the handover the crew held the A330 in a stall from 38,000 feet to the ocean. 228 people died. Two structural properties matter, and this controller makes both machine-shaped rather than flag-shaped: 1. There is NO state with the autopilot engaged and degraded data. The instant the channels split, AP-off and alternate law arrive as ONE transition — never a half-handover. 2. Alternate law is LATCHED for the remainder of the flight (as on the real A330): when the pitots thaw and the speeds agree again, the law does NOT spring back. soma verify proves the latch — the state is terminal.", "url": "https://soma-lang.dev/corpus/aerospace/unreliable_airspeed.cell", "repo_path": "examples/corpus/aerospace/unreliable_airspeed.cell", "lines": 105, "features": ["state_machine", "invariant", "try"], "cells": ["AirDataLaw", "LawTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "agents/approval_gate", "domain": "agents", "title": "Human-in-the-loop approval gate guarding an irreversible action", "summary": "Human-in-the-loop approval gate guarding an irreversible action. Demonstrates: approve() as a lifecycle gate, a state machine where the \"executing\" path is only reachable past the gate, and a rejected path that lands in a distinct terminal. approve() never answers on its own: a test scripts it with `mock approve true|false`; `soma run` asks the person at the terminal; under `soma serve` (nobody attached) it raises kind \"approval_required\" unless SOMA_APPROVE=always|never states an explicit policy. Run: soma run approval_gate.cell deploy \"v2.1.0\" (asks y/N) SOMA_APPROVE=never soma run approval_gate.cell deploy \"v2.1.0\" Test: soma test approval_gate.cell", "url": "https://soma-lang.dev/corpus/agents/approval_gate.cell", "repo_path": "examples/corpus/agents/approval_gate.cell", "lines": 70, "features": ["state_machine", "agent"], "cells": ["Deployer", "DeployTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/bounded_retry", "domain": "agents", "title": "Bounded-retry agent — the verified-termination poster child", "summary": "Bounded-retry agent — the verified-termination poster child. A naive `failed -> working` retry arrow creates a livelock the model checker would reject. Here the retry COUNT lives in memory and the loop is bounded, so the machine always reaches succeeded or exhausted. Run: SOMA_LLM_MOCK=echo soma run bounded_retry.cell --signal attempt \"flaky-op\" 2 Test: SOMA_LLM_MOCK=echo soma test bounded_retry.cell", "url": "https://soma-lang.dev/corpus/agents/bounded_retry.cell", "repo_path": "examples/corpus/agents/bounded_retry.cell", "lines": 60, "features": ["state_machine", "agent"], "cells": ["Retrier", "RetryTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/budget_guard", "domain": "agents", "title": "Token-budget enforcement, made testable", "summary": "Token-budget enforcement, made testable. Demonstrates: set_budget() as a hard cap, tokens_used()/tokens_remaining(), and a bounded think-loop that STOPS when the budget is exhausted — the verified-termination angle. No network: SOMA_LLM_MOCK=echo. Run: SOMA_LLM_MOCK=echo soma run budget_guard.cell --signal summarize \"a b c d\" Test: SOMA_LLM_MOCK=echo soma test budget_guard.cell", "url": "https://soma-lang.dev/corpus/agents/budget_guard.cell", "repo_path": "examples/corpus/agents/budget_guard.cell", "lines": 52, "features": ["state_machine", "agent", "think", "try"], "cells": ["Summarizer", "BudgetTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/guarded_agent", "domain": "agents", "title": "Agent with preconditions and a memory invariant — refuses bad input", "summary": "Agent with preconditions and a memory invariant — refuses bad input. Demonstrates: `require ... else` guards on a handler, a memory invariant that rejects out-of-range writes, and assert_fails proving the negative paths actually raise. The agent never enters its work state on bad input. Run: SOMA_LLM_MOCK=echo soma run guarded_agent.cell --signal spend \"rent\" 50 Test: SOMA_LLM_MOCK=echo soma test guarded_agent.cell", "url": "https://soma-lang.dev/corpus/agents/guarded_agent.cell", "repo_path": "examples/corpus/agents/guarded_agent.cell", "lines": 59, "features": ["state_machine", "invariant", "agent", "fail"], "cells": ["Treasurer", "TreasurerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/memory_agent", "domain": "agents", "title": "Agent with persistent memory via remember()/recall()", "summary": "Agent with persistent memory via remember()/recall(). Demonstrates: the remember/recall builtins backed by a [persistent] slot, a knowledge-base lifecycle, and recall() returning () for unknown keys (null-checked with ??). Run: SOMA_LLM_MOCK=echo soma run memory_agent.cell --signal learn \"capital\" \"Paris\" Test: SOMA_LLM_MOCK=echo soma test memory_agent.cell", "url": "https://soma-lang.dev/corpus/agents/memory_agent.cell", "repo_path": "examples/corpus/agents/memory_agent.cell", "lines": 61, "features": ["state_machine", "agent", "think", "try"], "cells": ["Librarian", "LibrarianTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/multi_agent_pipeline", "domain": "agents", "title": "Multi-agent content pipeline with verified handoffs", "summary": "Multi-agent content pipeline with verified handoffs. Demonstrates: delegate() across agent cells, each agent owning its own lifecycle machine, and a coordinator whose pipeline state machine proves the chain always terminates. Deterministic tool stubs keep it testable. Run: SOMA_LLM_MOCK=echo soma run multi_agent_pipeline.cell --signal produce \"soma\" Test: SOMA_LLM_MOCK=echo soma test multi_agent_pipeline.cell", "url": "https://soma-lang.dev/corpus/agents/multi_agent_pipeline.cell", "repo_path": "examples/corpus/agents/multi_agent_pipeline.cell", "lines": 70, "features": ["state_machine", "agent", "multi_cell"], "cells": ["Outliner", "Drafter", "Editor", "PipelineTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "27 passed, 5 warnings, 0 failures; temporal 3 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/planner", "domain": "agents", "title": "Planning agent: decompose a goal into ordered subtasks, then execute", "summary": "Planning agent: decompose a goal into ordered subtasks, then execute. Demonstrates: a plan/execute lifecycle, building a task list with range() and push(), and reporting progress. The decomposition is deterministic so the corpus can verify the plan shape without an LLM. Run: SOMA_LLM_MOCK=echo soma run planner.cell --signal plan \"ship feature\" 3 Test: SOMA_LLM_MOCK=echo soma test planner.cell", "url": "https://soma-lang.dev/corpus/agents/planner.cell", "repo_path": "examples/corpus/agents/planner.cell", "lines": 64, "features": ["state_machine", "agent", "fail"], "cells": ["Planner", "PlannerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/react_calculator", "domain": "agents", "title": "A ReAct-style agent whose tools are real, deterministic computations", "summary": "A ReAct-style agent whose tools are real, deterministic computations. Demonstrates: face `tool` declarations that the LLM can call, plus the tool handlers being directly unit-tested (they are ordinary handlers). The think() call dispatches tools automatically; the tools themselves need no network, so the corpus can verify them. Run: SOMA_LLM_MOCK=echo soma run react_calculator.cell --signal solve \"2 and 3\" Test: SOMA_LLM_MOCK=echo soma test react_calculator.cell", "url": "https://soma-lang.dev/corpus/agents/react_calculator.cell", "repo_path": "examples/corpus/agents/react_calculator.cell", "lines": 63, "features": ["state_machine", "agent", "think", "pipeline", "try", "lambda", "tools"], "cells": ["Calc", "CalcTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/sentiment_router", "domain": "agents", "title": "Sentiment-routing agent: classify a message, route by polarity", "summary": "Sentiment-routing agent: classify a message, route by polarity. Demonstrates: a match-based deterministic classifier as a tool, a router that branches the lifecycle on the result, and group_by-style bucketing over a batch. think() is available for the fuzzy path but tools are tested. Run: SOMA_LLM_MOCK=echo soma run sentiment_router.cell --signal route \"I love this\" Test: SOMA_LLM_MOCK=echo soma test sentiment_router.cell", "url": "https://soma-lang.dev/corpus/agents/sentiment_router.cell", "repo_path": "examples/corpus/agents/sentiment_router.cell", "lines": 67, "features": ["state_machine", "agent", "think", "match", "tools"], "cells": ["Router", "RouterTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/tool_dispatcher", "domain": "agents", "title": "Reflective tool-dispatch agent: routes a named action to the right tool", "summary": "Reflective tool-dispatch agent: routes a named action to the right tool. Demonstrates: several `tool` declarations, a manual dispatcher that mirrors what think() does automatically (so the routing logic is unit-testable), and an unknown-action path that lands in failed. Run: SOMA_LLM_MOCK=echo soma run tool_dispatcher.cell --signal act \"reverse\" \"abc\" Test: SOMA_LLM_MOCK=echo soma test tool_dispatcher.cell", "url": "https://soma-lang.dev/corpus/agents/tool_dispatcher.cell", "repo_path": "examples/corpus/agents/tool_dispatcher.cell", "lines": 77, "features": ["state_machine", "agent", "think", "match", "try", "tools"], "cells": ["Toolbox", "ToolboxTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/trace_audit", "domain": "agents", "title": "Self-auditing agent: it inspects its own execution trace", "summary": "Self-auditing agent: it inspects its own execution trace. Demonstrates: trace() returning the structured log of every think()/tool/ approval, clear_trace() resetting it, and using the trace length as an observable the agent reports back. No network needed. Run: SOMA_LLM_MOCK=echo soma run trace_audit.cell --signal investigate \"fraud\" Test: SOMA_LLM_MOCK=echo soma test trace_audit.cell", "url": "https://soma-lang.dev/corpus/agents/trace_audit.cell", "repo_path": "examples/corpus/agents/trace_audit.cell", "lines": 59, "features": ["state_machine", "agent", "think", "try", "tools"], "cells": ["Auditor", "AuditTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/triage_agent", "domain": "agents", "title": "Support-ticket triage agent", "summary": "Support-ticket triage agent. Demonstrates: a verified lifecycle state machine, set_budget cap, tool handlers with deterministic keyword classification (no LLM call — see services/refund_agent.cell for think() + validated JSON output), and a test cell that runs without any network. Run: SOMA_LLM_MOCK=echo soma run triage_agent.cell --signal triage \"login broken\" Test: SOMA_LLM_MOCK=echo soma test triage_agent.cell", "url": "https://soma-lang.dev/corpus/agents/triage_agent.cell", "repo_path": "examples/corpus/agents/triage_agent.cell", "lines": 65, "features": ["state_machine", "agent", "think", "tools"], "cells": ["Triage", "TriageTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/turn_bounded_chat", "domain": "agents", "title": "Turn-bounded conversation agent — proves a chat loop terminates", "summary": "Turn-bounded conversation agent — proves a chat loop terminates. Demonstrates: a fixed max-turns loop (no unbounded `chatting -> chatting` cycle that would break liveness), persistent transcript, and clear_context() between sessions. The bound is the verification-friendly idiom for \"loops\". Run: SOMA_LLM_MOCK=echo soma run turn_bounded_chat.cell --signal converse \"hi\" 2 Test: SOMA_LLM_MOCK=echo soma test turn_bounded_chat.cell", "url": "https://soma-lang.dev/corpus/agents/turn_bounded_chat.cell", "repo_path": "examples/corpus/agents/turn_bounded_chat.cell", "lines": 61, "features": ["state_machine", "agent", "think", "try", "fail"], "cells": ["Chatbot", "ChatTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/typed_lifecycle", "domain": "agents", "title": "Agent lifecycle typed against a sum type — typos become compile errors", "summary": "Agent lifecycle typed against a sum type — typos become compile errors. Demonstrates: `cell type` variants typing a `state X: T { }` machine, transition() taking a VARIANT not a string, get_status() returning the variant name as a string, and an exhaustive match over the status. Run: SOMA_LLM_MOCK=echo soma run typed_lifecycle.cell --signal handle \"refund\" Test: SOMA_LLM_MOCK=echo soma test typed_lifecycle.cell", "url": "https://soma-lang.dev/corpus/agents/typed_lifecycle.cell", "repo_path": "examples/corpus/agents/typed_lifecycle.cell", "lines": 57, "features": ["state_machine", "agent", "sum_type", "match"], "cells": ["TaskStatus", "Worker", "WorkerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "agents/verified_termination", "domain": "agents", "title": "The killer feature: an agent whose termination is PROVEN by soma verify", "summary": "The killer feature: an agent whose termination is PROVEN by soma verify. The lifecycle has a single terminal set {done, failed} reachable from every state, a `* -> failed` catch-all, and the matching soma.toml below drives `soma verify` to prove deadlock-freedom and liveness (eventually done|failed). Check: soma check verified_termination.cell Verify: soma verify verified_termination.cell (uses the soma.toml beside it) Run: SOMA_LLM_MOCK=echo soma run verified_termination.cell --signal solve \"x\" Test: SOMA_LLM_MOCK=echo soma test verified_termination.cell", "url": "https://soma-lang.dev/corpus/agents/verified_termination.cell", "repo_path": "examples/corpus/agents/verified_termination.cell", "lines": 52, "features": ["state_machine", "agent", "think", "try"], "cells": ["Solver", "SolverTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 5 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/agents/soma.toml"}, {"id": "algorithms/bfs", "domain": "algorithms", "title": "Breadth-first search on a small directed graph represented as an adjacency Map<String, List>", "summary": "Breadth-first search on a small directed graph represented as an adjacency Map<String, List>. Demonstrates: a queue (List) of frontier nodes, a visited Map used as a set, level-order distance tracking, and shortest unweighted path length between two nodes.", "url": "https://soma-lang.dev/corpus/algorithms/bfs.cell", "repo_path": "examples/corpus/algorithms/bfs.cell", "lines": 69, "features": [], "cells": ["BFS", "BFSTests"], "usage": ["soma run  examples/corpus/algorithms/bfs.cell hops A F", "soma test examples/corpus/algorithms/bfs.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/binary_search_list", "domain": "algorithms", "title": "Binary search over a sorted List<Int> — returns the index or -1", "summary": "Binary search over a sorted List<Int> — returns the index or -1. Also includes lower_bound (first index >= target), the building block for insertion into a sorted array. Demonstrates: while loop, mid = (lo+hi)/2 with floor, negative-literal sentinel, and known-answer tests.", "url": "https://soma-lang.dev/corpus/algorithms/binary_search_list.cell", "repo_path": "examples/corpus/algorithms/binary_search_list.cell", "lines": 50, "features": [], "cells": ["BinarySearch", "BinarySearchTests"], "usage": ["soma test examples/corpus/algorithms/binary_search_list.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/bubble_sort", "domain": "algorithms", "title": "Bubble sort over a list, with the classic early-exit optimization", "summary": "Bubble sort over a list, with the classic early-exit optimization. Demonstrates: list bracket indexing, in-place swap via a temp, a `swapped` flag to stop once a pass makes no changes, and self-verifying tests.", "url": "https://soma-lang.dev/corpus/algorithms/bubble_sort.cell", "repo_path": "examples/corpus/algorithms/bubble_sort.cell", "lines": 51, "features": [], "cells": ["BubbleSort", "BubbleSortTests"], "usage": ["soma run  examples/corpus/algorithms/bubble_sort.cell sort \"[5,1,4,2,8]\"", "soma test examples/corpus/algorithms/bubble_sort.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/counting_sort", "domain": "algorithms", "title": "Counting sort — a non-comparison O(n + k) sort for small non-negative integers, plus the Sieve of Eratosthenes for the primes up to n", "summary": "Counting sort — a non-comparison O(n + k) sort for small non-negative integers, plus the Sieve of Eratosthenes for the primes up to n. Demonstrates: a count array indexed by value, rebuilding the output by emitting each value count-times, and a boolean sieve over a List.", "url": "https://soma-lang.dev/corpus/algorithms/counting_sort.cell", "repo_path": "examples/corpus/algorithms/counting_sort.cell", "lines": 64, "features": [], "cells": ["CountingSort", "CountingSortTests"], "usage": ["soma run  examples/corpus/algorithms/counting_sort.cell sort \"[4,2,2,8,3,3,1]\"", "soma test examples/corpus/algorithms/counting_sort.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/dfs", "domain": "algorithms", "title": "Depth-first search on a directed graph: preorder traversal and cycle detection via the classic white/grey/black coloring", "summary": "Depth-first search on a directed graph: preorder traversal and cycle detection via the classic white/grey/black coloring. Demonstrates: recursion over an adjacency Map, a visited set, an explicit recursion stack for cycle detection, and accumulating an order list.", "url": "https://soma-lang.dev/corpus/algorithms/dfs.cell", "repo_path": "examples/corpus/algorithms/dfs.cell", "lines": 89, "features": [], "cells": ["DFS", "DFSTests"], "usage": ["soma run  examples/corpus/algorithms/dfs.cell order A", "soma test examples/corpus/algorithms/dfs.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/edit_distance", "domain": "algorithms", "title": "Levenshtein edit distance — classic 2D dynamic programming", "summary": "Levenshtein edit distance — classic 2D dynamic programming. Demonstrates: a DP table as a List of rows (each a List), nested loops over i,j, the insert/delete/substitute min recurrence, and min() over a list.", "url": "https://soma-lang.dev/corpus/algorithms/edit_distance.cell", "repo_path": "examples/corpus/algorithms/edit_distance.cell", "lines": 53, "features": [], "cells": ["EditDistance", "EditDistanceTests"], "usage": ["soma run  examples/corpus/algorithms/edit_distance.cell distance kitten sitting", "soma test examples/corpus/algorithms/edit_distance.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/fibonacci_memo", "domain": "algorithms", "title": "Fibonacci three ways: naive recursion, bottom-up iteration, and a memoized version backed by a [persistent] memory slot", "summary": "Fibonacci three ways: naive recursion, bottom-up iteration, and a memoized version backed by a [persistent] memory slot. Demonstrates: recursion, iterative DP with a rolling pair, and slot.get/.set/.has memoization.", "url": "https://soma-lang.dev/corpus/algorithms/fibonacci_memo.cell", "repo_path": "examples/corpus/algorithms/fibonacci_memo.cell", "lines": 58, "features": [], "cells": ["Fibonacci", "FibonacciTests"], "usage": ["soma run  examples/corpus/algorithms/fibonacci_memo.cell fib_memo 40", "soma test examples/corpus/algorithms/fibonacci_memo.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/gcd_lcm", "domain": "algorithms", "title": "Euclid's algorithm: GCD (iterative + recursive), LCM, the extended Euclid algorithm returning Bezout coefficients, and a coprimality check", "summary": "Euclid's algorithm: GCD (iterative + recursive), LCM, the extended Euclid algorithm returning Bezout coefficients, and a coprimality check. Demonstrates: the modulo recurrence, returning a record of {g, x, y}, and using the builtin gcd() as an oracle in tests.", "url": "https://soma-lang.dev/corpus/algorithms/gcd_lcm.cell", "repo_path": "examples/corpus/algorithms/gcd_lcm.cell", "lines": 81, "features": [], "cells": ["GcdLcm", "GcdLcmTests"], "usage": ["soma run  examples/corpus/algorithms/gcd_lcm.cell gcd_iter 48 36", "soma test examples/corpus/algorithms/gcd_lcm.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/insertion_sort", "domain": "algorithms", "title": "Insertion sort and binary insertion sort on a List<Int>", "summary": "Insertion sort and binary insertion sort on a List<Int>. Demonstrates: the shift-right inner while loop, building a sorted prefix, and a variant that uses binary search to locate the insertion point.", "url": "https://soma-lang.dev/corpus/algorithms/insertion_sort.cell", "repo_path": "examples/corpus/algorithms/insertion_sort.cell", "lines": 53, "features": [], "cells": ["InsertionSort", "InsertionSortTests"], "usage": ["soma run  examples/corpus/algorithms/insertion_sort.cell sort \"[5,2,4,6,1,3]\"", "soma test examples/corpus/algorithms/insertion_sort.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/knapsack", "domain": "algorithms", "title": "0/1 knapsack — maximize value within a weight budget via 2D DP", "summary": "0/1 knapsack — maximize value within a weight budget via 2D DP. Demonstrates: parallel weight/value lists, a (n+1) x (capacity+1) DP table built as nested Lists, the take-or-skip recurrence, and max() of two options.", "url": "https://soma-lang.dev/corpus/algorithms/knapsack.cell", "repo_path": "examples/corpus/algorithms/knapsack.cell", "lines": 55, "features": [], "cells": ["Knapsack", "KnapsackTests"], "usage": ["soma run  examples/corpus/algorithms/knapsack.cell best 7", "soma test examples/corpus/algorithms/knapsack.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/lis", "domain": "algorithms", "title": "Longest increasing subsequence (LIS) — O(n^2) dynamic programming", "summary": "Longest increasing subsequence (LIS) — O(n^2) dynamic programming. Demonstrates: a 1D DP array seeded to 1, the \"best among earlier smaller elements\" inner loop, and max() over the table for the final answer.", "url": "https://soma-lang.dev/corpus/algorithms/lis.cell", "repo_path": "examples/corpus/algorithms/lis.cell", "lines": 41, "features": [], "cells": ["LIS", "LISTests"], "usage": ["soma run  examples/corpus/algorithms/lis.cell length \"[10,9,2,5,3,7,101,18]\"", "soma test examples/corpus/algorithms/lis.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/merge_sort", "domain": "algorithms", "title": "Merge sort on a List<Int> — top-down, purely functional", "summary": "Merge sort on a List<Int> — top-down, purely functional. Demonstrates: splitting a list into halves, recursive sort, and the two-pointer merge of two sorted lists into one. Stable and O(n log n).", "url": "https://soma-lang.dev/corpus/algorithms/merge_sort.cell", "repo_path": "examples/corpus/algorithms/merge_sort.cell", "lines": 64, "features": [], "cells": ["MergeSort", "MergeSortTests"], "usage": ["soma run  examples/corpus/algorithms/merge_sort.cell sort \"[38,27,43,3,9,82,10]\"", "soma test examples/corpus/algorithms/merge_sort.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/min_coins", "domain": "algorithms", "title": "Coin change, minimum number of coins to make an amount (unbounded knapsack)", "summary": "Coin change, minimum number of coins to make an amount (unbounded knapsack). This is the \"fewest coins\" variant — distinct from counting the number of ways. Demonstrates: a 1D DP seeded with a big sentinel, the min-over-coins recurrence, and returning -1 when an amount is unreachable.", "url": "https://soma-lang.dev/corpus/algorithms/min_coins.cell", "repo_path": "examples/corpus/algorithms/min_coins.cell", "lines": 49, "features": [], "cells": ["MinCoins", "MinCoinsTests"], "usage": ["soma run  examples/corpus/algorithms/min_coins.cell fewest 11", "soma test examples/corpus/algorithms/min_coins.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/queue", "domain": "algorithms", "title": "A FIFO queue and a sliding-window maximum over a List", "summary": "A FIFO queue and a sliding-window maximum over a List. Demonstrates: enqueue (push to the back) / dequeue (take from the front), returning a {value, rest} record from dequeue, and a windowed scan.", "url": "https://soma-lang.dev/corpus/algorithms/queue.cell", "repo_path": "examples/corpus/algorithms/queue.cell", "lines": 48, "features": [], "cells": ["Queue", "QueueTests"], "usage": ["soma run  examples/corpus/algorithms/queue.cell window_max \"[1,3,-1,-3,5,3,6,7]\" 3", "soma test examples/corpus/algorithms/queue.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/quicksort", "domain": "algorithms", "title": "Quicksort on a List<Int> — Lomuto partition, recursive", "summary": "Quicksort on a List<Int> — Lomuto partition, recursive. Demonstrates: recursion with list slicing via helper, building result lists with push, and concatenating sublists. Pure / functional style: each call returns a fresh sorted list rather than mutating in place.", "url": "https://soma-lang.dev/corpus/algorithms/quicksort.cell", "repo_path": "examples/corpus/algorithms/quicksort.cell", "lines": 42, "features": [], "cells": ["Quicksort", "QuicksortTests"], "usage": ["soma run  examples/corpus/algorithms/quicksort.cell sort \"[3,6,1,8,2,9,4]\"", "soma test examples/corpus/algorithms/quicksort.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/stack", "domain": "algorithms", "title": "A stack (LIFO) backed by a List, used to check balanced brackets", "summary": "A stack (LIFO) backed by a List, used to check balanced brackets. Demonstrates: list-as-stack with push + index-based pop, a String scan, match over bracket characters, and an early-out on mismatch.", "url": "https://soma-lang.dev/corpus/algorithms/stack.cell", "repo_path": "examples/corpus/algorithms/stack.cell", "lines": 69, "features": ["match"], "cells": ["Brackets", "BracketsTests"], "usage": ["soma run  examples/corpus/algorithms/stack.cell balanced \"{[()]}\"", "soma test examples/corpus/algorithms/stack.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/two_sum", "domain": "algorithms", "title": "Two-sum with a hash set, and the count of distinct pairs summing to a target", "summary": "Two-sum with a hash set, and the count of distinct pairs summing to a target. Demonstrates: a Map used as a seen-set, the complement lookup that turns an O(n^2) scan into O(n), and returning index pairs as a record.", "url": "https://soma-lang.dev/corpus/algorithms/two_sum.cell", "repo_path": "examples/corpus/algorithms/two_sum.cell", "lines": 47, "features": [], "cells": ["TwoSum", "TwoSumTests"], "usage": ["soma run  examples/corpus/algorithms/two_sum.cell find \"[2,7,11,15]\" 9", "soma test examples/corpus/algorithms/two_sum.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "algorithms/word_count", "domain": "algorithms", "title": "Word frequency counting with a Map<String, Int> — the canonical hash-map histogram", "summary": "Word frequency counting with a Map<String, Int> — the canonical hash-map histogram. Demonstrates: map bracket read/write, the ?? null-coalescing guard for first-seen keys, .has / .get / .set on a memory slot, and finding the most frequent word.", "url": "https://soma-lang.dev/corpus/algorithms/word_count.cell", "repo_path": "examples/corpus/algorithms/word_count.cell", "lines": 54, "features": [], "cells": ["WordCount", "WordCountTests"], "usage": ["soma run  examples/corpus/algorithms/word_count.cell count \"the cat sat on the mat the cat\"", "soma test examples/corpus/algorithms/word_count.cell"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "civic/campaign_finance", "domain": "civic", "title": "CAMPAIGN FINANCE — the contribution limit lives in the ledger, not the law", "summary": "CAMPAIGN FINANCE — the contribution limit lives in the ledger, not the law In 2014 Dinesh D'Souza was convicted for funneling money past the federal per-donor limit through straw donors he reimbursed. Straw schemes work because the limit is checked at filing time, months after the money moved. Here the per-donor cap ($2,900, the 2022-cycle federal limit) is a memory invariant: the cumulative-total write for any donor name above the cap is refused at the instant of donation. The reporting lifecycle is one-way — once the committee files, `reported` is terminal: soma verify proves the books cannot be re-opened to massage totals.", "url": "https://soma-lang.dev/corpus/civic/campaign_finance.cell", "repo_path": "examples/corpus/civic/campaign_finance.cell", "lines": 106, "features": ["state_machine", "invariant", "try"], "cells": ["Committee", "CommitteeTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/census", "domain": "civic", "title": "CENSUS — after certification, the count is history, not a database row The decennial census count, once certified and delivered for apportionment (13 U.S.C", "summary": "CENSUS — after certification, the count is history, not a database row The decennial census count, once certified and delivered for apportionment (13 U.S.C. § 141), decides House seats and a decade of federal funding. The 2020 cycle showed why post-hoc edits are radioactive: any quiet change to a certified tract count would shift money and seats with no audit trail. Here certification is a terminal state — soma verify proves no transition leaves it — so amendment handlers go dead at that instant, and the count itself refuses impossible values (a negative population cannot be written, whatever a buggy import believes).", "url": "https://soma-lang.dev/corpus/civic/census.cell", "repo_path": "examples/corpus/civic/census.cell", "lines": 106, "features": ["state_machine", "invariant", "try"], "cells": ["Census", "CensusTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/disaster_aid", "domain": "civic", "title": "DISASTER AID — one emergency grant per household, however many times asked", "summary": "DISASTER AID — one emergency grant per household, however many times asked After Katrina, GAO estimated roughly $1 billion of FEMA individual assistance was improper — much of it duplicate registrations: the same household applying through different names, addresses, or call centers, each application paid because the dedup ran AFTER the checks went out. Here the duplicate is unrepresentable: a household's grant count is a memory invariant capped at 1, so the second disbursement is refused at the write, whichever intake channel it arrived through. The aid program also has a one-way lifecycle — once the program is audited, soma verify proves it never re-opens for \"supplemental\" off-book payments.", "url": "https://soma-lang.dev/corpus/civic/disaster_aid.cell", "repo_path": "examples/corpus/civic/disaster_aid.cell", "lines": 116, "features": ["state_machine", "invariant", "try"], "cells": ["DisasterAid", "DisasterAidTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/election_audit", "domain": "civic", "title": "ELECTION AUDIT — a risk-limiting audit that cannot count a ballot twice", "summary": "ELECTION AUDIT — a risk-limiting audit that cannot count a ballot twice Colorado pioneered statewide risk-limiting audits in 2017: pull a random sample of paper ballots, compare to the machine count, escalate to a full hand recount if the sample disagrees. The integrity of the method dies if the same favorable ballot can be inspected twice (padding agreement) or if a \"confirmed\" audit can be quietly reopened and re-run until it confirms. Both are structural here: each ballot's inspection count is capped at 1 by a memory invariant, escalation to full recount is a real transition the sample-mismatch forces, and `confirmed` is terminal — soma verify proves there is no second bite at the audit.", "url": "https://soma-lang.dev/corpus/civic/election_audit.cell", "repo_path": "examples/corpus/civic/election_audit.cell", "lines": 117, "features": ["state_machine", "invariant", "try"], "cells": ["RiskLimitingAudit", "AuditTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/foia", "domain": "civic", "title": "FOIA — the statutory clock cannot be silently ignored 5 U.S.C", "summary": "FOIA — the statutory clock cannot be silently ignored 5 U.S.C. § 552 gives an agency 20 working days to answer a FOIA request. In practice requests sit for years — agencies just keep them \"processing\" and courts call the silence a constructive denial (journalists sued the FBI over requests pending for a decade). The dodge works because nothing FORCES the escalation. Here the day counter has a hard ceiling: day 21 cannot be written for a request still in processing — the refused write trips the escalation transition instead. Overdue requests land on the commissioner's desk structurally, and `fulfilled` is terminal: an answered request cannot be quietly re-opened to dodge reporting.", "url": "https://soma-lang.dev/corpus/civic/foia.cell", "repo_path": "examples/corpus/civic/foia.cell", "lines": 99, "features": ["state_machine", "invariant", "try"], "cells": ["Foia", "FoiaTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/grants", "domain": "civic", "title": "GRANTS — budget conservation: the fund cannot award money it does not have", "summary": "GRANTS — budget conservation: the fund cannot award money it does not have COVID-era relief programs paid out past their appropriations because the \"remaining budget\" lived in a spreadsheet beside the disbursement system — GAO flagged billions in over- and duplicate disbursements. The bug class is always the same: the balance check and the payment are two systems. Here they are one write: an award debits the fund slot, and a negative balance is unrepresentable — the memory refuses the overdraft. Conservation (awards + remaining == appropriation) holds by construction, and a closed fund is terminal: soma verify proves no path re-opens it.", "url": "https://soma-lang.dev/corpus/civic/grants.cell", "repo_path": "examples/corpus/civic/grants.cell", "lines": 107, "features": ["state_machine", "invariant", "try"], "cells": ["GrantFund", "GrantFundTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/jury", "domain": "civic", "title": "JURY — strikes are counted by the bench, not by the honor system", "summary": "JURY — strikes are counted by the bench, not by the honor system Curtis Flowers was tried six times; the prosecutor's pattern of striking Black jurors finally reached the Supreme Court (Flowers v. Mississippi, 2019). Peremptory strikes are abusable partly because nothing mechanical stops a side from burning more than its allotment — the count lives in a clerk's margin notes. Here 28 U.S.C. § 1870's three peremptory challenges per side is a memory invariant: the fourth strike is refused at the write. A juror can be seated at most once, and a sworn panel is terminal — soma verify proves no one reshuffles the box after jeopardy attaches.", "url": "https://soma-lang.dev/corpus/civic/jury.cell", "repo_path": "examples/corpus/civic/jury.cell", "lines": 118, "features": ["state_machine", "invariant", "try"], "cells": ["JurySelection", "JuryTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/land_registry", "domain": "civic", "title": "LAND REGISTRY — a parcel cannot be sold to two buyers at once", "summary": "LAND REGISTRY — a parcel cannot be sold to two buyers at once Deed-theft rings in Brooklyn and Detroit ran the same con for years: file a sale of the same house to two different buyers in the gap before the recorder's index catches up, collect both down payments, vanish. The con needs a registry that will hold two open sales on one parcel. This one will not: open escrows per parcel is a memory invariant capped at 1 — the second contract is refused at the write. Sales also only move title when the seller IS the recorded owner, and an escheated parcel (abandoned to the state) is terminal: soma verify proves it never re-enters commerce.", "url": "https://soma-lang.dev/corpus/civic/land_registry.cell", "repo_path": "examples/corpus/civic/land_registry.cell", "lines": 110, "features": ["state_machine", "invariant", "try"], "cells": ["LandRegistry", "RegistryTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/lottery", "domain": "civic", "title": "LOTTERY — committed entries, a published seed, and a draw that closes forever", "summary": "LOTTERY — committed entries, a published seed, and a draw that closes forever Public lotteries get rigged in two ways: officials slip entries in after seeing the pool (charter-school placement scandals), or they quietly \"re-draw\" until a favored name comes up — the 2017 HUD housing-voucher re-draws drew exactly this complaint. Both attacks die structurally here: an applicant's entry count cannot exceed 1 (memory wall), entries lock BEFORE the draw, the winner is a pure function of the locked pool and a pre-published seed, and `drawn` is a terminal state soma verify proves has no exit — there is no second draw.", "url": "https://soma-lang.dev/corpus/civic/lottery.cell", "repo_path": "examples/corpus/civic/lottery.cell", "lines": 96, "features": ["state_machine", "invariant", "try"], "cells": ["HousingLottery", "LotteryTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/permit", "domain": "civic", "title": "PERMIT — a building permit that cannot skip a review", "summary": "PERMIT — a building permit that cannot skip a review New York's self-certification program let architects stamp their own permits \"to speed things up\" — DOB audits later found buildings approved with zoning and structural reviews simply skipped, and the city spent a decade revoking permits for occupied buildings. The skip is possible when \"reviewed\" is a checkbox. Here the approval chain is the state machine itself: `issued` is only reachable THROUGH zoning, structural, and fire review, soma verify proves it, and `denied` and `issued` are terminal. The fee ledger is a second wall: a permit cannot be charged twice.", "url": "https://soma-lang.dev/corpus/civic/permit.cell", "repo_path": "examples/corpus/civic/permit.cell", "lines": 118, "features": ["state_machine", "invariant", "try"], "cells": ["BuildingPermit", "PermitTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/petition", "domain": "civic", "title": "PETITION — one signature per citizen, a wall in memory, not a clerk's eye", "summary": "PETITION — one signature per citizen, a wall in memory, not a clerk's eye In 2022 five Michigan governor candidates were struck from the ballot after an estimated 68,000 forged or duplicate petition lines; in 2004 the Nader petition in Pennsylvania collapsed the same way. Paid circulators duplicate names because the dedup is a spreadsheet applied weeks later. Here it is structural: a citizen's line count CANNOT exceed 1 — the memory refuses the write — and the clerk's certify/reject ruling is a terminal state that", "url": "https://soma-lang.dev/corpus/civic/petition.cell", "repo_path": "examples/corpus/civic/petition.cell", "lines": 100, "features": ["state_machine", "invariant", "try"], "cells": ["Petition", "PetitionTests"], "usage": ["soma verify proves has no exit."], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/procurement", "domain": "civic", "title": "PROCUREMENT — sealed bids stay sealed, and the unsealing ends the auction", "summary": "PROCUREMENT — sealed bids stay sealed, and the unsealing ends the auction Classic bid-rigging (a DOJ antitrust staple): a procurement officer leaks the standing low bid to a favored vendor, who then \"submits\" a bid one dollar under it — possible because the system can read bids before close and accept bids after. Both capabilities are removed here, structurally: bid amounts are unreadable until the tender leaves `accepting`, the unsealing transition is the same event that closes submissions forever, and one bid per vendor is a memory invariant — there is no \"revised bid\" after a peek. `awarded` is terminal: the contract cannot be quietly re-tendered for a do-over.", "url": "https://soma-lang.dev/corpus/civic/procurement.cell", "repo_path": "examples/corpus/civic/procurement.cell", "lines": 112, "features": ["state_machine", "invariant", "try"], "cells": ["SealedTender", "TenderTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/sunshine", "domain": "civic", "title": "SUNSHINE — a council cannot vote on what the public never got to discuss", "summary": "SUNSHINE — a council cannot vote on what the public never got to discuss California's Brown Act and its fifty state cousins exist because councils kept adopting ordinances at 11pm on items never noticed on any agenda — courts void such votes, but only years later, after the garage is built. Here the sunshine sequence IS the state machine: `adopted` is reachable only through public notice and an open comment hearing, and soma verify proves it. Each councilmember votes at most once (memory wall), adoption requires a majority of the five-member body, and an adopted ordinance is terminal — no midnight amendment un-adopts it off the record.", "url": "https://soma-lang.dev/corpus/civic/sunshine.cell", "repo_path": "examples/corpus/civic/sunshine.cell", "lines": 135, "features": ["state_machine", "invariant", "try"], "cells": ["Ordinance", "SunshineTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "civic/vital_records", "domain": "civic", "title": "VITAL RECORDS — a person dies at most once, and benefits know it instantly", "summary": "VITAL RECORDS — a person dies at most once, and benefits know it instantly SSA's Inspector General found tens of millions paid to beneficiaries who were dead — and, in the mirror failure, thousands of LIVING people marked dead in the Death Master File (sometimes twice, by different counties), freezing their bank accounts. Both failures come from death being a row any clerk can insert again. Here a person's death count is a memory invariant capped at 1: the second certificate is refused at the write. A registered certificate is terminal — soma verify proves no resurrection edit — and the benefits handler refuses payment the moment the count is 1.", "url": "https://soma-lang.dev/corpus/civic/vital_records.cell", "repo_path": "examples/corpus/civic/vital_records.cell", "lines": 107, "features": ["state_machine", "invariant", "try"], "cells": ["VitalRecords", "VitalRecordsTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "data/ab_test", "domain": "data", "title": "A/B test rollup: per-variant conversions and lift over control", "summary": "A/B test rollup: per-variant conversions and lift over control. Demonstrates filtering a List<Map> by group, count over a predicate lambda, and computing a derived percentage with integer-aware floor division.", "url": "https://soma-lang.dev/corpus/data/ab_test.cell", "repo_path": "examples/corpus/data/ab_test.cell", "lines": 60, "features": ["pipeline", "lambda"], "cells": ["AbTest", "AbTestTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/basket_analysis", "domain": "data", "title": "Market-basket analysis: transactions of (order, product) lines", "summary": "Market-basket analysis: transactions of (order, product) lines. Compute product popularity, basket sizes per order, and the average order value. Demonstrates group_by to size baskets, agg for revenue, and count_by.", "url": "https://soma-lang.dev/corpus/data/basket_analysis.cell", "repo_path": "examples/corpus/data/basket_analysis.cell", "lines": 61, "features": ["pipeline"], "cells": ["Basket", "BasketTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/cohort_retention", "domain": "data", "title": "Cohort analysis: bucket users by signup month, then measure how many were still active in a later month", "summary": "Cohort analysis: bucket users by signup month, then measure how many were still active in a later month. Demonstrates inner_join across two tables, group_by + agg, and computing a derived retention-rate column with map().", "url": "https://soma-lang.dev/corpus/data/cohort_retention.cell", "repo_path": "examples/corpus/data/cohort_retention.cell", "lines": 59, "features": ["pipeline", "lambda"], "cells": ["Cohort", "CohortTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/csv_transform", "domain": "data", "title": "CSV-shaped transform: clean -> derive -> project", "summary": "CSV-shaped transform: clean -> derive -> project. Each row is a Map as if parsed from a CSV header. Demonstrates a block-lambda map(...) that derives new columns, filter for valid rows, and select to project the output shape.", "url": "https://soma-lang.dev/corpus/data/csv_transform.cell", "repo_path": "examples/corpus/data/csv_transform.cell", "lines": 51, "features": ["pipeline", "lambda"], "cells": ["CsvTransform", "CsvTransformTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/dedup_events", "domain": "data", "title": "Deduplication of an event stream with distinct()", "summary": "Deduplication of an event stream with distinct(). Events arrive with duplicate IDs; we collapse to unique rows, count unique users, and show distinct(field) for value-level dedup. Classic \"exactly-once\" cleanup.", "url": "https://soma-lang.dev/corpus/data/dedup_events.cell", "repo_path": "examples/corpus/data/dedup_events.cell", "lines": 52, "features": ["pipeline"], "cells": ["DedupEvents", "DedupEventsTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/expense_tracker", "domain": "data", "title": "Expense report over a List<Map> of line items", "summary": "Expense report over a List<Map> of line items. A normalize step tags each row as fixed vs variable, then aggregates spend per category and per type. Demonstrates a block-lambda classifier, agg, sum_by, and max_by together.", "url": "https://soma-lang.dev/corpus/data/expense_tracker.cell", "repo_path": "examples/corpus/data/expense_tracker.cell", "lines": 62, "features": ["pipeline", "lambda"], "cells": ["ExpenseReport", "ExpenseReportTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/funnel", "domain": "data", "title": "Conversion funnel: count distinct users reaching each stage, then compute step-to-step conversion rates", "summary": "Conversion funnel: count distinct users reaching each stage, then compute step-to-step conversion rates. Demonstrates count over a lambda, distinct per stage, and building a derived report list with map().", "url": "https://soma-lang.dev/corpus/data/funnel.cell", "repo_path": "examples/corpus/data/funnel.cell", "lines": 59, "features": ["pipeline"], "cells": ["Funnel", "FunnelTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/group_reduce", "domain": "data", "title": "group_by returns a Map<String, List>; iterate its entries to compute a custom reduction the built-in agg doesn't cover (here: weighted average)", "summary": "group_by returns a Map<String, List>; iterate its entries to compute a custom reduction the built-in agg doesn't cover (here: weighted average). Demonstrates group_by + manual fold with reduce over each bucket.", "url": "https://soma-lang.dev/corpus/data/group_reduce.cell", "repo_path": "examples/corpus/data/group_reduce.cell", "lines": 58, "features": ["pipeline", "lambda"], "cells": ["GroupReduce", "GroupReduceTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/inner_join_orders", "domain": "data", "title": "Relational inner_join: enrich order rows with customer details, then roll up spend per customer tier", "summary": "Relational inner_join: enrich order rows with customer details, then roll up spend per customer tier. Demonstrates inner_join on a shared key, select to project columns, and agg over the joined result.", "url": "https://soma-lang.dev/corpus/data/inner_join_orders.cell", "repo_path": "examples/corpus/data/inner_join_orders.cell", "lines": 57, "features": ["pipeline", "match"], "cells": ["OrderJoin", "OrderJoinTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/leaderboard", "domain": "data", "title": "Game leaderboard: rank players by score, award medals, compute gaps", "summary": "Game leaderboard: rank players by score, award medals, compute gaps. Demonstrates sort_by(\"score\",\"desc\") -> top, pluck, max_by/min_by, and per-row derived fields via map(... with ...). Records built with map().", "url": "https://soma-lang.dev/corpus/data/leaderboard.cell", "repo_path": "examples/corpus/data/leaderboard.cell", "lines": 60, "features": ["pipeline"], "cells": ["Leaderboard", "LeaderboardTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/left_join_inventory", "domain": "data", "title": "left_join keeps every left row even when the right side has no match", "summary": "left_join keeps every left row even when the right side has no match. Products joined to a sparse stock table; unmatched products keep their fields but gain no stock columns. Demonstrates the ?? guard for missing data.", "url": "https://soma-lang.dev/corpus/data/left_join_inventory.cell", "repo_path": "examples/corpus/data/left_join_inventory.cell", "lines": 54, "features": ["pipeline", "lambda"], "cells": ["Inventory", "InventoryTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/log_analysis", "domain": "data", "title": "Web access log analysis over List<Map> entries", "summary": "Web access log analysis over List<Map> entries. Demonstrates filter_by on status ranges, count_by, group_by, agg of latency, distinct paths, and top offenders. Classic log-crunching shape.", "url": "https://soma-lang.dev/corpus/data/log_analysis.cell", "repo_path": "examples/corpus/data/log_analysis.cell", "lines": 59, "features": ["pipeline"], "cells": ["LogAnalysis", "LogAnalysisTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/record_pipeline", "domain": "data", "title": "Pipeline over typed Record literals (Name { field: v }) instead of map()", "summary": "Pipeline over typed Record literals (Name { field: v }) instead of map(). Records carry a _type tag and support dot-mutation. Demonstrates that the data builtins (filter_by, sort_by, agg, pluck) work on records too.", "url": "https://soma-lang.dev/corpus/data/record_pipeline.cell", "repo_path": "examples/corpus/data/record_pipeline.cell", "lines": 46, "features": ["pipeline"], "cells": ["RecordPipeline", "RecordPipelineTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/sales_report", "domain": "data", "title": "Sales report: a List<Map> of orders rolled up by region and category", "summary": "Sales report: a List<Map> of orders rolled up by region and category. Demonstrates filter_by -> agg (group + sum/avg) -> sort_by, plus sum_by and pluck for headline numbers. Self-verifying via a test cell.", "url": "https://soma-lang.dev/corpus/data/sales_report.cell", "repo_path": "examples/corpus/data/sales_report.cell", "lines": 54, "features": ["pipeline"], "cells": ["SalesReport", "SalesReportTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/stream_ingest", "domain": "data", "title": "Streaming ingest pipeline: push records into an ephemeral buffer slot, then aggregate the buffer in the same handler", "summary": "Streaming ingest pipeline: push records into an ephemeral buffer slot, then aggregate the buffer in the same handler. Demonstrates a List slot, slot.push, reading the buffer back with slot.all, and piping it through agg + sort_by.", "url": "https://soma-lang.dev/corpus/data/stream_ingest.cell", "repo_path": "examples/corpus/data/stream_ingest.cell", "lines": 55, "features": ["pipeline"], "cells": ["StreamIngest", "StreamIngestTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/survey_scores", "domain": "data", "title": "Survey scoring: normalize raw responses, roll up per question, and flag low-confidence questions", "summary": "Survey scoring: normalize raw responses, roll up per question, and flag low-confidence questions. Demonstrates avg_by, agg with min/max, a derived spread column, and assert_fails on an out-of-bounds index (negative path).", "url": "https://soma-lang.dev/corpus/data/survey_scores.cell", "repo_path": "examples/corpus/data/survey_scores.cell", "lines": 50, "features": ["pipeline", "lambda"], "cells": ["Survey", "SurveyTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "data/topn_movies", "domain": "data", "title": "Top-N and bottom-N reporting over a movie ratings table", "summary": "Top-N and bottom-N reporting over a movie ratings table. Demonstrates top/bottom after sort_by, select for projection, avg_by for a summary stat, and filter_by chaining to build a \"critically acclaimed\" list.", "url": "https://soma-lang.dev/corpus/data/topn_movies.cell", "repo_path": "examples/corpus/data/topn_movies.cell", "lines": 59, "features": ["pipeline"], "cells": ["MovieCharts", "MovieChartsTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "devops/backup_retention", "domain": "devops", "title": "BACKUP RETENTION — the floor you cannot prune through", "summary": "BACKUP RETENTION — the floor you cannot prune through On January 31, 2017, a GitLab engineer cleaning up replication lag ran `rm -rf` on what turned out to be the PRIMARY database directory. That was survivable — until all five backup mechanisms turned out to be broken: pg_dump silently producing empty files, S3 uploads failing, snapshots disabled. Six hours of production data were gone forever. Two structural fixes here. First, a backup is only trusted after a restore drill: the lifecycle forces created -> verifying -> verified, and a backup that fails its drill lands in `corrupt`, a TERMINAL state that can never be counted or restored from. Second, the count of verified copies lives behind a memory invariant with a floor of 3: the prune that would leave you with two copies is refused by the MEMORY, not by a retention script somebody edits at 2 a.m.", "url": "https://soma-lang.dev/corpus/devops/backup_retention.cell", "repo_path": "examples/corpus/devops/backup_retention.cell", "lines": 102, "features": ["state_machine", "invariant", "try"], "cells": ["BackupVault", "RetentionTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/blue_green_cutover", "domain": "devops", "title": "BLUE/GREEN CUTOVER — there is no state where nobody serves traffic", "summary": "BLUE/GREEN CUTOVER — there is no state where nobody serves traffic Blue/green deployment's nightmare is the gap: blue is drained, green isn't ready, and for ninety seconds production serves nothing. It is the load-balancer cousin of the airlock problem — two doors that must never both be shut. Salesforce's May 2021 outage had this shape: a DNS change rolled out in a way that briefly left no servers answering, and the tooling needed those very servers to roll back. In this controller the gap is not a state. Every state names exactly which pool is live: blue_live, shifting_to_green (BOTH serve), green_live, shifting_to_blue (BOTH serve). A \"both dark\" state does not exist in the machine, and `soma verify` proves the reachable set is exactly these four. The traffic split is invariant-walled to 0..100 percent, so no weight calculation can send 130% or -30% of traffic anywhere.", "url": "https://soma-lang.dev/corpus/devops/blue_green_cutover.cell", "repo_path": "examples/corpus/devops/blue_green_cutover.cell", "lines": 114, "features": ["state_machine", "invariant", "try"], "cells": ["BlueGreen", "CutoverTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 7 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/cert_rotation", "domain": "devops", "title": "CERT ROTATION — expiry is an escalation ladder, not a surprise", "summary": "CERT ROTATION — expiry is an escalation ladder, not a surprise On December 6, 2018, an expired certificate inside Ericsson's SGSN software took mobile data down for 32 million O2 users in the UK and millions more on SoftBank in Japan. In February 2020, Microsoft Teams went down worldwide because an auth certificate simply lapsed. Nobody \"decided\" to let them expire — the deadline just never escalated. This controller makes expiry a one-way ladder the verifier checks: valid -> renewal_due -> critical -> expired, with rotation available at every rung BEFORE the fall. Both endings are TERMINAL — an expired cert can never quietly become valid again, and a superseded cert is retired for good. The lifetime ledger enforces the CA/Browser-forum ceiling: no handler can mint a certificate longer than 398 days.", "url": "https://soma-lang.dev/corpus/devops/cert_rotation.cell", "repo_path": "examples/corpus/devops/cert_rotation.cell", "lines": 108, "features": ["state_machine", "invariant", "try"], "cells": ["CertManager", "CertTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/db_migration", "domain": "devops", "title": "DB MIGRATION — applied migrations are immutable history", "summary": "DB MIGRATION — applied migrations are immutable history Every schema-drift horror story starts the same way: someone edits a migration that already ran in production. Staging replays the edited file, prod keeps the old shape, and three weeks later a column that \"must exist\" doesn't. Flyway and Liquibase bolt on checksum errors; here immutability is the machine itself: `applied` is a TERMINAL state `soma verify` proves you cannot leave. Undoing means writing a NEW down-migration, never rewriting the past. The second wall is the migrator lock — the GitLab-style disaster of two operators running migrations concurrently is refused by a memory invariant that admits at most one lock holder.", "url": "https://soma-lang.dev/corpus/devops/db_migration.cell", "repo_path": "examples/corpus/devops/db_migration.cell", "lines": 104, "features": ["state_machine", "invariant", "try"], "cells": ["Migrator", "MigrationTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/deploy_canary", "domain": "devops", "title": "DEPLOY CANARY — the staged rollout you cannot skip On July 19, 2024, CrowdStrike pushed a content update to every Windows sensor on Earth at once", "summary": "DEPLOY CANARY — the staged rollout you cannot skip On July 19, 2024, CrowdStrike pushed a content update to every Windows sensor on Earth at once. No canary ring, no staged expansion — 8.5 million machines blue-screened, grounding airlines and closing hospitals. The fix that day would have been boring: ship to 1% first. Here \"ship to 1% first\" is not a policy document. The release machine has NO edge from `built` to `expanding` or `complete` — global blast radius without a canary is unrepresentable, and `soma verify` proves it. A rolled-back release is TERMINAL: you cut a new build, you never re-push the one that burned. The canary slice itself is walled by a memory invariant: a \"canary\" taking more than 5% of traffic is rejected at the write.", "url": "https://soma-lang.dev/corpus/devops/deploy_canary.cell", "repo_path": "examples/corpus/devops/deploy_canary.cell", "lines": 102, "features": ["state_machine", "invariant", "try"], "cells": ["DeployPipeline", "PipelineTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/dns_change_control", "domain": "devops", "title": "DNS CHANGE CONTROL — no record goes live without passing validation", "summary": "DNS CHANGE CONTROL — no record goes live without passing validation On October 4, 2021, a routine maintenance command at Facebook withdrew every BGP route to its DNS servers. An audit tool existed precisely to block commands like that — but a bug let the command bypass it. With DNS gone, facebook.com vanished for six hours, internal tools died, and engineers couldn't badge into the datacenter to fix it. The lesson is not \"audit harder\", it is: the bypass must not be a path. In this change pipeline `live` is only reachable through `validated` and `staged` — there is no drafted -> live edge for a buggy tool to take, and `soma verify` proves it. A reverted change is TERMINAL: you draft a new change with a new review, you never re-push the one that broke the internet. TTLs sit behind a memory invariant so no change can ship a record the resolvers would cache for a year.", "url": "https://soma-lang.dev/corpus/devops/dns_change_control.cell", "repo_path": "examples/corpus/devops/dns_change_control.cell", "lines": 102, "features": ["state_machine", "invariant", "try"], "cells": ["DnsChanges", "ChangeGateTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/feature_flag_kill_switch", "domain": "devops", "title": "KILL SWITCH — a dead flag stays dead On August 1, 2012, Knight Capital repurposed an old feature flag — \"Power Peg\", dead code from 2003 — for a new router", "summary": "KILL SWITCH — a dead flag stays dead On August 1, 2012, Knight Capital repurposed an old feature flag — \"Power Peg\", dead code from 2003 — for a new router. One of eight servers still ran the old code. When the recycled flag flipped on, the zombie code woke up and bought $7 billion of stock in 45 minutes. Knight lost $440M and the company. The root cause was not the bug; it was that a KILLED flag could come back to life. Here `killed` is a TERMINAL state — `soma verify` proves no path out. Re-enabling a killed feature means minting a NEW flag through a new review, never resurrecting the old one. The rollout percentage rides a memory invariant so no handler can write an out-of-range exposure.", "url": "https://soma-lang.dev/corpus/devops/feature_flag_kill_switch.cell", "repo_path": "examples/corpus/devops/feature_flag_kill_switch.cell", "lines": 105, "features": ["state_machine", "invariant", "try"], "cells": ["FeatureFlags", "KillSwitchTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/fleet_sync_activation", "domain": "devops", "title": "FLEET SYNC — no activation until every node runs the same code", "summary": "FLEET SYNC — no activation until every node runs the same code The other half of the Knight Capital disaster: a technician deployed the new router to only 7 of 8 servers. The fleet was split-brained — one machine interpreted the activation flag as 2003-era \"Power Peg\" logic. Activating a half-deployed fleet is what turned a deploy slip into $440M of runaway orders. This controller makes the split-brain activation unrepresentable. `activated` is only reachable from `synced`, and the handler that enters `synced` requires the pending-node ledger to read zero. The ledger itself is invariant-walled: it can never go negative (no double-counting a node) and never exceed the fleet size.", "url": "https://soma-lang.dev/corpus/devops/fleet_sync_activation.cell", "repo_path": "examples/corpus/devops/fleet_sync_activation.cell", "lines": 100, "features": ["state_machine", "invariant", "try"], "cells": ["FleetSync", "FleetTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/image_promotion", "domain": "devops", "title": "IMAGE PROMOTION — nothing unscanned, unsigned, or vulnerable ships", "summary": "IMAGE PROMOTION — nothing unscanned, unsigned, or vulnerable ships The SolarWinds breach (disclosed December 2020) worked because the build pipeline itself was the attack surface: malicious code was injected during the build, then SIGNED and shipped to ~18,000 organizations as a legitimate update. Defense afterward converged on one idea — provenance gates: an artifact reaches production only by passing every gate, in order, with no side door. This registry encodes the gates as topology: built -> scanned -> signed -> promoted, and `soma verify` proves there is no edge that skips a gate. An image whose scan finds critical CVEs lands in `quarantined` — TERMINAL, because you rebuild from a patched base, you never \"un-quarantine\". The promoted registry's CVE ledger has a memory invariant pinned at zero: recording a critical vulnerability against a production image is a write the memory itself refuses.", "url": "https://soma-lang.dev/corpus/devops/image_promotion.cell", "repo_path": "examples/corpus/devops/image_promotion.cell", "lines": 105, "features": ["state_machine", "invariant", "try"], "cells": ["ImageRegistry", "ProvenanceTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/incident_ladder", "domain": "devops", "title": "INCIDENT LADDER — severity only climbs, and closure needs a postmortem Two ways incident processes rot", "summary": "INCIDENT LADDER — severity only climbs, and closure needs a postmortem Two ways incident processes rot. First, \"sev gaming\": an on-call quietly downgrades a Sev1 to Sev3 so the SLA clock stops and the VP page never fires — the 2013 Target breach unfolded exactly this way, with FireEye alerts dismissed for weeks while card data walked out. Second, closing without learning: the incident is marked resolved, no postmortem happens, and the same outage returns in six months. Both rots are unrepresentable here. Severity is a one-way ladder — there is no de-escalation edge, only mitigation. And `closed` is reachable ONLY through `postmortem_done`: the machine has no edge from mitigated to closed, so \"we'll write it up later\" cannot compile. `soma verify` proves closed is terminal and that every state can still reach it — no incident is ever stuck open forever.", "url": "https://soma-lang.dev/corpus/devops/incident_ladder.cell", "repo_path": "examples/corpus/devops/incident_ladder.cell", "lines": 118, "features": ["state_machine", "invariant", "try"], "cells": ["IncidentDesk", "LadderTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/pager_escalation", "domain": "devops", "title": "PAGER ESCALATION — no page resolves without a human acknowledging it", "summary": "PAGER ESCALATION — no page resolves without a human acknowledging it In the 2013 Target breach, FireEye flagged the malware and fired alerts to the security team — twice. The alerts were reviewed and dismissed without action; 40 million card numbers walked out during the busiest shopping weeks of the year. The killer pattern is the auto-resolve: an alert that nobody acknowledged quietly disappears from the queue, and the system that paged looks healthy again. In this pager, `resolved` is only reachable from `acked` — there is no triggered -> resolved edge for an auto-close to take, and `soma verify` proves it. An unacknowledged page can only ESCALATE: on-call, then secondary, then the manager — a one-way ladder with no edge pointing down. The unanswered-escalation counter is invariant-capped: past three hops the page cannot be re-escalated into the void, it must be acknowledged at the top of the chain.", "url": "https://soma-lang.dev/corpus/devops/pager_escalation.cell", "repo_path": "examples/corpus/devops/pager_escalation.cell", "lines": 110, "features": ["state_machine", "invariant", "try"], "cells": ["Pager", "PagerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/rate_limiter", "domain": "devops", "title": "RATE LIMITER — admission control with a quota the memory enforces", "summary": "RATE LIMITER — admission control with a quota the memory enforces On September 20, 2015, DynamoDB's storage servers all renewed their metadata leases at once after a network blip. The metadata service had no effective admission control; the retry storm starved it, which caused more timeouts, which caused more retries. The brownout took down large parts of us-east-1 for five hours and dragged twenty other AWS services with it. Cascading retry storms are what rate limiters exist to stop — IF the limiter itself cannot be talked out of its quota. This limiter's token bucket lives behind a memory invariant: tokens can never go below zero (no overdraft \"just this once\") and never above the burst ceiling (no refill bug minting infinite capacity). The breaker is a state machine with a one-way path through `shedding` and `recovering` — there is no edge from shedding straight back to closed-and-full-traffic, so the thundering herd cannot re-arrive at once.", "url": "https://soma-lang.dev/corpus/devops/rate_limiter.cell", "repo_path": "examples/corpus/devops/rate_limiter.cell", "lines": 119, "features": ["state_machine", "invariant", "try"], "cells": ["RateLimiter", "LimiterTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/secret_rotation", "domain": "devops", "title": "SECRET ROTATION — a revoked credential never logs in again In 2016, attackers found Uber's AWS keys sitting in a private GitHub repo", "summary": "SECRET ROTATION — a revoked credential never logs in again In 2016, attackers found Uber's AWS keys sitting in a private GitHub repo. The keys were long-lived — never rotated — and unlocked data on 57 million riders and drivers. The pattern repeats everywhere: a credential leaks, someone \"disables\" it in a dashboard, and months later a recovery script or a confused admin re-enables it. Here the credential lifecycle is a machine where `revoked` and `retired` are TERMINAL — `soma verify` proves no handler, script, or 3 a.m. admin can resurrect a dead key. Authentication consults the machine, so a revoked key fails closed. Key age sits behind a memory invariant: a credential older than the 90-day rotation policy cannot even be recorded, which makes \"we forgot to rotate\" a write error.", "url": "https://soma-lang.dev/corpus/devops/secret_rotation.cell", "repo_path": "examples/corpus/devops/secret_rotation.cell", "lines": 115, "features": ["state_machine", "invariant", "try"], "cells": ["SecretVault", "VaultTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "devops/state_lock", "domain": "devops", "title": "STATE LOCK — two concurrent applies can never both hold the lock", "summary": "STATE LOCK — two concurrent applies can never both hold the lock Terraform's docs put it bluntly: two `apply` runs against the same state file at once will corrupt it. Teams learn this the hard way — CI kicks off a plan while an engineer applies from a laptop, the state JSON is half-written by both, and suddenly Terraform wants to destroy and recreate half of production. HashiCorp added state locking for exactly this; here the lock's mutual exclusion is a proof, not a DynamoDB conditional write you hope is configured. The lock is a state machine: `unlocked -> held -> unlocked`, with a `stale` branch for the crashed-runner case — force-unlock exists, but ONLY from `stale`, never as a shortcut around a live holder. The holder-count ledger is invariant-walled at 0..1: a second holder is a write the memory refuses, independent of the machine.", "url": "https://soma-lang.dev/corpus/devops/state_lock.cell", "repo_path": "examples/corpus/devops/state_lock.cell", "lines": 114, "features": ["state_machine", "invariant", "try"], "cells": ["StateLock", "MutexTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/anti_islanding", "domain": "energy", "title": "ANTI-ISLANDING — a solar inverter must never energize a \"dead\" line When a feeder breaker opens, every lineworker on that circuit treats the wire as dead", "summary": "ANTI-ISLANDING — a solar inverter must never energize a \"dead\" line When a feeder breaker opens, every lineworker on that circuit treats the wire as dead. But a neighborhood of rooftop solar can keep the islanded segment energized — backfeeding lethal voltage into a line the crew has every reason to believe is isolated. This is why IEEE 1547 mandates that a grid-tied inverter CEASE energizing within 2 seconds of grid loss and stay off until the grid has been stable for a full hold-off window (classically 5 minutes) — not \"until the voltage flickers back\". The lethal shortcut is `ceased -> exporting`: the grid blinks, the inverter jumps straight back to full output while a recloser is mid- sequence or a crew is mid-repair. Below, that transition DOES NOT EXIST. The only exit from `ceased` is `monitoring`, where the hold-off clock restarts. soma verify proves the reachable graph; the export-watts slot is a second wall — output is zeroed on cessation and capped at nameplate.", "url": "https://soma-lang.dev/corpus/energy/anti_islanding.cell", "repo_path": "examples/corpus/energy/anti_islanding.cell", "lines": 107, "features": ["state_machine", "invariant", "try"], "cells": ["Inverter", "IslandTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/battery_soc", "domain": "energy", "title": "BATTERY DISPATCH — the charge window is a wall, not a setpoint", "summary": "BATTERY DISPATCH — the charge window is a wall, not a setpoint April 19, 2019, Surprise, Arizona: a rack at the APS McMicken battery facility went into thermal runaway; when firefighters opened the door the accumulated gases exploded and put four of them in the hospital. Lithium cells driven outside their charge window — overcharged at the top, or dragged below empty by an aggressive arbitrage optimizer — plate lithium, grow dendrites, and eventually burn. Dispatch software optimizes revenue and will happily command one more charging interval at the top of the window unless something refuses. Here the refusal is the memory itself: state-of-charge lives in a slot whose invariant is 0..100. The write that would cross the bound is rejected BY THE SLOT, even if every guard in the handler is deleted. A 20%-per-interval ramp limit rides on top in the handler.", "url": "https://soma-lang.dev/corpus/energy/battery_soc.cell", "repo_path": "examples/corpus/energy/battery_soc.cell", "lines": 83, "features": ["invariant", "try"], "cells": ["Battery", "SocTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "2 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "energy/black_start", "domain": "energy", "title": "BLACK START — you cannot boot a power plant from a dead grid out of order August 14, 2003: the Northeast blackout dropped 61,800 MW and 50 million people", "summary": "BLACK START — you cannot boot a power plant from a dead grid out of order August 14, 2003: the Northeast blackout dropped 61,800 MW and 50 million people. Restoration took days, because a big thermal plant cannot start itself — its boiler feed pumps, fans, and lube-oil systems need tens of megawatts of \"station service\" power that normally comes FROM the grid. In February 2021, winter storm Uri brought ERCOT within minutes of a total collapse that engineers estimated would have taken weeks to black-start. The restoration sequence is rigid for physical reasons: a small self-starting unit (hydro, diesel) cranks first; it feeds the big plant's auxiliaries; only then can the big unit roll; the unit then carries a small stable island; and the island is synchronized to its neighbors LAST. Skip a step and you trip everything back to black. The sequence below is the state machine. Every skip is a transition that does not exist; collapse paths return to `blackout`; and `reconnected` is terminal for the event — the restoration log of a finished black start is history. soma verify proves all of it.", "url": "https://soma-lang.dev/corpus/energy/black_start.cell", "repo_path": "examples/corpus/energy/black_start.cell", "lines": 118, "features": ["state_machine", "invariant", "try"], "cells": ["BlackStart", "BlackStartTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/breaker_reclose", "domain": "energy", "title": "RECLOSER — a trip is permanent until a human walks the line", "summary": "RECLOSER — a trip is permanent until a human walks the line A distribution recloser that trips on a fault will, by default, try to re-energize the line a few seconds later — most faults are a branch brushing a phase and clear themselves. But a conductor lying on the ground is the OTHER kind of fault: every reclose attempt pumps thousands of amps into whatever the wire is touching — a dry field, a car, a person. Reclosing into downed lines has electrocuted bystanders and started wildfires; after 2020, utilities in California fire country (PG&E's \"fast trip\" program) disabled automatic reclosing outright. Here the rule is structural, not procedural: from `tripped` the ONLY exit is `patrolling` — a crew dispatched to walk the span. `closed` is reachable from `tripped` by no path that skips the patrol, and a line the patrol condemns can never be energized again: `condemned` is terminal, and `soma verify` proves it.", "url": "https://soma-lang.dev/corpus/energy/breaker_reclose.cell", "repo_path": "examples/corpus/energy/breaker_reclose.cell", "lines": 94, "features": ["state_machine", "invariant", "try"], "cells": ["Recloser", "RecloseTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/demand_response", "domain": "energy", "title": "DEMAND RESPONSE — no payment before measurement, and settlement is final", "summary": "DEMAND RESPONSE — no payment before measurement, and settlement is final Demand-response programs pay customers for NOT consuming during a grid emergency — which makes the payout an invitation to invent curtailment. In 2013 FERC penalized Rumford Paper Co. for gaming its DR baseline: the mill ran flat-out during the baseline window, then \"curtailed\" to its normal level and collected for megawatts it never actually shed. The money leaks wherever settlement can run before measurement, or run twice. Here the event lifecycle is the control: payout can only be posted from `measured` (verified meter data in hand), `settled` is TERMINAL — no re-settlement, no retroactive sweetener — and a cancelled event is terminal too, payable by no path. soma verify proves both. The payout ledger refuses negative or program-cap-busting amounts at the memory.", "url": "https://soma-lang.dev/corpus/energy/demand_response.cell", "repo_path": "examples/corpus/energy/demand_response.cell", "lines": 124, "features": ["state_machine", "invariant", "try"], "cells": ["DrEvent", "DrTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/ev_charging", "domain": "energy", "title": "EV CHARGING — no current before the handshake, no session past the cap Two real failure modes, one charging post", "summary": "EV CHARGING — no current before the handshake, no session past the cap Two real failure modes, one charging post. 1. Current before negotiation. The J1772/CCS pilot handshake exists so the cable, the car, and the post agree on a current the weakest link can carry. Skip it — a bent pin, a counterfeit adapter — and a 16 A cable carries 48 A until the insulation melts. Garage fires from uncertified EVSE gear are a documented pattern. 2. Charging past the cell limit. GM's 2021 recall of every Chevy Bolt came down to defective cells that became dangerous near full charge; the interim fix was SOFTWARE: cap the session. A cap that lives in an if-statement is a cap a firmware update can delete. Both are structural here: `charging` is reachable ONLY through `authorized` (the handshake state — soma verify proves it), and the session energy ledger refuses any write past 60 kWh at the memory.", "url": "https://soma-lang.dev/corpus/energy/ev_charging.cell", "repo_path": "examples/corpus/energy/ev_charging.cell", "lines": 124, "features": ["state_machine", "invariant", "try"], "cells": ["ChargePost", "ChargeTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/gas_purge", "domain": "energy", "title": "GAS TURBINE LIGHT-OFF — purge before every ignition attempt, no exceptions", "summary": "GAS TURBINE LIGHT-OFF — purge before every ignition attempt, no exceptions February 7, 2010, Middletown, Connecticut: the Kleen Energy power plant, weeks from commissioning, exploded during a natural-gas pipe-cleaning operation. Six workers died. The blast led NFPA 56 to ban flammable-gas blows outright — but the same physics lives inside every gas turbine and HRSG: admit fuel without flame, and the exhaust path fills with a combustible cloud waiting for one spark. That is why NFPA 85 requires a forced-air purge of several full volume changes before EVERY ignition attempt — including the retry after a failed light-off, which is exactly when an impatient operator (or a buggy auto-restart) wants to skip it. Here the purge is unskippable: `firing` is reachable only from `purge_complete`, and the ONLY exit from `failed_light` is back into `purging`. soma verify proves no path admits fuel into an unpurged machine. The purge-volume ledger refuses credit for less than the mandated 5 volume changes.", "url": "https://soma-lang.dev/corpus/energy/gas_purge.cell", "repo_path": "examples/corpus/energy/gas_purge.cell", "lines": 134, "features": ["state_machine", "invariant", "try"], "cells": ["Combustor", "PurgeTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/generator_sync", "domain": "energy", "title": "GENERATOR PARALLELING — sync-check before the breaker, always", "summary": "GENERATOR PARALLELING — sync-check before the breaker, always Closing a generator breaker onto a live grid while the machine is out of phase is one of the most violent things you can do to rotating iron. At 120 degrees out, the instantaneous torque on the shaft is several times rated — enough to twist couplings, crack stator end-windings, and scrap a turbine-generator worth more than the plant's annual revenue. This is why every utility interconnection requires a sync-check relay (ANSI device 25): slip, phase angle, and voltage must all be inside the window BEFORE the close command can reach the breaker. Here the relay is the state machine: `online` is reachable ONLY from `synchronized`. From `at_speed` (machine at rated speed and voltage, breaker open) there is no close path — the transition does not exist, so no operator shortcut, race, or script can close out of phase. when online, and never beyond the 500 MW nameplate.", "url": "https://soma-lang.dev/corpus/energy/generator_sync.cell", "repo_path": "examples/corpus/energy/generator_sync.cell", "lines": 137, "features": ["state_machine", "invariant", "try"], "cells": ["Genset", "SyncTests"], "usage": ["soma verify proves it. The MW slot is the second wall: load only flows"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/load_shedding", "domain": "energy", "title": "LOAD SHEDDING — the transformer's nameplate is a wall, hospitals shed last", "summary": "LOAD SHEDDING — the transformer's nameplate is a wall, hospitals shed last When demand outruns supply, somebody's lights go off — the only question is whose, and whether the choice is made by a priority plan or by a melting transformer. In February 2021, winter storm Uri forced ERCOT to shed 20,000 MW; where rotation plans failed, circuits feeding hospitals and water plants went dark alongside empty offices, and people died of cold. The two properties a shedding controller must keep: 1. The transformer NEVER carries more than nameplate. Here that is a memory invariant — connecting a feeder that would overload the bank is rejected at the write, not by an if-statement upstream. 2. Shedding follows priority: interruptible contracts (3) drop before commercial (2); critical loads (1 — hospitals, water) are never auto-shed. The shed handler structurally cannot pick a priority-1 feeder.", "url": "https://soma-lang.dev/corpus/energy/load_shedding.cell", "repo_path": "examples/corpus/energy/load_shedding.cell", "lines": 112, "features": ["invariant", "try"], "cells": ["Shedder", "ShedTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "6 passed, 2 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "energy/meter_billing", "domain": "energy", "title": "METER BILLING — you are billed exactly what the meter read, once", "summary": "METER BILLING — you are billed exactly what the meter read, once In December 2015 the UK regulator Ofgem fined npower £26 million for billing failures: estimated and duplicated invoices that didn't match what meters had recorded, sent to half a million customers. The root pattern is always the same — billing reads a copy of the meter data that can drift, and nothing structural ties the invoice to the register. Here conservation is by construction. Each billing cycle is a state machine: usage accumulates only while `accumulating`; `locked` snapshots the register; the ONLY write to `billed` copies the metered value at invoice time. You cannot invoice an unlocked register (the transition doesn't exist), cannot invoice twice (invoiced -> invoiced doesn't exist), and a settled cycle is TERMINAL — no retroactive \"adjustment\".", "url": "https://soma-lang.dev/corpus/energy/meter_billing.cell", "repo_path": "examples/corpus/energy/meter_billing.cell", "lines": 115, "features": ["state_machine", "invariant", "match", "try"], "cells": ["Billing", "BillingTests"], "usage": ["soma verify proves the lifecycle; the audit signal pins billed==metered."], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/spillway_gates", "domain": "energy", "title": "SPILLWAY GATES — a dam may never lose its last release path", "summary": "SPILLWAY GATES — a dam may never lose its last release path February 2017, Oroville, California: the tallest dam in the US lost its main spillway to erosion mid-flood, the emergency spillway began to fail within hours of first use, and 188,000 people downstream were evacuated. The lesson generalized by every dam-safety review since: release capacity is life-safety equipment, and maintenance scheduling is where it silently disappears — gate 3 is down for seal replacement, gate 5's hoist motor is out, a contractor asks to isolate gate 7 \"just for the afternoon\", and suddenly the dam cannot pass the inflow it was built for. Two structural walls below. The fleet ledger `gates_avail` carries an invariant floor of ONE: the write that would take the last operable gate out of service is rejected by the memory, whatever the work order says. And each gate's overhaul is a state machine: an overhauled gate returns to service only through `wet_tested` — an untested gate back on the flood roster is a transition that does not exist. soma verify proves it.", "url": "https://soma-lang.dev/corpus/energy/spillway_gates.cell", "repo_path": "examples/corpus/energy/spillway_gates.cell", "lines": 121, "features": ["state_machine", "invariant", "try"], "cells": ["Spillway", "SpillwayTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/spinning_reserve", "domain": "energy", "title": "SPINNING RESERVE — every megawatt you sell must claim real iron", "summary": "SPINNING RESERVE — every megawatt you sell must claim real iron Spinning reserve is capacity a generator is PAID to hold back, ready to inject within minutes when a unit elsewhere trips. The market failure: energy and reserve are sold in separate transactions, so a 500 MW unit can dispatch 450 MW of energy AND sell 100 MW of reserve — 550 MW of promises against 500 MW of iron. During winter storm Uri in February 2021, ERCOT discovered how much of its purchased reserve was paper: units that had sold readiness tripped offline or never ramped, and the shortfall became rolling blackouts in single-digit cold. The fix here is one slot: `claimed` holds energy dispatch PLUS reserve commitments per unit, and its invariant is the nameplate. Both markets write through the same wall, so the double-sell is rejected at the memory — there is no code path on which promises exceed iron.", "url": "https://soma-lang.dev/corpus/energy/spinning_reserve.cell", "repo_path": "examples/corpus/energy/spinning_reserve.cell", "lines": 109, "features": ["invariant", "try"], "cells": ["ReserveDesk", "ReserveTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "5 passed, 2 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "energy/substation_loto", "domain": "energy", "title": "LOCKOUT-TAGOUT — test before touch, and nobody re-energizes over a lock", "summary": "LOCKOUT-TAGOUT — test before touch, and nobody re-energizes over a lock Electrical workers are killed every year by circuits that were \"locked out\": a breaker opened but the bus still live through a backfeed, an induced voltage from the parallel line nobody tested for, or a dispatcher closing remotely while a crew is on the conductors. OSHA's hazardous- energy rules (1910.147 / 1910.269) exist because each of these has a body count. The two rules that do the saving: TEST BEFORE TOUCH — isolation is not proof. You meter every phase before grounds go on. Here, `grounded` is unreachable from `isolated` without passing `proven_dead`; soma verify proves it. ONE LOCK, ONE LIFE — every worker hangs a personal lock; the line cannot be declared clear while ANY lock remains. The lock ledger refuses to go negative (you cannot remove a lock that isn't yours to remove), and re-energizing from `grounded` is not a transition at all.", "url": "https://soma-lang.dev/corpus/energy/substation_loto.cell", "repo_path": "examples/corpus/energy/substation_loto.cell", "lines": 137, "features": ["state_machine", "invariant", "try"], "cells": ["Loto", "LotoTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/transformer_overload", "domain": "energy", "title": "TRANSFORMER EMERGENCY LOADING — overload only with every fan running", "summary": "TRANSFORMER EMERGENCY LOADING — overload only with every fan running A large power transformer dies slowly and then suddenly: every hour spent above its thermal rating cooks the paper insulation (IEEE C57.91 calls it loss-of-life), until one hot afternoon the winding faults and forty tons of mineral oil have an ignition source. Grid operators DO run transformers past nameplate during emergencies — that is what the ONAF cooling stages are for: first fan bank buys you 115%, second bank 125%, but only while the fans are actually spinning. The classic failure is the quiet one: a fan contactor died months ago, the SCADA point was never wired, and the bank takes emergency load with cooling it does not have. Here the cooling stage is a state machine and the loading ceiling is derived FROM the state: `emergency_load` is a state reachable only from `fans_full` — soma verify proves overload cannot be entered with idle fans. The MVA slot's invariant is the absolute thermal wall at 125.", "url": "https://soma-lang.dev/corpus/energy/transformer_overload.cell", "repo_path": "examples/corpus/energy/transformer_overload.cell", "lines": 134, "features": ["state_machine", "invariant", "try"], "cells": ["Transformer", "OverloadTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "energy/wind_overspeed", "domain": "energy", "title": "WIND TURBINE OVERSPEED — after an emergency brake, inspection or nothing", "summary": "WIND TURBINE OVERSPEED — after an emergency brake, inspection or nothing February 22, 2008, Hornslet, Denmark: a 600 kW turbine's brakes failed during a storm and the machine spun until it tore itself apart — blades and nacelle thrown hundreds of meters, the disintegration caught on a video that every wind technician has since been shown. A rotor past its design speed stores energy in exactly the form that kills: blade root fatigue you cannot see from the ground. That is why an overspeed event is never \"reset and resume\". Here the rule is the machine: from `storm_brake` the ONLY exit is `inspection` — there is no path back to `running` that skips a human at the blade roots. A turbine the inspection condemns is `condemned`, terminal, forever; soma verify proves both. The rotor-speed slot is the inner wall: no write can record an rpm past the 25-rpm design limit, so the telemetry layer cannot even pretend an overspeed was normal.", "url": "https://soma-lang.dev/corpus/energy/wind_overspeed.cell", "repo_path": "examples/corpus/energy/wind_overspeed.cell", "lines": 136, "features": ["state_machine", "invariant", "try"], "cells": ["Turbine", "OverspeedTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "15 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/chargeback_window", "domain": "escrow_finance", "title": "CHARGEBACK WINDOW — disputes die at day 120, reversals happen exactly once Card networks give cardholders ~120 days to dispute a charge", "summary": "CHARGEBACK WINDOW — disputes die at day 120, reversals happen exactly once Card networks give cardholders ~120 days to dispute a charge. Two ways processors lose money here: accepting a dispute after the window (the merchant's funds were already swept as final), and reversing the same charge twice when a manual agent and an automated rule both fire. Both are structural below: `finalized` is terminal so a late dispute has no edge to take, and `reversed`/`upheld` are terminal so a second reversal raises. The merchant ledger refuses negative balances.", "url": "https://soma-lang.dev/corpus/escrow_finance/chargeback_window.cell", "repo_path": "examples/corpus/escrow_finance/chargeback_window.cell", "lines": 109, "features": ["state_machine", "invariant"], "cells": ["Chargeback", "ChargebackTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/client_money_segregation", "domain": "escrow_finance", "title": "CLIENT MONEY SEGREGATION — the firm can only ever touch its own excess", "summary": "CLIENT MONEY SEGREGATION — the firm can only ever touch its own excess MF Global, October 2011: as the firm's own liquidity died, roughly $1.6B of SEGREGATED customer funds were wired out to cover house obligations. The rule (CFTC 1.20) was clear; the enforcement was a spreadsheet. The structural version: the seg account tracks an `excess` slot — firm money deposited as a buffer — and EVERY house withdrawal draws ONLY on excess, with `excess >= 0` as the invariant. The wire that dips into customer money is a rejected write, even at 2am on the last day. Client claims are themselves a slot that cannot go negative (no over-withdrawal).", "url": "https://soma-lang.dev/corpus/escrow_finance/client_money_segregation.cell", "repo_path": "examples/corpus/escrow_finance/client_money_segregation.cell", "lines": 100, "features": ["invariant"], "cells": ["SegAccount", "SegTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "3 passed, 3 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "escrow_finance/crowdfund_all_or_nothing", "domain": "escrow_finance", "title": "ALL-OR-NOTHING CROWDFUNDING — miss the goal, every backer gets refunded The all-or-nothing pledge model only works if \"nothing\" is enforced", "summary": "ALL-OR-NOTHING CROWDFUNDING — miss the goal, every backer gets refunded The all-or-nothing pledge model only works if \"nothing\" is enforced. Platforms have been burned both ways: creators paid out on campaigns that quietly missed their goal, and failed campaigns where refunds ran twice (or never). Here the payout edge exists ONLY from `succeeded`, a campaign can reach `succeeded` only via close_campaign checking pledged >= goal, and the failed branch must drain the pledge pool to zero through refunds — the pool slot refuses negative writes, so a double refund of the same backer raises in memory.", "url": "https://soma-lang.dev/corpus/escrow_finance/crowdfund_all_or_nothing.cell", "repo_path": "examples/corpus/escrow_finance/crowdfund_all_or_nothing.cell", "lines": 120, "features": ["state_machine", "invariant"], "cells": ["Crowdfund", "CrowdfundTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "15 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/dividend_pool", "domain": "escrow_finance", "title": "DIVIDEND DISTRIBUTION — payments can never exceed the declared pool", "summary": "DIVIDEND DISTRIBUTION — payments can never exceed the declared pool When a board declares a dividend, that number is legally binding — and transfer agents have paid out MORE than the declaration through duplicate shareholder records or a re-run batch job (the same disease as the 2021 \"accidental\" duplicate ACH dividend runs brokers had to claw back). Structure: the declared pool is a slot every payment decrements, with `pool >= 0` as the invariant — the payment that would overspend the declaration is a rejected write. A shareholder can be paid once per declaration, and a closed distribution is terminal.", "url": "https://soma-lang.dev/corpus/escrow_finance/dividend_pool.cell", "repo_path": "examples/corpus/escrow_finance/dividend_pool.cell", "lines": 96, "features": ["state_machine", "invariant"], "cells": ["Dividend", "DividendTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/dvp_settlement", "domain": "escrow_finance", "title": "DELIVERY-VERSUS-PAYMENT — no securities leave before the cash arrives", "summary": "DELIVERY-VERSUS-PAYMENT — no securities leave before the cash arrives On 26 June 1974, Bankhaus Herstatt was shut down by regulators AFTER its counterparties had irrevocably paid the Deutschmark leg of their FX trades but BEFORE Herstatt paid out the dollar leg. The money was simply gone — \"Herstatt risk\" got its name and CLS Bank got founded. The cure is delivery-versus-payment: the two legs are ONE state machine, and the deliver edge exists only after cash is confirmed. A trade abandoned after cash arrives must pass through `refunded` — cash can never be stranded — and `soma verify` proves every path ends settled or made-whole.", "url": "https://soma-lang.dev/corpus/escrow_finance/dvp_settlement.cell", "repo_path": "examples/corpus/escrow_finance/dvp_settlement.cell", "lines": 111, "features": ["state_machine", "invariant"], "cells": ["DvP", "DvPTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "16 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/invoice_factoring", "domain": "escrow_finance", "title": "INVOICE FACTORING — no advance on unverified paper, no double-selling", "summary": "INVOICE FACTORING — no advance on unverified paper, no double-selling Greensill Capital collapsed in 2021 holding billions in \"invoices\" that were never verified — some for trade that hadn't happened, some financed twice through different vehicles. The two frauds are structural here: an invoice can only be SOLD from the verified state (the issued -> sold edge does not exist), and sold has no edge back to itself or to verified, so the same invoice cannot be advanced twice. The advance ledger caps the cash at 90% of face value and refuses negative writes.", "url": "https://soma-lang.dev/corpus/escrow_finance/invoice_factoring.cell", "repo_path": "examples/corpus/escrow_finance/invoice_factoring.cell", "lines": 108, "features": ["state_machine", "invariant"], "cells": ["Factoring", "FactoringTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "15 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/letter_of_credit", "domain": "escrow_finance", "title": "LETTER OF CREDIT — the bank pays against verified documents, never trust", "summary": "LETTER OF CREDIT — the bank pays against verified documents, never trust A documentary letter of credit (UCP 600) exists because exporter and importer don't trust each other across an ocean: the bank promises to pay the seller, but ONLY against documents proving shipment. The classic loss is paying on presented-but-unexamined documents — the Salomon-era trade-finance frauds ran exactly this gap, with bills of lading for cargo that never sailed. Here `honored` is reachable only through `docs_verified`; presenting is not verifying; partial drawings draw down a credit slot that refuses to go below zero, so the beneficiary can never draw more than the credit line. Expired credits are terminal.", "url": "https://soma-lang.dev/corpus/escrow_finance/letter_of_credit.cell", "repo_path": "examples/corpus/escrow_finance/letter_of_credit.cell", "lines": 116, "features": ["state_machine", "invariant"], "cells": ["LetterOfCredit", "LocTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/loan_amortization", "domain": "escrow_finance", "title": "LOAN AMORTIZATION — principal never goes negative, never grows back", "summary": "LOAN AMORTIZATION — principal never goes negative, never grows back Two amortization bugs with real victims: servicers who kept drafting payments after payoff (principal goes negative = the borrower is owed money and usually never told), and the pre-2008 \"option ARM\" negative amortization, where a payment smaller than the accrued interest silently GREW the principal until the loan ballooned past the house's value. Here `principal >= 0` is a memory invariant — the overdraft write raises — and a payment must at least cover the month's interest, so the balance is monotonically non-increasing. paid_off is terminal and proven.", "url": "https://soma-lang.dev/corpus/escrow_finance/loan_amortization.cell", "repo_path": "examples/corpus/escrow_finance/loan_amortization.cell", "lines": 100, "features": ["state_machine", "invariant"], "cells": ["Loan", "LoanTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/milestone_escrow", "domain": "escrow_finance", "title": "MILESTONE ESCROW — a contractor is paid per accepted milestone, never ahead", "summary": "MILESTONE ESCROW — a contractor is paid per accepted milestone, never ahead Freelance platforms learned this the expensive way: pay a contractor the full project fee up front and disputes become hostage negotiations. The escrow answer is milestones — but then the bug moves: releasing milestone money TWICE, or releasing more than the client funded. Here the funded balance is a slot that releases draw down (`escrowed >= 0`: the over-release is a rejected write), each milestone is released at most once, and a cancelled or completed project is terminal — the leftover balance goes back to the client exactly once.", "url": "https://soma-lang.dev/corpus/escrow_finance/milestone_escrow.cell", "repo_path": "examples/corpus/escrow_finance/milestone_escrow.cell", "lines": 106, "features": ["state_machine", "invariant"], "cells": ["MilestoneEscrow", "MilestoneTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/multisig_disburse", "domain": "escrow_finance", "title": "MULTISIG TREASURY — 2-of-3 distinct approvals, proven before a cent moves", "summary": "MULTISIG TREASURY — 2-of-3 distinct approvals, proven before a cent moves In July 2017 the Parity multisig wallet lost $30M because a code path let a single caller re-initialize ownership and drain funds alone — the \"multi\" in multisig was a convention, not a structure. Here the quorum IS the structure: disbursed is reachable ONLY through the quorum state, which requires two approvals from DISTINCT owners (a repeat approval does not advance the machine). `soma verify` proves the only path to disbursed passes through quorum; the vault refuses negative balances.", "url": "https://soma-lang.dev/corpus/escrow_finance/multisig_disburse.cell", "repo_path": "examples/corpus/escrow_finance/multisig_disburse.cell", "lines": 109, "features": ["state_machine", "invariant"], "cells": ["Multisig", "MultisigTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/payroll_run", "domain": "escrow_finance", "title": "PAYROLL RUN — the payslips must sum EXACTLY to the approved total", "summary": "PAYROLL RUN — the payslips must sum EXACTLY to the approved total Payroll overpayments are a quiet epidemic: a duplicated payslip or a fat-fingered salary slips into a run, the bank file goes out, and the company spends months clawing money back from employees (legally messy, morale-destroying). The wall here: the approved budget is a slot that each payslip DECREMENTS, with `budget >= 0` as an invariant — a payslip that would overspend the approval RAISES at the write. And the run can only commit when the budget hits exactly zero: paid == approved, proven by arithmetic, not by hope. Committed runs are terminal.", "url": "https://soma-lang.dev/corpus/escrow_finance/payroll_run.cell", "repo_path": "examples/corpus/escrow_finance/payroll_run.cell", "lines": 100, "features": ["state_machine", "invariant"], "cells": ["Payroll", "PayrollTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/security_deposit", "domain": "escrow_finance", "title": "SECURITY DEPOSIT — deductions can never exceed what the tenant paid", "summary": "SECURITY DEPOSIT — deductions can never exceed what the tenant paid Every US state's tenancy law has the same clause because the same abuse keeps happening: a landlord itemizes $2,400 of \"damages\" against a $1,500 deposit and bills the tenant for the fantasy difference — or keeps deducting after the deposit was already returned. Here the deposit is a slot that deductions draw down with `deposit >= 0` as the wall: the over-deduction is a REJECTED WRITE. Returning the balance moves the tenancy to a terminal state, so post-return deductions have no edge.", "url": "https://soma-lang.dev/corpus/escrow_finance/security_deposit.cell", "repo_path": "examples/corpus/escrow_finance/security_deposit.cell", "lines": 99, "features": ["state_machine", "invariant"], "cells": ["DepositAccount", "DepositTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/two_party_escrow", "domain": "escrow_finance", "title": "TWO-PARTY ESCROW — funds move only when BOTH sides say so, and never leak", "summary": "TWO-PARTY ESCROW — funds move only when BOTH sides say so, and never leak Classified-ad escrow fraud works one way: the \"escrow agent\" releases the buyer's money before the seller delivers, or refunds after releasing — paying the same dollars out twice. The FBI's IC3 logs thousands of these a year. The fix is structural: release/refund are TERMINAL states of one machine (no path back, proven by `soma verify`), release requires both confirmations, and the held ledger refuses negative balances so the same cent cannot leave twice. Conservation (held + paid == funded) is checked on every read.", "url": "https://soma-lang.dev/corpus/escrow_finance/two_party_escrow.cell", "repo_path": "examples/corpus/escrow_finance/two_party_escrow.cell", "lines": 117, "features": ["state_machine", "invariant"], "cells": ["Escrow", "EscrowTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "17 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/vesting_schedule", "domain": "escrow_finance", "title": "VESTING SCHEDULE — cliff then linear, and over-vesting is unwritable", "summary": "VESTING SCHEDULE — cliff then linear, and over-vesting is unwritable Equity vesting disputes are a startup classic: a payroll script with an off-by-one releases shares before the 12-month cliff, or rounds the linear schedule up until the employee has claimed MORE than the grant. Clawing shares back after the fact means lawyers. Here the award pool is a memory slot that only decrements: `remaining >= 0` makes claiming past the total grant a rejected write, the cliff is enforced in the vested math, and a forfeited grant is a TERMINAL state — verified, no path back.", "url": "https://soma-lang.dev/corpus/escrow_finance/vesting_schedule.cell", "repo_path": "examples/corpus/escrow_finance/vesting_schedule.cell", "lines": 118, "features": ["state_machine", "invariant"], "cells": ["Vesting", "VestingTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "escrow_finance/wire_dual_control", "domain": "escrow_finance", "title": "WIRE DUAL CONTROL — the maker can never be the checker", "summary": "WIRE DUAL CONTROL — the maker can never be the checker In August 2020 Citibank meant to send $7.8M of interest on a Revlon loan and instead wired the full $893M principal. Three humans approved it — but all three were looking at the same misleading screen, and a court initially let the creditors KEEP it. Dual control only works when the checker is structurally distinct and the amount has a hard ceiling. Here a wire cannot reach `sent` except through `checked` (the drafted -> sent edge does not exist), the maker's own approval is refused, and the per-wire amount slot rejects anything over the desk's $10M limit at the write — the $893M fat-finger dies in memory, not in a code review.", "url": "https://soma-lang.dev/corpus/escrow_finance/wire_dual_control.cell", "repo_path": "examples/corpus/escrow_finance/wire_dual_control.cell", "lines": 98, "features": ["state_machine", "invariant"], "cells": ["WireDesk", "WireTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "finance/bond_pricer", "domain": "finance", "title": "Fixed-coupon bond pricing: present value of coupons plus redemption, current yield, and a par/premium/discount classifier", "summary": "Fixed-coupon bond pricing: present value of coupons plus redemption, current yield, and a par/premium/discount classifier. Discounts each coupon over a range, sum() of the discounted stream.", "url": "https://soma-lang.dev/corpus/finance/bond_pricer.cell", "repo_path": "examples/corpus/finance/bond_pricer.cell", "lines": 49, "features": [], "cells": ["BondPricer", "BondTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/budget_tracker", "domain": "finance", "title": "Monthly budget tracker with a spend cap invariant", "summary": "Monthly budget tracker with a spend cap invariant. Total spend per category must never exceed its allotted budget; an over-budget write is rejected by memory. Shows group accounting and a remaining-budget query.", "url": "https://soma-lang.dev/corpus/finance/budget_tracker.cell", "repo_path": "examples/corpus/finance/budget_tracker.cell", "lines": 54, "features": ["invariant", "try"], "cells": ["BudgetTracker", "BudgetTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "0 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "finance/chip_ledger", "domain": "finance", "title": "Chip/cash ledger with a non-negative balance invariant", "summary": "Chip/cash ledger with a non-negative balance invariant. The memory itself rejects any write that would overdraw an account — the bad .set() never commits, so the slot keeps its previous value. Demonstrates: memory invariant, try around a guarded write, assert_fails.", "url": "https://soma-lang.dev/corpus/finance/chip_ledger.cell", "repo_path": "examples/corpus/finance/chip_ledger.cell", "lines": 54, "features": ["invariant", "try"], "cells": ["ChipLedger", "ChipLedgerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "0 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "finance/compound_interest", "domain": "finance", "title": "Compound interest: future value, with periodic compounding and a continuous-compounding variant", "summary": "Compound interest: future value, with periodic compounding and a continuous-compounding variant. Pure numeric handlers, tolerance-based float assertions (never == on floats).", "url": "https://soma-lang.dev/corpus/finance/compound_interest.cell", "repo_path": "examples/corpus/finance/compound_interest.cell", "lines": 46, "features": [], "cells": ["CompoundInterest", "CompoundTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/currency_converter", "domain": "finance", "title": "FX converter with a rate table in memory and a non-negative rate invariant", "summary": "FX converter with a rate table in memory and a non-negative rate invariant. Cross rates are derived via a USD base. Demonstrates a Map<String,Float> slot, an invariant on stored values, and triangular cross-rate arithmetic.", "url": "https://soma-lang.dev/corpus/finance/currency_converter.cell", "repo_path": "examples/corpus/finance/currency_converter.cell", "lines": 60, "features": ["invariant", "try"], "cells": ["FxConverter", "FxTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "0 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "finance/dividend_yield", "domain": "finance", "title": "Equity income metrics: dividend yield, payout ratio, dividend-discount (Gordon growth) fair value, and yield-on-cost", "summary": "Equity income metrics: dividend yield, payout ratio, dividend-discount (Gordon growth) fair value, and yield-on-cost. Straightforward ratios with guards against division by zero.", "url": "https://soma-lang.dev/corpus/finance/dividend_yield.cell", "repo_path": "examples/corpus/finance/dividend_yield.cell", "lines": 49, "features": [], "cells": ["DividendMetrics", "DividendTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/fee_calculator", "domain": "finance", "title": "Brokerage fee calculator: tiered commission, bps fee with a floor, and a maker/taker exchange fee", "summary": "Brokerage fee calculator: tiered commission, bps fee with a floor, and a maker/taker exchange fee. Shows clamp/max for floors and caps, and match on a tier bucket.", "url": "https://soma-lang.dev/corpus/finance/fee_calculator.cell", "repo_path": "examples/corpus/finance/fee_calculator.cell", "lines": 57, "features": ["match"], "cells": ["FeeCalculator", "FeeTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/loan_amortization", "domain": "finance", "title": "Fixed-rate loan amortization: monthly payment, remaining balance after k payments, and total interest paid", "summary": "Fixed-rate loan amortization: monthly payment, remaining balance after k payments, and total interest paid. Standard annuity formula with periodic compounding.", "url": "https://soma-lang.dev/corpus/finance/loan_amortization.cell", "repo_path": "examples/corpus/finance/loan_amortization.cell", "lines": 48, "features": [], "cells": ["LoanAmortization", "LoanTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/moving_average", "domain": "finance", "title": "Moving averages over a price series: simple MA window, full-series mean, and a momentum signal from an SMA crossover", "summary": "Moving averages over a price series: simple MA window, full-series mean, and a momentum signal from an SMA crossover. Uses range(), avg(), slicing by index, sum() reductions.", "url": "https://soma-lang.dev/corpus/finance/moving_average.cell", "repo_path": "examples/corpus/finance/moving_average.cell", "lines": 64, "features": [], "cells": ["MovingAverage", "MovingAverageTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/npv", "domain": "finance", "title": "Discounted cash flow: present value of a single flow, net present value of a cash-flow stream, and a simple payback-period count", "summary": "Discounted cash flow: present value of a single flow, net present value of a cash-flow stream, and a simple payback-period count. Discounting over an index range, sum() of derived discounted flows.", "url": "https://soma-lang.dev/corpus/finance/npv.cell", "repo_path": "examples/corpus/finance/npv.cell", "lines": 57, "features": [], "cells": ["DCF", "DCFTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/option_payoff", "domain": "finance", "title": "European option payoffs at expiry, plus a long straddle", "summary": "European option payoffs at expiry, plus a long straddle. max()/min() of two numbers, records for the trade leg, tolerance asserts.", "url": "https://soma-lang.dev/corpus/finance/option_payoff.cell", "repo_path": "examples/corpus/finance/option_payoff.cell", "lines": 56, "features": [], "cells": ["OptionPayoff", "OptionTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/order_lifecycle", "domain": "finance", "title": "Order lifecycle as a verified state machine: an order flows from new to filled or rejected, and a fill settles", "summary": "Order lifecycle as a verified state machine: an order flows from new to filled or rejected, and a fill settles. Every state can reach a terminal (settled / rejected / cancelled). Pairs with order_lifecycle.toml so `soma verify` proves deadlock-freedom and eventual settlement.", "url": "https://soma-lang.dev/corpus/finance/order_lifecycle.cell", "repo_path": "examples/corpus/finance/order_lifecycle.cell", "lines": 63, "features": ["state_machine", "guard"], "cells": ["OrderLifecycle", "OrderLifecycleTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "finance/portfolio_pnl", "domain": "finance", "title": "Portfolio P&L tracker over a list of position records", "summary": "Portfolio P&L tracker over a list of position records. Each position: {symbol, qty, cost, mark}. Computes per-position and total unrealized P&L, market value, and the best/worst performer. Shows records, pipe map/filter, sum_by-style reductions over derived fields.", "url": "https://soma-lang.dev/corpus/finance/portfolio_pnl.cell", "repo_path": "examples/corpus/finance/portfolio_pnl.cell", "lines": 63, "features": ["pipeline", "lambda"], "cells": ["PortfolioPnL", "PortfolioTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/position_limit", "domain": "finance", "title": "Position-limit risk gate", "summary": "Position-limit risk gate. Each symbol's net position must stay within [-MAX, +MAX]. The memory invariant enforces it on every write, so an order that would breach the limit is refused and the book is unchanged.", "url": "https://soma-lang.dev/corpus/finance/position_limit.cell", "repo_path": "examples/corpus/finance/position_limit.cell", "lines": 59, "features": ["invariant", "try"], "cells": ["PositionBook", "PositionTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "0 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "finance/returns_stats", "domain": "finance", "title": "Return-series statistics: arithmetic mean return, volatility (sample stdev), annualized Sharpe ratio, and max drawdown of an equity curve", "summary": "Return-series statistics: arithmetic mean return, volatility (sample stdev), annualized Sharpe ratio, and max drawdown of an equity curve. sqrt/pow, sum() reductions, running peak tracking.", "url": "https://soma-lang.dev/corpus/finance/returns_stats.cell", "repo_path": "examples/corpus/finance/returns_stats.cell", "lines": 62, "features": [], "cells": ["ReturnStats", "ReturnStatsTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/tax_brackets", "domain": "finance", "title": "Progressive income tax over marginal brackets, plus effective rate and marginal rate lookup", "summary": "Progressive income tax over marginal brackets, plus effective rate and marginal rate lookup. Iterates a list of {upto, rate} bracket records, taxing each slice. Records, min(), accumulation.", "url": "https://soma-lang.dev/corpus/finance/tax_brackets.cell", "repo_path": "examples/corpus/finance/tax_brackets.cell", "lines": 70, "features": [], "cells": ["TaxBrackets", "TaxTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "finance/trade_settlement", "domain": "finance", "title": "Trade settlement as a sum type", "summary": "Trade settlement as a sum type. A settlement attempt yields one of three tagged variants; `match` over them is exhaustive (drop an arm and `soma check` refuses). Demonstrates struct / tuple / unit variants and exhaustive matching for money outcomes.", "url": "https://soma-lang.dev/corpus/finance/trade_settlement.cell", "repo_path": "examples/corpus/finance/trade_settlement.cell", "lines": 58, "features": ["sum_type", "match"], "cells": ["Settlement", "TradeSettlement", "SettlementTests"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "games/blackjack", "domain": "games", "title": "Blackjack — hand scoring with soft/hard aces and bust detection hand_value() sums card ranks, counting each Ace as 11 then demoting to 1 while the total busts", "summary": "Blackjack — hand scoring with soft/hard aces and bust detection hand_value() sums card ranks, counting each Ace as 11 then demoting to 1 while the total busts. outcome() compares a player and dealer hand under standard rules (blackjack beats 21-of-three, bust loses). Run: soma run blackjack.cell --signal demo Test: soma test blackjack.cell", "url": "https://soma-lang.dev/corpus/games/blackjack.cell", "repo_path": "examples/corpus/games/blackjack.cell", "lines": 86, "features": ["match"], "cells": ["Blackjack", "BlackjackTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/card_deck", "domain": "games", "title": "Card deck — build, deterministic Fisher-Yates shuffle, and deal A 52-card deck is built as \"Rank of Suit\" strings", "summary": "Card deck — build, deterministic Fisher-Yates shuffle, and deal A 52-card deck is built as \"Rank of Suit\" strings. shuffle() uses a seeded linear-congruential PRNG so the permutation is reproducible (no random()). deal() splits the deck into n hands of k cards round-robin. Run: soma run card_deck.cell --signal demo Test: soma test card_deck.cell", "url": "https://soma-lang.dev/corpus/games/card_deck.cell", "repo_path": "examples/corpus/games/card_deck.cell", "lines": 85, "features": [], "cells": ["CardDeck", "CardDeckTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/connect_four", "domain": "games", "title": "Connect Four — drop a disc and detect four-in-a-row The board is a flat row-major 6x7 grid (row 0 = top)", "summary": "Connect Four — drop a disc and detect four-in-a-row The board is a flat row-major 6x7 grid (row 0 = top). drop() lands a disc in the lowest empty slot of a column. has_four() scans every horizontal, vertical, and both diagonal directions for four matching discs. Run: soma run connect_four.cell --signal demo Test: soma test connect_four.cell", "url": "https://soma-lang.dev/corpus/games/connect_four.cell", "repo_path": "examples/corpus/games/connect_four.cell", "lines": 93, "features": [], "cells": ["ConnectFour", "ConnectFourTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/conway_life", "domain": "games", "title": "Conway's Game of Life — one generation step on a fixed grid The grid is a flat row-major list of 0/1 over an r×c board", "summary": "Conway's Game of Life — one generation step on a fixed grid The grid is a flat row-major list of 0/1 over an r×c board. step() applies the B3/S23 rule with bounded (non-wrapping) neighbour counts. A blinker oscillates with period 2; a block is still life. Run: soma run conway_life.cell --signal demo Test: soma test conway_life.cell", "url": "https://soma-lang.dev/corpus/games/conway_life.cell", "repo_path": "examples/corpus/games/conway_life.cell", "lines": 82, "features": [], "cells": ["ConwayLife", "ConwayTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/craps", "domain": "games", "title": "Craps — the come-out roll and point-resolution rules come_out(total) resolves the first roll: 7/11 wins, 2/3/12 craps out, any other number becomes the \"point\"", "summary": "Craps — the come-out roll and point-resolution rules come_out(total) resolves the first roll: 7/11 wins, 2/3/12 craps out, any other number becomes the \"point\". resolve(point, rolls) plays the rest of the round — rolling the point again wins, a 7 loses. All from a roll log. Run: soma run craps.cell --signal demo Test: soma test craps.cell", "url": "https://soma-lang.dev/corpus/games/craps.cell", "repo_path": "examples/corpus/games/craps.cell", "lines": 77, "features": ["match"], "cells": ["Craps", "CrapsTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/game_2048", "domain": "games", "title": "2048 — slide-and-merge a single row (the core move primitive)", "summary": "2048 — slide-and-merge a single row (the core move primitive) slide_left() compacts a row toward the left, merging equal adjacent tiles exactly once per move (left-to-right), and reports the points scored (sum of merged tiles). A full board move is four row slides; this is that primitive. Run: soma run game_2048.cell --signal demo Test: soma test game_2048.cell", "url": "https://soma-lang.dev/corpus/games/game_2048.cell", "repo_path": "examples/corpus/games/game_2048.cell", "lines": 77, "features": [], "cells": ["Game2048", "Game2048Tests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/guessing_game", "domain": "games", "title": "Number guessing game — hi/lo feedback and a binary-search solver feedback() compares a guess to the secret and returns \"low\" / \"high\" / \"correct\"", "summary": "Number guessing game — hi/lo feedback and a binary-search solver feedback() compares a guess to the secret and returns \"low\" / \"high\" / \"correct\". auto_solve() proves the search space is exhausted in at most ceil(log2(range)) guesses by playing the optimal binary-search strategy. Run: soma run guessing_game.cell --signal demo Test: soma test guessing_game.cell", "url": "https://soma-lang.dev/corpus/games/guessing_game.cell", "repo_path": "examples/corpus/games/guessing_game.cell", "lines": 67, "features": ["match"], "cells": ["GuessingGame", "GuessingTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/hanoi", "domain": "games", "title": "Tower of Hanoi — minimum moves and an explicit move list min_moves(n) = 2^n - 1", "summary": "Tower of Hanoi — minimum moves and an explicit move list min_moves(n) = 2^n - 1. solve(n) produces the ordered list of \"from->to\" peg moves by the classic recursive strategy, implemented iteratively with an explicit stack so it stays within Soma's handler model. Run: soma run hanoi.cell --signal demo Test: soma test hanoi.cell", "url": "https://soma-lang.dev/corpus/games/hanoi.cell", "repo_path": "examples/corpus/games/hanoi.cell", "lines": 78, "features": [], "cells": ["Hanoi", "HanoiTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/mastermind", "domain": "games", "title": "Mastermind — score a guess with black and white pegs Black pegs = right colour in the right position", "summary": "Mastermind — score a guess with black and white pegs Black pegs = right colour in the right position. White pegs = right colour in the wrong position, counted with multiplicity via colour frequency matching (the classic rule). Pure scoring over fixed-length code lists. Run: soma run mastermind.cell --signal demo Test: soma test mastermind.cell", "url": "https://soma-lang.dev/corpus/games/mastermind.cell", "repo_path": "examples/corpus/games/mastermind.cell", "lines": 92, "features": ["match"], "cells": ["Mastermind", "MastermindTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/maze_step", "domain": "games", "title": "Maze movement — one step with wall collision on a grid The maze is a flat row-major list: 0 = open, 1 = wall", "summary": "Maze movement — one step with wall collision on a grid The maze is a flat row-major list: 0 = open, 1 = wall. move() attempts a step in a compass direction; the player stays put if the target is a wall or off the grid. walk() applies a sequence of moves and returns the final position plus whether the exit was reached. Run: soma run maze_step.cell --signal demo Test: soma test maze_step.cell", "url": "https://soma-lang.dev/corpus/games/maze_step.cell", "repo_path": "examples/corpus/games/maze_step.cell", "lines": 82, "features": [], "cells": ["MazeStep", "MazeTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/minesweeper", "domain": "games", "title": "Minesweeper — compute the neighbour-mine board from a mine layout mines is a flat row-major r×c list of 0/1", "summary": "Minesweeper — compute the neighbour-mine board from a mine layout mines is a flat row-major r×c list of 0/1. annotate() returns a board where each non-mine cell holds its count of adjacent mines (0..8) and each mine cell holds -1. reveal_safe() reports whether a click is safe. Run: soma run minesweeper.cell --signal demo Test: soma test minesweeper.cell", "url": "https://soma-lang.dev/corpus/games/minesweeper.cell", "repo_path": "examples/corpus/games/minesweeper.cell", "lines": 77, "features": [], "cells": ["Minesweeper", "MinesweeperTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/nim", "domain": "games", "title": "Nim — optimal play via the Sprague-Grundy nim-sum In normal-play Nim a position is a loss for the player to move iff the XOR of all heap sizes is 0", "summary": "Nim — optimal play via the Sprague-Grundy nim-sum In normal-play Nim a position is a loss for the player to move iff the XOR of all heap sizes is 0. nim_sum() computes it; best_move() finds a winning (heap, take) move when one exists, else surrenders. Run: soma run nim.cell --signal demo Test: soma test nim.cell", "url": "https://soma-lang.dev/corpus/games/nim.cell", "repo_path": "examples/corpus/games/nim.cell", "lines": 75, "features": [], "cells": ["Nim", "NimTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/pig_dice", "domain": "games", "title": "Pig — the press-your-luck dice game, scored from a roll log", "summary": "Pig — the press-your-luck dice game, scored from a roll log In Pig a player rolls a d6 repeatedly, banking the running total — but a 1 busts the turn and scores 0. turn_score() folds a list of rolls into the banked points. play() runs the \"hold at 20\" strategy over a deterministic roll stream and reports the turn outcomes. Run: soma run pig_dice.cell --signal demo Test: soma test pig_dice.cell", "url": "https://soma-lang.dev/corpus/games/pig_dice.cell", "repo_path": "examples/corpus/games/pig_dice.cell", "lines": 66, "features": ["lambda"], "cells": ["PigDice", "PigTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/rock_paper_scissors", "domain": "games", "title": "Rock-paper-scissors — round judging and best-of-N scoring judge(a, b) returns \"p1\", \"p2\", or \"tie\" from the two throws", "summary": "Rock-paper-scissors — round judging and best-of-N scoring judge(a, b) returns \"p1\", \"p2\", or \"tie\" from the two throws. play_match scores a list of round pairs and reports the winner. Pure and deterministic. Run: soma run rock_paper_scissors.cell --signal demo Test: soma test rock_paper_scissors.cell", "url": "https://soma-lang.dev/corpus/games/rock_paper_scissors.cell", "repo_path": "examples/corpus/games/rock_paper_scissors.cell", "lines": 72, "features": ["match"], "cells": ["RockPaperScissors", "RpsTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/snake", "domain": "games", "title": "Snake — one movement tick with growth, wall and self collision The snake is a list of {y, x} segments, head first", "summary": "Snake — one movement tick with growth, wall and self collision The snake is a list of {y, x} segments, head first. tick() moves the head one cell in the current direction; if it lands on food the tail is kept (grow), otherwise the tail is dropped. A move into a wall or into the snake's own body is reported as a crash. Run: soma run snake.cell --signal demo Test: soma test snake.cell", "url": "https://soma-lang.dev/corpus/games/snake.cell", "repo_path": "examples/corpus/games/snake.cell", "lines": 75, "features": ["lambda"], "cells": ["Snake", "SnakeTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/tic_tac_toe", "domain": "games", "title": "Tic-tac-toe win detection — pure board logic A board is a flat list of 9 cells, each \"X\", \"O\", or \"\" (empty)", "summary": "Tic-tac-toe win detection — pure board logic A board is a flat list of 9 cells, each \"X\", \"O\", or \"\" (empty). The winner() handler scans the 8 winning lines and returns the mark of the winner, \"draw\" if the board is full with no line, or \"\" if still playing. Run: soma run tic_tac_toe.cell --signal demo Test: soma test tic_tac_toe.cell", "url": "https://soma-lang.dev/corpus/games/tic_tac_toe.cell", "repo_path": "examples/corpus/games/tic_tac_toe.cell", "lines": 67, "features": ["lambda"], "cells": ["TicTacToe", "TicTacToeTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/turn_tracker", "domain": "games", "title": "Turn tracker — round/phase state machine with player rotation", "summary": "Turn tracker — round/phase state machine with player rotation Models a multi-player turn order: the active player index cycles 0..n-1, incrementing the round each time play wraps back to player 0. A `phase` state machine guards the upkeep → main → end → upkeep cycle, with a *->over catch-all so the game always terminates. Run: soma run turn_tracker.cell --signal demo Test: soma test turn_tracker.cell Verify: soma verify turn_tracker.cell (needs soma.toml)", "url": "https://soma-lang.dev/corpus/games/turn_tracker.cell", "repo_path": "examples/corpus/games/turn_tracker.cell", "lines": 71, "features": ["state_machine"], "cells": ["TurnTracker", "TurnTrackerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "7 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/war", "domain": "games", "title": "War — the card-comparison game, played to exhaustion Each card is an integer rank 2..14 (J=11..A=14)", "summary": "War — the card-comparison game, played to exhaustion Each card is an integer rank 2..14 (J=11..A=14). A \"battle\" gives the higher card to the winner; ties trigger a simplified \"war\" where the next card decides. play() runs two ordered decks head to head and reports the winner and number of battles. Fully deterministic. Run: soma run war.cell --signal demo Test: soma test war.cell", "url": "https://soma-lang.dev/corpus/games/war.cell", "repo_path": "examples/corpus/games/war.cell", "lines": 76, "features": [], "cells": ["War", "WarTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games/yahtzee", "domain": "games", "title": "Yahtzee — score a roll of five dice in any category counts() buckets the five dice into face frequencies", "summary": "Yahtzee — score a roll of five dice in any category counts() buckets the five dice into face frequencies. The category scorers read those buckets: upper boxes, n-of-a-kind, full house, straights, and the 50-point Yahtzee. All pure integer logic. Run: soma run yahtzee.cell --signal demo Test: soma test yahtzee.cell", "url": "https://soma-lang.dev/corpus/games/yahtzee.cell", "repo_path": "examples/corpus/games/yahtzee.cell", "lines": 99, "features": ["lambda"], "cells": ["Yahtzee", "YahtzeeTests"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/games/soma.toml"}, {"id": "games_economy/auction_house", "domain": "games_economy", "title": "AUCTION HOUSE — escrowed bids, gold that cannot be printed", "summary": "AUCTION HOUSE — escrowed bids, gold that cannot be printed In 2013 Blizzard took the Diablo III auction house offline after patch 1.0.8: cancelling a bid refunded the gold WITHOUT releasing the escrow, and billions of duplicated gold crashed the economy within hours. The bug was an accounting gap — wallet and escrow updated by paths that disagreed. Here the accounting is structural: a bid MOVES gold wallet->escrow in one handler, an outbid refunds exactly the escrowed amount, and total_gold() is conserved by construction. Balances cannot go negative (the memory refuses the write), and `sold` is a TERMINAL state soma verify proves: a settled auction can never reopen for a second refund.", "url": "https://soma-lang.dev/corpus/games_economy/auction_house.cell", "repo_path": "examples/corpus/games_economy/auction_house.cell", "lines": 124, "features": ["state_machine", "invariant", "try"], "cells": ["AuctionHouse", "AuctionTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/battle_pass", "domain": "games_economy", "title": "BATTLE PASS — every tier reward claimed exactly once", "summary": "BATTLE PASS — every tier reward claimed exactly once Battle-pass duplication exploits reduce to two writes: a claim counter going past 1 (claim, crash the client mid-grant, claim again — the \"crash-and-reclaim\" farmed in several seasons of big battle royales), or tier progress jumping the track via a modified client. Here each (player, tier) claim is walled at <= 1 BY THE MEMORY, tier progress is capped at 50 by an invariant, and the season itself is a machine whose `closed` state is terminal — soma verify proves that when a season ends, the books are shut for good.", "url": "https://soma-lang.dev/corpus/games_economy/battle_pass.cell", "repo_path": "examples/corpus/games_economy/battle_pass.cell", "lines": 92, "features": ["state_machine", "invariant", "try"], "cells": ["BattlePass", "PassTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/battle_turns", "domain": "games_economy", "title": "BATTLE TURNS — nobody acts twice, and the dead stay dead", "summary": "BATTLE TURNS — nobody acts twice, and the dead stay dead The oldest cheat in networked turn-based games is the double-move: send two action packets before the server flips the turn flag (Pokemon battle simulators and play-by-mail chess servers both had it). Its cousin: keep acting after the battle ended to farm rewards from a corpse. Here the turn IS the machine — your attack is the transition that hands the turn over, so a second attack has no state to fire from. `victory` and `defeat` are terminal (soma verify proves it), and HP lives behind a 0..100 invariant: damage can never make HP negative, healing can never pass full.", "url": "https://soma-lang.dev/corpus/games_economy/battle_turns.cell", "repo_path": "examples/corpus/games_economy/battle_turns.cell", "lines": 89, "features": ["state_machine", "invariant"], "cells": ["Battle", "BattleTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/crafting_forge", "domain": "games_economy", "title": "CRAFTING FORGE — ingredients consumed exactly once", "summary": "CRAFTING FORGE — ingredients consumed exactly once The classic MMO \"craft-cancel dupe\": start a craft, let the server consume the ingredients, then cancel at the exact tick that refunds them — keeping both the refund and (on a desynced shard) the output. Ultima Online and early WoW economies were both warped by variants of this bug. Here the craft job is a machine soma verify proves: `cancelled` is reachable ONLY from `pending` — before anything was consumed. Once the ingredients are gone the only path is `finished`, which is terminal (no re-finishing for a second free sword). And the pantry refuses to go negative, so a craft can never consume ingredients that are not there.", "url": "https://soma-lang.dev/corpus/games_economy/crafting_forge.cell", "repo_path": "examples/corpus/games_economy/crafting_forge.cell", "lines": 98, "features": ["state_machine", "invariant", "try"], "cells": ["Forge", "ForgeTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/daily_chest", "domain": "games_economy", "title": "DAILY CHEST — one claim per day, clock tricks be damned", "summary": "DAILY CHEST — one claim per day, clock tricks be damned Daily-reward double claims — via device-clock manipulation or plain request replay — are the most farmed exploit in free-to-play games, and \"fixes\" that compare timestamps keep losing to timezone math. The fix is not a better clock check. It is that each (player, day) claim is a one-way machine: unclaimed -> claimed, with `claimed` TERMINAL. The replayed request has no transition to fire — soma verify proves it. The coin ledger's >= 0 invariant keeps the wallet honest on the way through.", "url": "https://soma-lang.dev/corpus/games_economy/daily_chest.cell", "repo_path": "examples/corpus/games_economy/daily_chest.cell", "lines": 57, "features": ["state_machine", "invariant", "try"], "cells": ["DailyChest", "ChestTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/gem_store", "domain": "games_economy", "title": "GEM STORE — a purchase receipt credits exactly once", "summary": "GEM STORE — a purchase receipt credits exactly once The \"receipt replay\" exploit: capture one valid in-app-purchase receipt and submit it to the game server again and again — each replay credits the gems again. Several mobile studios shipped this exact validation gap before Apple and Google hardened server-side receipt checks; it is real money printed from a single purchase. Here a receipt is a state machine: created -> paid -> credited, and `credited` is TERMINAL — the replayed submit has no transition to take. Conservation rides on top: every gem in circulation traces to exactly one credited receipt (minted == circulating + sunk), and no balance can ever go negative.", "url": "https://soma-lang.dev/corpus/games_economy/gem_store.cell", "repo_path": "examples/corpus/games_economy/gem_store.cell", "lines": 101, "features": ["state_machine", "invariant", "try"], "cells": ["GemStore", "GemTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/guild_bank", "domain": "games_economy", "title": "GUILD BANK — the heist needs a key an expelled member cannot hold", "summary": "GUILD BANK — the heist needs a key an expelled member cannot hold EVE Online's Guiding Hand Social Club heist and a thousand WoW guild-bank ninja-loots share one mechanic: ACCESS OUTLIVES STANDING. A member is expelled but a cached session, a stale permission row, or a race lets one last withdrawal through. Here membership is a machine — `expelled` is TERMINAL (soma verify proves there is no readmission edge) and every withdrawal checks live standing. Two memory walls hold even if all that logic were deleted: the vault can never go negative, and no member's daily withdrawals can exceed 500 gold, because larger values cannot be written into the ledger at all.", "url": "https://soma-lang.dev/corpus/games_economy/guild_bank.cell", "repo_path": "examples/corpus/games_economy/guild_bank.cell", "lines": 102, "features": ["state_machine", "invariant", "try"], "cells": ["GuildBank", "BankTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/harvest_node", "domain": "games_economy", "title": "HARVEST NODE — one vein, one yield per respawn cycle", "summary": "HARVEST NODE — one vein, one yield per respawn cycle \"Node duping\" in MMO gathering: hit the same ore vein twice inside the lag window before the server marks it empty. Classic WoW's launch had mining nodes yielding to two players at once, and every gathering economy since has fought the same race. Here the race has nowhere to live: the yield IS the transition `ripe -> harvested`, so the second strike in the lag window has no edge to take. Nodes also wear out — `depleted` is terminal (soma verify proves it), killing infinite-respawn farm spots — and the ore ledger can never go negative.", "url": "https://soma-lang.dev/corpus/games_economy/harvest_node.cell", "repo_path": "examples/corpus/games_economy/harvest_node.cell", "lines": 79, "features": ["state_machine", "invariant", "try"], "cells": ["Mine", "MineTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/loot_roll", "domain": "games_economy", "title": "LOOT ROLL — one roll per raider, one award per drop", "summary": "LOOT ROLL — one roll per raider, one award per drop Raid loot drama is as old as raids: a player spam-clicks \"Need\" and gets two entries in the roll, or a master looter awards the same drop to two friends (\"it bugged, I swear\"). Both killed guilds; the second was a real duping vector when award and mail-out raced. Here each (raider, drop) roll is walled at <= 1 entry by the memory, and the drop itself is a machine: rolling -> awarded is the ONLY award edge and `awarded` is terminal — soma verify proves a drop cannot be handed out twice.", "url": "https://soma-lang.dev/corpus/games_economy/loot_roll.cell", "repo_path": "examples/corpus/games_economy/loot_roll.cell", "lines": 84, "features": ["state_machine", "invariant", "try"], "cells": ["LootRoll", "RollTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/loot_trade", "domain": "games_economy", "title": "LOOT TRADE — an item exists in exactly one inventory, ever", "summary": "LOOT TRADE — an item exists in exactly one inventory, ever Item duplication broke Diablo II's economy so completely that duped Stones of Jordan became the server currency. Most dupes had one shape: a trade that crashed or desynced mid-swap left the item in BOTH inventories. Here that shape is unrepresentable. Ownership is a single registry entry (one item -> one owner), the copy counter is walled at <= 1 by the memory itself — a second copy of an item id CANNOT BE STORED — and a trade is a machine soma verify proves: `executed` and `withdrawn` are terminal, so a completed swap can never replay.", "url": "https://soma-lang.dev/corpus/games_economy/loot_trade.cell", "repo_path": "examples/corpus/games_economy/loot_trade.cell", "lines": 101, "features": ["state_machine", "invariant", "try"], "cells": ["TradePost", "TradeTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/pity_banner", "domain": "games_economy", "title": "PITY BANNER — the 90-pull guarantee that cannot be skipped Gacha games promise a \"pity timer\": a guaranteed top-rarity drop by pull 90", "summary": "PITY BANNER — the 90-pull guarantee that cannot be skipped Gacha games promise a \"pity timer\": a guaranteed top-rarity drop by pull 90. When the counter resets wrongly — and players HAVE caught smaller gachas dropping pity across banner switches, via crowd-sourced drop statistics — it is a consumer-protection violation: people paid for odds they did not get. Here the promise is not in the drop code. The counter lives behind `invariant pity <= 89`: a 90th consecutive miss CANNOT BE STORED. The only write that survives at 89 misses is the reset that arrives together with the guaranteed legendary.", "url": "https://soma-lang.dev/corpus/games_economy/pity_banner.cell", "repo_path": "examples/corpus/games_economy/pity_banner.cell", "lines": 73, "features": ["invariant"], "cells": ["Banner", "BannerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "3 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "games_economy/season_ladder", "domain": "games_economy", "title": "SEASONAL LADDER — decay you cannot dodge, ratings that cannot underflow Two real ladder failures", "summary": "SEASONAL LADDER — decay you cannot dodge, ratings that cannot underflow Two real ladder failures. One: integer underflow on rating loss minted players with astronomical \"unsigned\" MMR on early third-party CS ladders. Two: operators quietly editing ARCHIVED seasons, retroactively changing who earned rewards. Here the rating lives behind a 0..3000 memory invariant — no underflow, no injected over-cap — and the season is a machine soma verify proves: gains only while `active`, decay only inside the `decaying` window, and `archived` is terminal. History cannot be edited.", "url": "https://soma-lang.dev/corpus/games_economy/season_ladder.cell", "repo_path": "examples/corpus/games_economy/season_ladder.cell", "lines": 98, "features": ["state_machine", "invariant", "try"], "cells": ["Ladder", "LadderTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/stamina", "domain": "games_economy", "title": "STAMINA — the energy bar that cannot be overfilled or driven negative Mobile-game energy systems are attacked two ways", "summary": "STAMINA — the energy bar that cannot be overfilled or driven negative Mobile-game energy systems are attacked two ways. Clock rollback: set the device clock forward, bank the regen, roll it back, regen again. Spend underflow: spend more than you have and an unsigned wrap leaves you with ~4 billion energy — this shipped in more than one free-to-play title. Both attacks are, at bottom, a write outside [0, 100]. Here the MEMORY refuses them: energy past the cap or below zero is not a bug to catch, it is a value that cannot be stored.", "url": "https://soma-lang.dev/corpus/games_economy/stamina.cell", "repo_path": "examples/corpus/games_economy/stamina.cell", "lines": 68, "features": ["invariant", "try"], "cells": ["Stamina", "StaminaTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "2 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "games_economy/tournament_bracket", "domain": "games_economy", "title": "TOURNAMENT BRACKET — eliminated means eliminated", "summary": "TOURNAMENT BRACKET — eliminated means eliminated Online tournament platforms keep having bracket-integrity incidents: an admin \"fixes\" a reported result and a knocked-out player reappears in the semifinals, or a player skips a round entirely. Fighting-game brackets on early smash.gg/Challonge saw enough of this that audit logs were added. The integrity rule is structural here: ELIMINATION IS PERMANENT, CHAMPION IS FINAL, and the only way into a round is winning the previous one. and no edge skips a round.", "url": "https://soma-lang.dev/corpus/games_economy/tournament_bracket.cell", "repo_path": "examples/corpus/games_economy/tournament_bracket.cell", "lines": 73, "features": ["state_machine", "match", "try"], "cells": ["Bracket", "BracketTests"], "usage": ["soma verify proves it: `eliminated` and `champion` have no outgoing edges,"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/veterancy_ranks", "domain": "games_economy", "title": "VETERANCY RANKS — promotion is earned and can never be rolled back", "summary": "VETERANCY RANKS — promotion is earned and can never be rolled back Competitive games have shipped both halves of this bug: rank-rollback (disconnect during the promotion screen and log back in demoted — Halo and several ladder games paid out compensation waves for it) and rank-injection (a modified client reports Grandmaster and the server believes it). Both are writes the server should never accept. Here XP is walled into 0..100000 — no death-penalty underflow, no injected overflow — and rank is a FORWARD-ONLY machine: novice -> adept -> master -> grandmaster. soma verify proves there are no demotion edges and that grandmaster is terminal: a rank, once earned, is permanent.", "url": "https://soma-lang.dev/corpus/games_economy/veterancy_ranks.cell", "repo_path": "examples/corpus/games_economy/veterancy_ranks.cell", "lines": 92, "features": ["state_machine", "invariant", "try"], "cells": ["Veterancy", "RankTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "games_economy/wager_duel", "domain": "games_economy", "title": "WAGER DUEL — staked gold that exactly one fighter can win", "summary": "WAGER DUEL — staked gold that exactly one fighter can win Wager duels and \"death-match stakes\" servers keep reproducing the same scam: both fighters stake gold, the loser disconnects before the result commits, and a support ticket gets the stake refunded — while the winner was ALSO paid. The pot pays out twice. Here the duel is a machine where `paid_out` and `refunded` are both TERMINAL and mutually exclusive: the pot leaves through exactly one door, once. Stakes move wallet -> pot in one handler, gold is conserved across every path, and no wallet can go negative — you cannot stake gold you do not have.", "url": "https://soma-lang.dev/corpus/games_economy/wager_duel.cell", "repo_path": "examples/corpus/games_economy/wager_duel.cell", "lines": 122, "features": ["state_machine", "invariant", "match", "try"], "cells": ["WagerDuel", "DuelTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "15 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/amendment", "domain": "governance", "title": "AMENDMENT — supermajority ratification, and a \"yes\" that cannot be unsaid", "summary": "AMENDMENT — supermajority ratification, and a \"yes\" that cannot be unsaid In 1868, Ohio and New Jersey ratified the Fourteenth Amendment — then, as politics shifted, voted to RESCIND their ratifications. Congress and the Secretary of State counted them anyway: under Article V practice, ratification is a one-way act. The same fight resurfaced with the ERA in the 1970s. The constitutional answer became doctrine: a state's \"yes\" enters the permanent record; there is no take-back. This module makes both halves structural. A ratification slot can hold exactly the value 1 — the rescission (writing it back to 0) is refused by the MEMORY, not by a clerk's ruling. And the amendment cannot reach `ratified` (terminal, proven by soma verify) until a supermajority of 7 of the 10 member states is actually on the books.", "url": "https://soma-lang.dev/corpus/governance/amendment.cell", "repo_path": "examples/corpus/governance/amendment.cell", "lines": 129, "features": ["state_machine", "invariant", "try"], "cells": ["ArticleFive", "AmendmentTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/anti_deficiency", "domain": "governance", "title": "ANTI-DEFICIENCY — no obligation of funds Congress never appropriated The Anti-Deficiency Act (31 U.S.C", "summary": "ANTI-DEFICIENCY — no obligation of funds Congress never appropriated The Anti-Deficiency Act (31 U.S.C. §1341, roots in 1870) exists because 19th-century agencies routinely spent money first and dared Congress to cover the bill — \"coercive deficiencies.\" The Act makes it a federal crime to obligate a dollar in excess of, or in advance of, an appropriation. It is the reason the U.S. government literally shuts down when appropriations lapse: with no enacted appropriation there is no legal way to spend. Both halves are structural here. \"In advance of\": spending handlers gate on the appropriation's lifecycle, and a LAPSED appropriation is terminal — soma verify proves money cannot flow from it again. \"In excess of\": the account balance carries `invariant remaining >= 0`, so the overdraft is not an error code — it is a write the memory refuses, and the balance keeps its last lawful value.", "url": "https://soma-lang.dev/corpus/governance/anti_deficiency.cell", "repo_path": "examples/corpus/governance/anti_deficiency.cell", "lines": 126, "features": ["state_machine", "invariant", "try"], "cells": ["Treasury", "AntiDeficiencyTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/auditor_independence", "domain": "governance", "title": "AUDITOR INDEPENDENCE — one firm, one client, ONE role In 2000, Arthur Andersen billed Enron $25 million for the audit — and $27 million for consulting", "summary": "AUDITOR INDEPENDENCE — one firm, one client, ONE role In 2000, Arthur Andersen billed Enron $25 million for the audit — and $27 million for consulting. The firm certifying the books had a bigger business interest in pleasing management than in challenging it. When Enron collapsed, Andersen's partners were found shredding audit workpapers; the firm itself dissolved, taking 85,000 jobs with it. Sarbanes-Oxley §201 answered by making the dual role itself illegal: a registered public accounting firm may not provide most consulting services to an audit client. Not \"disclose it\" — may not hold both. Here the prohibition is arithmetic. A firm/client pair can hold at most ONE engagement. Signing the audit writes 1; selling consulting to the same client tries to write 2 — and the engagement ledger refuses. The conflict isn't reviewed by an ethics board after the fact; it is a value the books cannot hold. The audit itself runs a machine where `opinion_issued` is terminal: once signed, an opinion cannot be quietly recalled and re-negotiated.", "url": "https://soma-lang.dev/corpus/governance/auditor_independence.cell", "repo_path": "examples/corpus/governance/auditor_independence.cell", "lines": 117, "features": ["state_machine", "invariant", "try"], "cells": ["EngagementLedger", "IndependenceTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/board_motion", "domain": "governance", "title": "BOARD MOTION — Robert's Rules where \"no quorum, no vote\" is structural", "summary": "BOARD MOTION — Robert's Rules where \"no quorum, no vote\" is structural Quorum is the oldest anti-capture device in deliberative bodies: a minority that shows up early cannot bind the whole board. It matters enough that in 2011 fourteen Wisconsin state senators fled to Illinois for three weeks SOLELY to deny the chamber a quorum — denying quorum was the only brake left. Corporate law is harsher: board action taken without quorum is void, not voidable. Courts unwind the merger. Here the brake is not a clerk remembering to count the room. The motion lifecycle (Robert's Rules: moved -> seconded -> voted) is a state machine soma verify proves, `passed`/`failed` are terminal so a resolved motion can never be re-voted, and one-director-one-ballot is a MEMORY invariant — the second ballot is refused at the write.", "url": "https://soma-lang.dev/corpus/governance/board_motion.cell", "repo_path": "examples/corpus/governance/board_motion.cell", "lines": 155, "features": ["state_machine", "invariant", "try"], "cells": ["Boardroom", "MotionTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "15 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/emergency_sunset", "domain": "governance", "title": "EMERGENCY SUNSET — extraordinary powers that cannot become ordinary Egypt declared a state of emergency in 1981 after Sadat's assassination", "summary": "EMERGENCY SUNSET — extraordinary powers that cannot become ordinary Egypt declared a state of emergency in 1981 after Sadat's assassination. It was \"temporarily\" renewed, again and again, for THIRTY-ONE YEARS — a whole generation governed under exception. The pattern is universal enough that modern emergency statutes (and the post-2020 reform wave in U.S. states) all converge on the same two teeth: an emergency expires BY ITSELF unless the legislature acts, and the executive cannot renew it indefinitely on its own signature. Both teeth are structural here. A declaration must be confirmed by the legislature before any power is exercised; `expired` is terminal — soma verify proves a lapsed emergency has no path back to life (you must declare a NEW one, in public, with a new confirmation). And the renewal counter carries `invariant <= 2`: the third renewal of the same declaration is a write the statute book refuses.", "url": "https://soma-lang.dev/corpus/governance/emergency_sunset.cell", "repo_path": "examples/corpus/governance/emergency_sunset.cell", "lines": 136, "features": ["state_machine", "invariant", "try"], "cells": ["EmergencyAct", "SunsetTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/four_eyes_approval", "domain": "governance", "title": "FOUR-EYES APPROVAL — the maker cannot be the checker, by construction", "summary": "FOUR-EYES APPROVAL — the maker cannot be the checker, by construction Wirecard collapsed in 2020 with €1.9 billion that never existed; for years the same small circle that originated transactions also signed off on them. Every controls framework since (SOX, Basel, ISO 27001) demands \"segregation of duties\": the person who drafts a document may not be the person who approves it. Usually that is a checkbox in a workflow tool — deletable, bypassable. Here it is arithmetic the memory enforces. Each document/person pair holds AT MOST ONE role. Authoring writes 1. Approving adds 1. If the author tries to approve their own document the write becomes 2 — and the invariant rejects it. The self-approval is not caught by a check; it is a value the ledger cannot hold.", "url": "https://soma-lang.dev/corpus/governance/four_eyes_approval.cell", "repo_path": "examples/corpus/governance/four_eyes_approval.cell", "lines": 115, "features": ["state_machine", "invariant", "try"], "cells": ["ApprovalChain", "FourEyesTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/grant_milestones", "domain": "governance", "title": "GRANT MILESTONES — money moves only behind verified work, and only once", "summary": "GRANT MILESTONES — money moves only behind verified work, and only once Milestone-based disbursement is how funders stop the oldest grant fraud there is: draw the full award up front, deliver a report nobody reads, dissolve the entity. GAO audits of federal grant programs keep finding the same two failure modes — funds released ahead of the work, and the same milestone paid twice under slightly different paperwork. Clawing money back after the fact almost never works; the only cheap control is at the moment of disbursement. So that moment is where the walls are. The grant walks a machine — each milestone must be verified before the next opens, soma verify proves there is no path around the order. The escrow balance carries `invariant >= 0` (you cannot disburse money that is not there) and each milestone pays AT MOST ONCE: the duplicate-invoice write is refused by the ledger itself.", "url": "https://soma-lang.dev/corpus/governance/grant_milestones.cell", "repo_path": "examples/corpus/governance/grant_milestones.cell", "lines": 148, "features": ["state_machine", "invariant", "try"], "cells": ["GrantEscrow", "EscrowTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/judicial_recusal", "domain": "governance", "title": "JUDICIAL RECUSAL — a conflicted judge cannot sit, and cases aren't shopped Caperton v", "summary": "JUDICIAL RECUSAL — a conflicted judge cannot sit, and cases aren't shopped Caperton v. A.T. Massey Coal (2009): while a $50M verdict against Massey was heading to West Virginia's Supreme Court, Massey's CEO spent $3M electing Justice Brent Benjamin to that court. Benjamin refused to recuse himself — twice — and cast the deciding vote to overturn the verdict. The U.S. Supreme Court held the Due Process Clause itself required recusal. The lesson: recusal cannot be left to the conflicted judge's own discretion. Here the conflicts register is consulted by the assignment machinery, not by the judge's conscience. And the second classic abuse — judge shopping, reassigning a case until a friendly bench appears — is a memory invariant: one case, one assignment, ever. The second assignment is a write the docket refuses.", "url": "https://soma-lang.dev/corpus/governance/judicial_recusal.cell", "repo_path": "examples/corpus/governance/judicial_recusal.cell", "lines": 121, "features": ["state_machine", "invariant", "try"], "cells": ["Docket", "RecusalTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/minutes_adoption", "domain": "governance", "title": "MINUTES ADOPTION — the corporate record cannot be edited after the fact", "summary": "MINUTES ADOPTION — the corporate record cannot be edited after the fact The stock-option backdating scandals of 2006 (over 130 companies under SEC investigation, CEOs of Brocade and Comverse criminally charged) ran on one quiet mechanic: board paperwork written or \"fixed\" AFTER the fact, dressed up as the record of an earlier date. Minutes are evidence — Delaware courts treat adopted minutes as the authoritative memory of what a board decided. Their value collapses the moment they can be revised after adoption. So adoption here is a one-way door. Amendments append to a numbered revision trail only while the draft circulates; `adopted` is a terminal state soma verify proves, and the adoption ledger holds at most one adoption per document — a second \"corrected\" adoption of the same minutes is a write the memory refuses.", "url": "https://soma-lang.dev/corpus/governance/minutes_adoption.cell", "repo_path": "examples/corpus/governance/minutes_adoption.cell", "lines": 115, "features": ["state_machine", "invariant", "try"], "cells": ["MinuteBook", "MinuteBookTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/open_meetings", "domain": "governance", "title": "OPEN MEETINGS — no public decision without public notice, structurally Every U.S", "summary": "OPEN MEETINGS — no public decision without public notice, structurally Every U.S. state has a Sunshine law because councils kept doing the same thing: decide in private, ratify in public. Texas's Open Meetings Act requires 72 hours of posted notice before a governmental body may act; actions taken in an unnoticed meeting are voidable, and courts have voided them — bond issues, firings, rezonings. The dodge du jour is the \"walking quorum\": a chain of small private chats that adds up to a deliberating majority no citizen ever saw. Here the Act is the machine. A meeting reaches `in_session` ONLY through `noticed`, and the notice ledger physically cannot record a posting shorter than 72 hours — `invariant notice_hours >= 72` makes the midnight 2-hour notice a write the memory refuses. Votes happen only in session; `adjourned` is terminal, so nothing can be slipped into a meeting after the gavel falls.", "url": "https://soma-lang.dev/corpus/governance/open_meetings.cell", "repo_path": "examples/corpus/governance/open_meetings.cell", "lines": 118, "features": ["state_machine", "invariant", "try"], "cells": ["SunshineLaw", "SunshineTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/peer_review", "domain": "governance", "title": "PEER REVIEW — double-blind where the blind cannot be lifted early", "summary": "PEER REVIEW — double-blind where the blind cannot be lifted early Double-blind review exists because the data says it must: when reviewers see author names, papers from famous labs are accepted at measurably higher rates (the NeurIPS 2014 and 2021 consistency experiments put numbers on how noisy and biased single-blind judging is). The whole mechanism collapses on two failure modes: an author reviewing their own paper under a conflict, and the author's identity leaking to the reviewer BEFORE the decision is locked. Both are structural here. A reviewer/author pair can hold at most one role on a paper — self-review is a write the memory refuses. And `unmasked` is reachable ONLY from `decided`: there is no edge from any pre-decision state to the unmasked world. soma verify proves it.", "url": "https://soma-lang.dev/corpus/governance/peer_review.cell", "repo_path": "examples/corpus/governance/peer_review.cell", "lines": 132, "features": ["state_machine", "invariant", "try"], "cells": ["ReviewDesk", "BlindTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/release_pipeline", "domain": "governance", "title": "RELEASE PIPELINE — \"tests pass before deploy\" as a theorem, not a habit", "summary": "RELEASE PIPELINE — \"tests pass before deploy\" as a theorem, not a habit On August 1, 2012, Knight Capital deployed new trading code to seven of eight production servers. The eighth still ran a dead code path that the new deploy re-activated by reusing its feature flag. In 45 minutes Knight bought and sold $7 billion of stock it didn't want and lost $440 million — the firm was sold within the year. The SEC's post-mortem: no enforced deployment process. A human checklist, partly followed. Below, the pipeline is a state machine: production is reachable ONLY through green tests and a human approval, soma verify proves no other path exists, and the deploy ledger lets each build artifact reach production AT MOST ONCE — re-pushing a rolled-back artifact (Knight's exact sin: stale code reactivated) is a write the memory refuses.", "url": "https://soma-lang.dev/corpus/governance/release_pipeline.cell", "repo_path": "examples/corpus/governance/release_pipeline.cell", "lines": 133, "features": ["state_machine", "invariant", "try"], "cells": ["Pipeline", "PipelineTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/sealed_bids", "domain": "governance", "title": "SEALED BIDS — the envelope opens once, for everyone, after the deadline", "summary": "SEALED BIDS — the envelope opens once, for everyone, after the deadline Public procurement runs on sealed bidding because the alternative is what the DOJ Antitrust Division prosecutes every year: a contracting insider leaks competitor numbers to a favored vendor, who underbids by a dollar. Whole construction markets have been rigged this way. The integrity property is precise: NO bid is readable while the window is open, late bids do not exist, and once the envelopes open the window can never quietly re-open to slip a friend's bid in afterward. Here the envelope is the state machine: bids land only in `accepting`, numbers are served only past `opened`, and the opening is IRREVERSIBLE — soma verify proves no edge leads back. One vendor, one bid, is a memory invariant: the amended-after-peeking second bid is refused at the write.", "url": "https://soma-lang.dev/corpus/governance/sealed_bids.cell", "repo_path": "examples/corpus/governance/sealed_bids.cell", "lines": 131, "features": ["state_machine", "invariant", "try"], "cells": ["BidRoom", "SealedBidTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/term_limits", "domain": "governance", "title": "TERM LIMITS — the third term is not forbidden, it is unrepresentable", "summary": "TERM LIMITS — the third term is not forbidden, it is unrepresentable In 2008, New York's City Council — at Mayor Bloomberg's urging — voted 29-22 to extend its own term limits so the sitting mayor could run again, overriding two public referenda in which New Yorkers had twice voted for a two-term cap. It was legal precisely because the limit lived in an ordinary statute the limited officials themselves could amend. The U.S. answer to FDR's four terms was different: the 22nd Amendment put the cap somewhere no incumbent can reach. This module is the 22nd-Amendment version. The terms ledger carries `invariant terms <= 2` — certifying a third term for the same person is a WRITE THE MEMORY REFUSES, and there is no handler anywhere that can loosen an invariant at runtime. Each term also walks a machine whose `vacated` state is terminal: an ended term cannot be revived as a sneaky continuation of itself.", "url": "https://soma-lang.dev/corpus/governance/term_limits.cell", "repo_path": "examples/corpus/governance/term_limits.cell", "lines": 128, "features": ["state_machine", "invariant", "try"], "cells": ["TermRegistry", "TermLimitTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/three_readings", "domain": "governance", "title": "THREE READINGS — an ordinance cannot be law the night it is introduced", "summary": "THREE READINGS — an ordinance cannot be law the night it is introduced Most municipal charters require an ordinance to be read at three separate council meetings before adoption. The rule is anti-ambush: the public gets two full meeting cycles to notice, organize, and object before anything binds them. The standard evasion is the \"emergency clause\" — Ohio councils became notorious for passing garden-variety zoning as an \"emergency\" to skip readings and, not coincidentally, to dodge the citizen referendum that attaches to normal ordinances. In this machine the readings are not a custom the clerk remembers — they are the only path. `adopted` is reachable solely through three reading states, soma verify proves no shortcut edge exists, and each reading can be logged at most once per ordinance stage: stuffing all three readings into one wild night is a write the journal refuses.", "url": "https://soma-lang.dev/corpus/governance/three_readings.cell", "repo_path": "examples/corpus/governance/three_readings.cell", "lines": 145, "features": ["state_machine", "invariant", "try", "fail"], "cells": ["CouncilJournal", "ReadingsTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "governance/whistleblower_shield", "domain": "governance", "title": "WHISTLEBLOWER SHIELD — retaliation against a reporter is unrepresentable", "summary": "WHISTLEBLOWER SHIELD — retaliation against a reporter is unrepresentable Sherron Watkins warned Ken Lay about Enron's accounting in August 2001; within days, Enron's lawyers were researching \"the consequences of terminating\" her. That memo is why Sarbanes-Oxley §806 exists: any adverse employment action against a corporate whistleblower — firing, demotion, the quiet bad shift — is unlawful retaliation. Yet OSHA's docket shows it still happens constantly, because the protection lives in a policy document while the termination lives in the HR system. Here they live in the same memory. Once a person files a report they are shielded: the adverse-actions ledger for a shielded employee carries `invariant == 0`, so HR's termination write is not flagged for review — it is REFUSED. And the report itself moves through a machine where `substantiated`/`unfounded` are terminal: a closed finding cannot be quietly re-opened to grind a reporter down.", "url": "https://soma-lang.dev/corpus/governance/whistleblower_shield.cell", "repo_path": "examples/corpus/governance/whistleblower_shield.cell", "lines": 119, "features": ["state_machine", "invariant", "try"], "cells": ["ComplianceOffice", "ShieldTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/bonded_warehouse", "domain": "logistics", "title": "BONDED WAREHOUSE — no duty, no exit A customs bonded warehouse holds imported goods on which duty has NOT yet been paid", "summary": "BONDED WAREHOUSE — no duty, no exit A customs bonded warehouse holds imported goods on which duty has NOT yet been paid. The whole institution rests on one rule: bonded goods leave for the domestic market only after duty is settled, or leave the country entirely (re-export, duty never owed). \"Bond leakage\" — goods slipping into commerce duty-unpaid — is a perennial fraud; the UK lost hundreds of millions of pounds a year to bonded alcohol diversion in the 1990s \"London City Bond\" scandal, where paperwork showed exports that never left the island. Structurally: `domestic_market` is reachable ONLY through `duty_paid`, `re_exported` is terminal, and the duty ledger refuses a release whose payment doesn't cover the assessment. The diversion has no path.", "url": "https://soma-lang.dev/corpus/logistics/bonded_warehouse.cell", "repo_path": "examples/corpus/logistics/bonded_warehouse.cell", "lines": 125, "features": ["state_machine", "invariant", "try"], "cells": ["BondedWarehouse", "NoBondLeakage"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/cold_chain_custody", "domain": "logistics", "title": "COLD-CHAIN CUSTODY — a warm vaccine never gets cold again", "summary": "COLD-CHAIN CUSTODY — a warm vaccine never gets cold again In 2022 the WHO estimated half of all vaccines are wasted globally, much of it to cold-chain failure — and the dangerous half of that is the failure NOBODY LOGS: a pallet of mRNA doses sits on a hot tarmac during a handoff, the temperature recorder is reset, and the shipment continues as if nothing happened. The doses are inert; the syringes still go in. Two structural fixes. Every custody handoff is a recorded transition — no anonymous gaps. And `breached` is a TERMINAL state: the moment any custodian logs an excursion, there is no transition that puts the pallet back on the cold chain. You cannot \"re-chill\" the record. soma verify proves both: every path is named, and breached has no exit.", "url": "https://soma-lang.dev/corpus/logistics/cold_chain_custody.cell", "repo_path": "examples/corpus/logistics/cold_chain_custody.cell", "lines": 105, "features": ["state_machine", "invariant", "try"], "cells": ["ColdChain", "NoRechilledRecords"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/container_seal_custody", "domain": "logistics", "title": "CONTAINER SEAL — a broken seal cannot be quietly replaced", "summary": "CONTAINER SEAL — a broken seal cannot be quietly replaced Europol calls it \"rip-on / rip-off\": corrupted port workers crack a container's bolt seal, pull out a duffel of cocaine stashed among the bananas, and fit a cloned seal before the box hits the gate. The whole scheme depends on the custody record showing an unbroken seal chain — on a mismatch being something an insider can paper over. Antwerp and Rotterdam seize 100+ tonnes a year that DIDN'T get papered over. Here every checkpoint verifies the seal number against the manifest. A match is a recorded hop; a MISMATCH moves the box to `tampered` — a TERMINAL state. There is no transition out: no re-verification, no supervisor override, no quiet reseal. The box ends at inspection, every time, and soma verify proves no path leads back.", "url": "https://soma-lang.dev/corpus/logistics/container_seal_custody.cell", "repo_path": "examples/corpus/logistics/container_seal_custody.cell", "lines": 108, "features": ["state_machine", "invariant", "match", "try"], "cells": ["SealCustody", "NoQuietReseal"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/container_weight", "domain": "logistics", "title": "CONTAINER WEIGHT — the misdeclared box that breaks the ship", "summary": "CONTAINER WEIGHT — the misdeclared box that breaks the ship When the MSC Napoli was beached off Devon in 2007, investigators weighed the containers coming off her deck: 137 of 660 were more than 3 tonnes heavier than their declared weight — one was 20 tonnes over. Misdeclared container weights overload stacks, snap lashings, and capsize feeder ships. The IMO's answer was SOLAS VGM (2016): no verified gross mass, no loading. Period. Here the rule is structural. A container's gross mass lives behind a memory invariant capped at the ISO max for a 40-foot box (30,480 kg): the write that would overload it is REFUSED by the memory itself, and a container only reaches the `laden_aboard` state through `vgm_certified` — there is no path from packing straight onto the ship.", "url": "https://soma-lang.dev/corpus/logistics/container_weight.cell", "repo_path": "examples/corpus/logistics/container_weight.cell", "lines": 97, "features": ["state_machine", "invariant", "try"], "cells": ["ContainerYard", "SolasVgm"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/customs_clearance", "domain": "logistics", "title": "CUSTOMS CLEARANCE — no release without an examination verdict", "summary": "CUSTOMS CLEARANCE — no release without an examination verdict The 2019 Philadelphia seizure of 17.5 tonnes of cocaine aboard the MSC Gayane worked because the containers were HELD at the port until CBP finished examining them. The failure mode customs agencies fear is the opposite: a \"port runner\" — cargo that leaves the terminal while its entry is still under review, or after a seizure order. Once goods are on a truck, the border has already failed. This lifecycle makes the run impossible in the record system: `released` is reachable ONLY from `cleared`, an exam hold must return a verdict before anything moves, and `seized` is TERMINAL — a seizure order can never be walked back to circulation. soma verify proves all three.", "url": "https://soma-lang.dev/corpus/logistics/customs_clearance.cell", "repo_path": "examples/corpus/logistics/customs_clearance.cell", "lines": 112, "features": ["state_machine", "invariant", "try"], "cells": ["Customs", "NoPortRunners"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/dock_door_interlock", "domain": "logistics", "title": "DOCK DOOR INTERLOCK — the trailer that drives off with the forklift", "summary": "DOCK DOOR INTERLOCK — the trailer that drives off with the forklift OSHA logs several deaths a year from one warehouse scenario: a driver, thinking loading is done, pulls the trailer away from the dock while a forklift is still crossing the dock plate. The forklift drops through the gap — operators have been crushed under their own machines. The industry fix is a vehicle restraint (a hook that grabs the trailer's rear bar) interlocked with the dock door. In ladder logic that interlock is wiring you hope is right. Here it is a theorem: the door can only be open in the `loading` state, and `loading` is only reachable with the restraint LOCKED. The trailer can only depart from `trailer_at_door` — restraint off, door closed. The state \"door open, trailer free to move\" does not exist to race into.", "url": "https://soma-lang.dev/corpus/logistics/dock_door_interlock.cell", "repo_path": "examples/corpus/logistics/dock_door_interlock.cell", "lines": 86, "features": ["state_machine", "try"], "cells": ["DockDoor", "RestraintInterlock"], "verified": {"check": true, "test": true, "verify": true}, "verify": "5 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/gate_appointment", "domain": "logistics", "title": "GATE APPOINTMENTS — a dock door cannot be double-booked", "summary": "GATE APPOINTMENTS — a dock door cannot be double-booked When the ports of LA and Long Beach gridlocked in 2021, a big share of the chaos was appointment churn: terminal systems double-booking gate slots, two trucks arriving for one window, one of them idling for hours and missing its next pickup. Inland, the same bug at a grocery DC means a reefer truck of frozen food waits in the yard burning diesel — detention fees run $50-100 an hour and the cold chain ticks. The scheduling rule here is not a uniqueness check in application code someone can bypass with a second code path. It is a memory invariant: each door-hour slot holds AT MOST ONE booking, and the second write to the same slot is refused by the memory itself.", "url": "https://soma-lang.dev/corpus/logistics/gate_appointment.cell", "repo_path": "examples/corpus/logistics/gate_appointment.cell", "lines": 100, "features": ["invariant"], "cells": ["GateSchedule", "OneTruckPerWindow"], "verified": {"check": true, "test": true, "verify": true}, "verify": "2 passed, 0 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "logistics/hazmat_bay_segregation", "domain": "logistics", "title": "HAZMAT BAY SEGREGATION — Beirut, as a state that cannot exist", "summary": "HAZMAT BAY SEGREGATION — Beirut, as a state that cannot exist On 4 August 2020, 2,750 tonnes of ammonium nitrate stored for six years in Beirut's Hangar 12 — alongside a cache of FIREWORKS — detonated and killed more than 200 people. Tianjin 2015 was the same story: oxidizers warehoused next to fuels, 173 dead. Every dangerous-goods code on earth (IMDG, NFPA 400) says the same thing: oxidizers and flammables never share a bay. And in both cities, the paperwork said they did anyway. Here the bay is a state machine with NO mixed state: a bay holds oxidizer, or flammables, or nothing. The state \"both\" is not refused — it is unrepresentable, and soma verify proves the reachable set. A tonnage invariant caps any single bay at 25 t of oxidizer: a 2,750-tonne Hangar 12 cannot be written into this ledger at all.", "url": "https://soma-lang.dev/corpus/logistics/hazmat_bay_segregation.cell", "repo_path": "examples/corpus/logistics/hazmat_bay_segregation.cell", "lines": 120, "features": ["state_machine", "invariant", "try"], "cells": ["HazmatBay", "Hangar12CannotHappen"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/inventory_conservation", "domain": "logistics", "title": "INVENTORY CONSERVATION — stock never teleports, never goes negative", "summary": "INVENTORY CONSERVATION — stock never teleports, never goes negative \"Phantom inventory\" costs retail roughly a quarter of a trillion dollars a year: the system says 12 units, the shelf has none, and replenishment never triggers because the ghost stock looks fine. The classic cause is an unbalanced transfer — a warehouse decrements, the receiving store's increment is lost (crash, double-click, integration retry), and the books drift from the world one transaction at a time. Here a transfer is one handler that does BOTH sides or NEITHER, and the memory refuses any write that would drive a site negative — the units for an oversized transfer simply do not exist to send. Conservation (total units constant across any transfer) is pinned by the tests.", "url": "https://soma-lang.dev/corpus/logistics/inventory_conservation.cell", "repo_path": "examples/corpus/logistics/inventory_conservation.cell", "lines": 92, "features": ["invariant", "pipeline", "try", "lambda"], "cells": ["StockLedger", "NothingTeleports"], "verified": {"check": true, "test": true, "verify": true}, "verify": "2 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "logistics/package_tracking", "domain": "logistics", "title": "PACKAGE TRACKING — delivered is FOREVER", "summary": "PACKAGE TRACKING — delivered is FOREVER Couriers under per-stop quotas have been caught marking parcels \"delivered\" early, then quietly reverting the scan and dropping the box a day later — or never. Amazon, FedEx and UPS all field thousands of \"marked delivered, never arrived\" claims a year, and every fraudulent rewrite depends on one thing: the tracking record being MUTABLE. Here the journey is a verified state machine and `delivered` is a TERMINAL state: no outgoing transitions exist, so no handler — and no \"corrected\" rescan — can ever pull a delivered parcel back into transit. A failed doorstep attempt legally loops back to the depot; history rewriting does not. `soma verify` proves it.", "url": "https://soma-lang.dev/corpus/logistics/package_tracking.cell", "repo_path": "examples/corpus/logistics/package_tracking.cell", "lines": 84, "features": ["state_machine", "invariant", "try"], "cells": ["PackageTracker", "DeliveredIsForever"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/proof_of_delivery", "domain": "logistics", "title": "PROOF OF DELIVERY — no signature, no \"delivered\"", "summary": "PROOF OF DELIVERY — no signature, no \"delivered\" Last-mile drivers paid per stop, racing a routing app's countdown, have a known shortcut: scan \"delivered\" from the van and toss the parcel — or never deliver it at all. Carrier audits call these \"phantom deliveries\"; for high-value freight (pharma, electronics) the missing proof-of-delivery turns straight into chargebacks and theft claims that the shipper, not the courier, eats. The fix is sequencing made structural: `delivered` is reachable ONLY from `pod_captured`, and capturing a POD requires being physically at the stop (`at_door`). A driver still in `en_route` has no transition — not a forbidden one, a NONEXISTENT one — that marks the box delivered. `delivered` and `returned_undeliverable` are terminal; verify proves it.", "url": "https://soma-lang.dev/corpus/logistics/proof_of_delivery.cell", "repo_path": "examples/corpus/logistics/proof_of_delivery.cell", "lines": 105, "features": ["state_machine", "try"], "cells": ["LastMile", "NoPhantomDeliveries"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/rack_slot_capacity", "domain": "logistics", "title": "RACK SLOT CAPACITY — the pallet that brings down the aisle Warehouse racking collapses kill", "summary": "RACK SLOT CAPACITY — the pallet that brings down the aisle Warehouse racking collapses kill. When a beam rated for 1,000 kg takes a 1,400 kg pallet, it doesn't fail politely — it buckles, sheds its load into the next bay, and entire aisles domino (the 2018 collapse at an English cold store buried a worker under hundreds of pallets; SEMA logs dozens of such collapses a year). The root cause is almost always the same: the WMS happily recorded a put-away the steel could not hold. Here the beam rating is a memory invariant. The put-away that would overload bay steel is not logged-and-regretted; the write itself is REFUSED, so the WMS record can never describe an overloaded beam.", "url": "https://soma-lang.dev/corpus/logistics/rack_slot_capacity.cell", "repo_path": "examples/corpus/logistics/rack_slot_capacity.cell", "lines": 85, "features": ["invariant", "try"], "cells": ["RackBay", "BeamRatingIsLaw"], "verified": {"check": true, "test": true, "verify": true}, "verify": "2 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "logistics/recall_quarantine", "domain": "logistics", "title": "RECALL QUARANTINE — the recalled lot that ships anyway", "summary": "RECALL QUARANTINE — the recalled lot that ships anyway The 2008-09 Peanut Corporation of America scandal: lots that TESTED POSITIVE for salmonella were re-tested until a lab said yes, then shipped. Nine people died, 714 fell ill, and the CEO went to prison for 28 years. The enabling failure was procedural: \"on hold\" was a status field someone could flip back. Here a lot's lifecycle is a verified machine. A recall moves the lot to `quarantined`, and from quarantine the ONLY exits are `destroyed` or `returned_to_supplier` — both TERMINAL. There is no edge back to `sellable`, so no re-test, no override, and no commercial pressure can put a recalled lot back on a truck. soma verify proves the absence.", "url": "https://soma-lang.dev/corpus/logistics/recall_quarantine.cell", "repo_path": "examples/corpus/logistics/recall_quarantine.cell", "lines": 110, "features": ["state_machine", "invariant", "try"], "cells": ["RecallControl", "PcaCannotHappen"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/reefer_setpoint", "domain": "logistics", "title": "REEFER SETPOINT — the typo that thaws forty tonnes of tuna", "summary": "REEFER SETPOINT — the typo that thaws forty tonnes of tuna Refrigerated containers are programmed by hand at the terminal: a tech keys the setpoint from the booking sheet. The classic, expensive typo is sign and unit confusion — +18 instead of -18 (cargo claims files are full of them), or a Fahrenheit value keyed into a Celsius controller. Frozen tuna, ice cream, plasma: one transposed character and the claim runs to hundreds of thousands of dollars, discovered three weeks later at the destination port. This controller's setpoint memory carries the frozen-cargo envelope as an invariant: nothing outside [-30, -10] C can ever BE the setpoint. The +18 typo isn't caught by a validator someone forgot to call on one code path — the memory itself refuses, and the reefer keeps its last safe value. Power state is a verified machine: you cannot program a unit that isn't on, and a tripped unit must be inspected before reuse.", "url": "https://soma-lang.dev/corpus/logistics/reefer_setpoint.cell", "repo_path": "examples/corpus/logistics/reefer_setpoint.cell", "lines": 111, "features": ["state_machine", "invariant", "try"], "cells": ["ReeferController", "FrozenEnvelope"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "logistics/uld_loadmaster", "domain": "logistics", "title": "ULD LOADMASTER — National Airlines 102, refused at the manifest", "summary": "ULD LOADMASTER — National Airlines 102, refused at the manifest On 29 April 2013, National Airlines Flight 102 lifted off from Bagram with five armored vehicles strapped to its main deck. At rotation, at least one 12-tonne MRAP broke loose, slid aft, smashed the jackscrew of the horizontal stabilizer — and the 747 stalled onto the runway, killing all seven crew. The NTSB found the cargo was restrained by a scheme the operator had invented, far below the required tie-down strength, and the load was never properly verified. This loadmaster makes both failures structural: a unit load device's weight ledger refuses any write past the position's certified limit, and the pallet lifecycle has no path onto the aircraft that skips `restraints_verified`. An unverified pallet cannot board — the edge does not exist.", "url": "https://soma-lang.dev/corpus/logistics/uld_loadmaster.cell", "repo_path": "examples/corpus/logistics/uld_loadmaster.cell", "lines": 111, "features": ["state_machine", "invariant", "try"], "cells": ["UldLoadmaster", "Bagram102"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "math/bisection_root", "domain": "math", "title": "Bisection — bracket a root of a continuous function and halve", "summary": "Bisection — bracket a root of a continuous function and halve Given a bracket [a,b] with f(a)·f(b) < 0, the root lies between them; halve the interval toward whichever sub-bracket keeps the sign change. Converges linearly but never diverges. Here f(x) = x² − 2, whose positive root is √2.", "url": "https://soma-lang.dev/corpus/math/bisection_root.cell", "repo_path": "examples/corpus/math/bisection_root.cell", "lines": 61, "features": ["native"], "cells": ["BisectionRoot", "BisectTests"], "usage": ["soma run bisection_root.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/combinatorics", "domain": "math", "title": "Combinatorics — factorial, permutations, combinations factorial folds product over range(1, n+1)", "summary": "Combinatorics — factorial, permutations, combinations factorial folds product over range(1, n+1). nPr = n!/(n-r)! and nCr = n!/(r!(n-r)!). To stay exact for larger n we compute nCr with a running product instead of three separate factorials. Pascal's identity is the cross-check: C(n,r) = C(n-1,r-1) + C(n-1,r).", "url": "https://soma-lang.dev/corpus/math/combinatorics.cell", "repo_path": "examples/corpus/math/combinatorics.cell", "lines": 64, "features": [], "cells": ["Combinatorics", "ComboTests"], "usage": ["soma run combinatorics.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/complex", "domain": "math", "title": "Complex numbers — records carrying real and imaginary parts Soma has no native complex type, so a Complex is a record { re, im }", "summary": "Complex numbers — records carrying real and imaginary parts Soma has no native complex type, so a Complex is a record { re, im }. Addition is componentwise; multiplication uses the FOIL identity (a+bi)(c+di) = (ac−bd) + (ad+bc)i; modulus is sqrt(re²+im²). Records carry a _type field so is_a recognizes them.", "url": "https://soma-lang.dev/corpus/math/complex.cell", "repo_path": "examples/corpus/math/complex.cell", "lines": 63, "features": [], "cells": ["Complex", "ComplexTests"], "usage": ["soma run complex.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/ext_euclid", "domain": "math", "title": "Extended Euclidean algorithm — Bezout coefficients and modular inverse", "summary": "Extended Euclidean algorithm — Bezout coefficients and modular inverse Beyond the gcd, the extended algorithm finds integers x, y with a·x + b·y = gcd(a, b) (Bezout's identity). When gcd(a, m) = 1, x mod m is the modular inverse of a. Returns a record { g, x, y }.", "url": "https://soma-lang.dev/corpus/math/ext_euclid.cell", "repo_path": "examples/corpus/math/ext_euclid.cell", "lines": 70, "features": [], "cells": ["ExtEuclid", "ExtEuclidTests"], "usage": ["soma run ext_euclid.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/fibonacci", "domain": "math", "title": "Fibonacci — iterative, and the closed-form Binet approximation The iterative version carries the last two terms in two variables", "summary": "Fibonacci — iterative, and the closed-form Binet approximation The iterative version carries the last two terms in two variables. Binet's formula F(n) = (phi^n − psi^n)/√5 gives a closed form; we round it back to the exact integer for small n. Both agree, which the tests cross-check.", "url": "https://soma-lang.dev/corpus/math/fibonacci.cell", "repo_path": "examples/corpus/math/fibonacci.cell", "lines": 66, "features": [], "cells": ["Fibonacci", "FibTests"], "usage": ["soma run fibonacci.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/gcd_lcm", "domain": "math", "title": "GCD / LCM — Euclid's algorithm and its consequences gcd() is a builtin (Euclid on absolute values)", "summary": "GCD / LCM — Euclid's algorithm and its consequences gcd() is a builtin (Euclid on absolute values). lcm(a,b) = a*b / gcd(a,b). gcd_list folds the builtin across a whole list with reduce. Coprimality is just gcd == 1.", "url": "https://soma-lang.dev/corpus/math/gcd_lcm.cell", "repo_path": "examples/corpus/math/gcd_lcm.cell", "lines": 54, "features": ["pipeline", "lambda"], "cells": ["GcdLcm", "GcdTests"], "usage": ["soma run gcd_lcm.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/integration", "domain": "math", "title": "Numerical integration — trapezoidal and Simpson's rule Approximate the area under f over [a,b] with n panels", "summary": "Numerical integration — trapezoidal and Simpson's rule Approximate the area under f over [a,b] with n panels. The trapezoid rule averages the endpoints of each panel; Simpson's rule fits parabolas and is exact for cubics. Here f(x) = x², whose integral over [0,1] is 1/3.", "url": "https://soma-lang.dev/corpus/math/integration.cell", "repo_path": "examples/corpus/math/integration.cell", "lines": 66, "features": ["native"], "cells": ["Integration", "IntegrationTests"], "usage": ["soma run integration.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/linear_solve", "domain": "math", "title": "Solving 2x2 linear systems — Cramer's rule via determinants", "summary": "Solving 2x2 linear systems — Cramer's rule via determinants For A·x = b with A 2x2, Cramer's rule gives x_i = det(A_i)/det(A), where A_i is A with column i replaced by b. det() is the matrix builtin. A zero determinant means the system is singular (no unique solution).", "url": "https://soma-lang.dev/corpus/math/linear_solve.cell", "repo_path": "examples/corpus/math/linear_solve.cell", "lines": 46, "features": [], "cells": ["LinearSolve", "SolveTests"], "usage": ["soma run linear_solve.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/matrix_algebra", "domain": "math", "title": "Matrix algebra — product, transpose, determinant, trace Matrices are List<List<Float>> built by reshape", "summary": "Matrix algebra — product, transpose, determinant, trace Matrices are List<List<Float>> built by reshape. `*` is matmul, `.T` is transpose, det() is the determinant (LU with pivoting), diag_sum() the trace. Soma has no structural list ==, so we probe results by index/det.", "url": "https://soma-lang.dev/corpus/math/matrix_algebra.cell", "repo_path": "examples/corpus/math/matrix_algebra.cell", "lines": 56, "features": [], "cells": ["MatrixAlgebra", "MatrixTests"], "usage": ["soma run matrix_algebra.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/modular", "domain": "math", "title": "Modular arithmetic — fast exponentiation and Fermat primality pow_mod(base, exp, m) is a builtin doing square-and-multiply mod m", "summary": "Modular arithmetic — fast exponentiation and Fermat primality pow_mod(base, exp, m) is a builtin doing square-and-multiply mod m. Fermat's little theorem: if p is prime then a^(p-1) ≡ 1 (mod p) for any a coprime to p. We use it as a probable-prime witness. modinv finds a^-1 via Fermat when the modulus is prime: a^(p-2) mod p.", "url": "https://soma-lang.dev/corpus/math/modular.cell", "repo_path": "examples/corpus/math/modular.cell", "lines": 54, "features": [], "cells": ["Modular", "ModularTests"], "usage": ["soma run modular.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/monte_carlo_pi", "domain": "math", "title": "Monte Carlo — estimate pi by dart-throwing Throw random points into the unit square; the fraction landing inside the quarter circle (x²+y² ≤ 1) approaches pi/4", "summary": "Monte Carlo — estimate pi by dart-throwing Throw random points into the unit square; the fraction landing inside the quarter circle (x²+y² ≤ 1) approaches pi/4. random() is the time-seeded PRNG — flagged nondeterministic for `soma replay`, so the estimate varies run-to-run. The test asserts only that the estimate is in a loose band.", "url": "https://soma-lang.dev/corpus/math/monte_carlo_pi.cell", "repo_path": "examples/corpus/math/monte_carlo_pi.cell", "lines": 44, "features": [], "cells": ["MonteCarloPi", "MonteCarloTests"], "usage": ["soma run monte_carlo_pi.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/newton_sqrt", "domain": "math", "title": "Newton's method — square root and reciprocal without division/sqrt", "summary": "Newton's method — square root and reciprocal without division/sqrt sqrt(a) is the positive root of f(x) = x² − a; Newton's iteration becomes the Babylonian update x ← (x + a/x) / 2. The reciprocal 1/a is the root of f(x) = 1/x − a, giving x ← x·(2 − a·x) — a multiply-only iteration.", "url": "https://soma-lang.dev/corpus/math/newton_sqrt.cell", "repo_path": "examples/corpus/math/newton_sqrt.cell", "lines": 67, "features": ["native"], "cells": ["NewtonSqrt", "NewtonTests"], "usage": ["soma run newton_sqrt.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/primes", "domain": "math", "title": "Primes — primality test, prime list, factorization Trial division up to √n decides primality", "summary": "Primes — primality test, prime list, factorization Trial division up to √n decides primality. primes_up_to collects them into a list. factorize peels off prime factors smallest-first. Everything stays in plain Int arithmetic with while loops.", "url": "https://soma-lang.dev/corpus/math/primes.cell", "repo_path": "examples/corpus/math/primes.cell", "lines": 76, "features": [], "cells": ["Primes", "PrimeTests"], "usage": ["soma run primes.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/quadratic", "domain": "math", "title": "Quadratic equations — discriminant and the two real roots", "summary": "Quadratic equations — discriminant and the two real roots For ax² + bx + c = 0 the discriminant D = b² − 4ac decides the root count: D > 0 two real roots, D == 0 one repeated, D < 0 none real. Vieta's relations cross-check: roots sum to −b/a and multiply to c/a.", "url": "https://soma-lang.dev/corpus/math/quadratic.cell", "repo_path": "examples/corpus/math/quadratic.cell", "lines": 54, "features": [], "cells": ["Quadratic", "QuadraticTests"], "usage": ["soma run quadratic.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/series", "domain": "math", "title": "Power series — e via 1/k!, and pi via the Leibniz / Nilakantha series e = Σ 1/k!", "summary": "Power series — e via 1/k!, and pi via the Leibniz / Nilakantha series e = Σ 1/k! converges fast (factorial denominator). The Leibniz series pi = 4·Σ (−1)^k/(2k+1) converges painfully slowly; Nilakantha's 3 + 4·Σ (−1)^k / (2k(2k+1)(2k+2)) is far quicker. We carry the factorial incrementally to avoid recomputing it each term.", "url": "https://soma-lang.dev/corpus/math/series.cell", "repo_path": "examples/corpus/math/series.cell", "lines": 75, "features": ["native"], "cells": ["Series", "SeriesTests"], "usage": ["soma run series.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/statistics", "domain": "math", "title": "Descriptive statistics — mean, variance, stddev, median via sort Mean is sum/len", "summary": "Descriptive statistics — mean, variance, stddev, median via sort Mean is sum/len. Variance is the mean of squared deviations. Median sorts the sample and takes the middle (or the average of the two middles for an even count). All of it rides on list reductions and bracket indexing.", "url": "https://soma-lang.dev/corpus/math/statistics.cell", "repo_path": "examples/corpus/math/statistics.cell", "lines": 69, "features": ["pipeline", "lambda"], "cells": ["Statistics", "StatTests"], "usage": ["soma run statistics.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "math/vector_ops", "domain": "math", "title": "Vector operations — dot product, norm, cosine similarity Vectors are plain lists", "summary": "Vector operations — dot product, norm, cosine similarity Vectors are plain lists. dot() zips two lists and sums the pairwise products; norm is sqrt of the self-dot; cosine similarity normalizes the dot by the product of the norms. Reductions (sum) and zip do the work.", "url": "https://soma-lang.dev/corpus/math/vector_ops.cell", "repo_path": "examples/corpus/math/vector_ops.cell", "lines": 56, "features": ["pipeline", "lambda"], "cells": ["VectorOps", "VectorTests"], "usage": ["soma run vector_ops.cell run"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "medical/bloodbank", "domain": "medical", "title": "BLOOD BANK — an ABO-incompatible transfusion is unrepresentable, and", "summary": "BLOOD BANK — an ABO-incompatible transfusion is unrepresentable, and you cannot issue a unit you do not have Acute hemolytic transfusion reaction — giving group A blood to a group O patient — is one of the few transfusion errors that kills within minutes. It is almost always a clerical/lookup error: the wrong unit pulled, a label misread. Every blood bank runs a compatibility check; the failure mode is that it is advisory, a screen a tired tech can click past. Here `issue` REFUSES an incompatible match outright (compatible() is the real ABO/Rh donor→recipient lattice), AND the inventory is a conserved quantity: a unit count can never go negative and you cannot issue from an empty shelf. The stock invariant makes \"issued more units than exist\" a rejected write, not a reconciliation headache.", "url": "https://soma-lang.dev/corpus/medical/bloodbank.cell", "repo_path": "examples/corpus/medical/bloodbank.cell", "lines": 129, "features": ["invariant", "match", "try", "lambda"], "cells": ["BloodBank", "BloodBankTests"], "usage": ["soma check examples/corpus/medical/bloodbank.cell", "soma test  examples/corpus/medical/bloodbank.cell", "soma run   examples/corpus/medical/bloodbank.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "1 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "medical/chain_of_custody", "domain": "medical", "title": "LAB CHAIN OF CUSTODY — a sample whose custody broke can never be", "summary": "LAB CHAIN OF CUSTODY — a sample whose custody broke can never be reported, by construction A forensic toxicology or pathology result is only as trustworthy as the unbroken chain of custody behind it. If a sample is left unsealed, or its identity can't be accounted for at any handoff, the result is inadmissible and clinically worthless — but the dangerous version is the lab that reports it anyway, and a treatment (or a conviction) rests on a possibly-swapped tube. Here a specimen walks collected → sealed → in_transit → received → analyzed → reported. The one terminal failure state is `compromised`: any custody break sends the sample there and it can NEVER reach `reported`. `soma verify` proves reported is unreachable from compromised, and that compromised is itself terminal — no \"re-seal and pretend\" path exists.", "url": "https://soma-lang.dev/corpus/medical/chain_of_custody.cell", "repo_path": "examples/corpus/medical/chain_of_custody.cell", "lines": 125, "features": ["state_machine", "try"], "cells": ["ChainOfCustody", "CustodyTests"], "usage": ["soma verify examples/corpus/medical/chain_of_custody.cell", "soma test   examples/corpus/medical/chain_of_custody.cell", "soma run    examples/corpus/medical/chain_of_custody.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/coldchain", "domain": "medical", "title": "VACCINE COLD-CHAIN — a temperature breach is PERMANENT, not \"probably fine\"", "summary": "VACCINE COLD-CHAIN — a temperature breach is PERMANENT, not \"probably fine\" In 2018 a UK pharmacy revaccinated hundreds of patients after a fridge failure: the mRNA/protein vaccines had spent hours out of the 2–8 °C window and nobody could prove they were still potent. The temptation in software is always the same — log the excursion, let a human \"assess\" it, quietly keep using the vials. That is how spoiled doses reach arms. Here a vial's life is a state machine whose `discarded` state is TERMINAL: once a reading leaves [2,8] °C the vial transitions to discarded and there is NO path back to administrable. `soma verify` proves discarded is a sink — no sequence of \"re-inspect\" or \"override\" signals can resurrect it. A second wall: the recorded temperature slot only accepts plausible readings, so a stuck sensor reporting 999 °C can't be silently stored as in-range.", "url": "https://soma-lang.dev/corpus/medical/coldchain.cell", "repo_path": "examples/corpus/medical/coldchain.cell", "lines": 126, "features": ["state_machine", "invariant", "try", "lambda"], "cells": ["ColdChain", "ColdChainTests"], "usage": ["soma verify examples/corpus/medical/coldchain.cell   # discarded is terminal", "soma test   examples/corpus/medical/coldchain.cell", "soma run    examples/corpus/medical/coldchain.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/controlled_substance", "domain": "medical", "title": "CONTROLLED SUBSTANCE CABINET — the narcotic count must reconcile, always", "summary": "CONTROLLED SUBSTANCE CABINET — the narcotic count must reconcile, always Diversion of controlled drugs (fentanyl, morphine, oxycodone) from hospital cabinets is a real and deadly problem: nurses have overdosed stealing from the supply, and patients have been undertreated when their dose was diverted and saline charted instead. The DEA requires a perpetual inventory where every dispense, every waste, every return is accounted for and the physical count matches the record. Here the cabinet count is a CONSERVED quantity. You cannot dispense a vial that isn't there (count can't go negative), and a \"waste\" of a partial dose must be witnessed — recorded as its own ledger entry — so the on-hand plus dispensed plus wasted always reconciles. The invariant makes an impossible count (negative, or more than ever stocked) a rejected write, turning diversion-by-miscount into a hard error.", "url": "https://soma-lang.dev/corpus/medical/controlled_substance.cell", "repo_path": "examples/corpus/medical/controlled_substance.cell", "lines": 133, "features": ["invariant", "try"], "cells": ["Cabinet", "CabinetTests"], "usage": ["soma check examples/corpus/medical/controlled_substance.cell", "soma test  examples/corpus/medical/controlled_substance.cell", "soma run   examples/corpus/medical/controlled_substance.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "3 passed, 4 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "medical/dialysis", "domain": "medical", "title": "DIALYSIS — fluid removal is capped, and a session always ends with the", "summary": "DIALYSIS — fluid removal is capped, and a session always ends with the patient reconnected to their own blood In hemodialysis the machine pulls a patient's blood through a filter and returns it, removing excess fluid (ultrafiltration) along the way. Two ways it harms: removing too much fluid too fast crashes blood pressure (intradialytic hypotension — nausea, cramps, cardiac arrest in the frail); and a session ABORTED without rinse-back strands the patient's blood in the extracorporeal circuit — a real loss of ~200+ mL. Here the ultrafiltration total is a bounded ledger: it can never exceed the prescribed fluid removal goal, enforced by the memory invariant — the pump cannot pull more than the body can spare. And the session machine has NO path from `running` straight to `complete`: it must pass through `rinse_back`, so the blood is always returned. `soma verify` proves that path is the only way to finish.", "url": "https://soma-lang.dev/corpus/medical/dialysis.cell", "repo_path": "examples/corpus/medical/dialysis.cell", "lines": 148, "features": ["state_machine", "invariant", "try"], "cells": ["Dialysis", "DialysisTests"], "usage": ["soma verify examples/corpus/medical/dialysis.cell", "soma test   examples/corpus/medical/dialysis.cell", "soma run    examples/corpus/medical/dialysis.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/infusion_pump", "domain": "medical", "title": "INFUSION PUMP — the programmed rate can never exceed the drug's hard limit (\"guardrails\") A nurse programming an IV pump types the rate by hand", "summary": "INFUSION PUMP — the programmed rate can never exceed the drug's hard limit (\"guardrails\") A nurse programming an IV pump types the rate by hand. A misplaced decimal — 250 mL/h instead of 25, or a 10x insulin/heparin overdose — has killed patients; the infamous cases turn on a keypad slip that the pump dutifully obeyed. The fix the industry settled on is a \"drug library\" with hard maximums (Guardrails): the pump simply REFUSES to run faster than the ceiling for that drug, no override. Here the programmed rate lives in a memory slot whose invariant is the hard guardrail — a write above the maximum (or a negative rate) is rejected and the pump keeps its last safe setting. The cumulative volume infused is a second bounded ledger, so a runaway pump cannot silently deliver more than the bag holds.", "url": "https://soma-lang.dev/corpus/medical/infusion_pump.cell", "repo_path": "examples/corpus/medical/infusion_pump.cell", "lines": 113, "features": ["invariant", "try", "lambda"], "cells": ["InfusionPump", "InfusionTests"], "usage": ["soma check examples/corpus/medical/infusion_pump.cell", "soma test  examples/corpus/medical/infusion_pump.cell", "soma run   examples/corpus/medical/infusion_pump.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "0 passed, 2 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "medical/isolation", "domain": "medical", "title": "ISOLATION PRECAUTIONS — a contagious patient cannot be discharged to a", "summary": "ISOLATION PRECAUTIONS — a contagious patient cannot be discharged to a shared bay, and clearance requires two negative tests Hospital-acquired infection spreads when an isolation breach goes unnoticed: a patient colonized with a multidrug-resistant organism (MRSA, C. diff, or a novel respiratory virus) is moved out of contact/airborne precautions before they are cleared, seeding the next ward. The control is a strict status: isolated patients stay isolated until an infection- prevention clearance — typically TWO negative tests — is documented. Here the patient's infection-control status is a state machine. A patient under `isolated` can only reach `cleared` through `pending_clearance` after the required negatives — there is no isolated -> cleared shortcut, and `cleared` is the only state from which a normal-ward transfer is allowed. A bounded counter records consecutive negatives; one positive resets it, so \"two negatives\" can't be faked by a single lucky swab.", "url": "https://soma-lang.dev/corpus/medical/isolation.cell", "repo_path": "examples/corpus/medical/isolation.cell", "lines": 155, "features": ["state_machine", "invariant", "try"], "cells": ["Isolation", "IsolationTests"], "usage": ["soma verify examples/corpus/medical/isolation.cell", "soma test   examples/corpus/medical/isolation.cell", "soma run    examples/corpus/medical/isolation.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/med_administration", "domain": "medical", "title": "MEDICATION ADMINISTRATION — the \"five rights\" enforced by barcode, no", "summary": "MEDICATION ADMINISTRATION — the \"five rights\" enforced by barcode, no scan no dose Wrong-patient and wrong-drug medication errors are among the most common causes of inpatient harm. The defense that actually moved the numbers is Barcode Medication Administration (BCMA): the nurse scans their badge, the patient's wristband, and the drug — and the system confirms the five rights (right patient, drug, dose, route, time) BEFORE the dose is recorded as administered_done. Workarounds (charting without scanning) are exactly how the errors slip back in. Here an administration is a state machine that physically cannot reach `administered_done` without passing through `patient_verified` and `drug_verified`. A mismatch at either scan sends it to the TERMINAL `aborted` state — the dose is never administered_done and the attempt can't be silently retried into success. `soma verify` proves `administered_done` is unreachable from `aborted`.", "url": "https://soma-lang.dev/corpus/medical/med_administration.cell", "repo_path": "examples/corpus/medical/med_administration.cell", "lines": 135, "features": ["state_machine", "match", "try"], "cells": ["BCMA", "BCMATests"], "usage": ["soma verify examples/corpus/medical/med_administration.cell", "soma test   examples/corpus/medical/med_administration.cell", "soma run    examples/corpus/medical/med_administration.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/prescription_lockout", "domain": "medical", "title": "PRESCRIPTION INTERACTION LOCKOUT — a lethal drug combination is refused", "summary": "PRESCRIPTION INTERACTION LOCKOUT — a lethal drug combination is refused at the point of order, not flagged for later Serotonin syndrome (an MAOI plus an SSRI), fatal bleeds (warfarin plus an NSAID), torsade from stacked QT-prolongers — co-prescribing certain drugs can kill. Every CPOE system has an interaction checker; the recurring tragedy is alert fatigue, where the warning is one more dismissible pop-up and the order goes through anyway. Here the active medication list is the source of truth, and `prescribe` REFUSES to add a drug that interacts with anything already on the list — there is no \"override\" path in the data model, so the dangerous pair never coexists. A bounded count invariant also caps polypharmacy, the independent risk multiplier behind most interaction harm.", "url": "https://soma-lang.dev/corpus/medical/prescription_lockout.cell", "repo_path": "examples/corpus/medical/prescription_lockout.cell", "lines": 142, "features": ["invariant", "try", "lambda"], "cells": ["Pharmacy", "PharmacyTests"], "usage": ["soma check examples/corpus/medical/prescription_lockout.cell", "soma test  examples/corpus/medical/prescription_lockout.cell", "soma run   examples/corpus/medical/prescription_lockout.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "2 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "medical/sepsis_bundle", "domain": "medical", "title": "SEPSIS BUNDLE — antibiotics never go in before the blood cultures are", "summary": "SEPSIS BUNDLE — antibiotics never go in before the blood cultures are drawn, and the 1-hour clock is real The Surviving Sepsis \"hour-1 bundle\" saves lives by ordering: measure lactate, DRAW BLOOD CULTURES, then give broad-spectrum antibiotics, then start fluids — all within an hour of recognition. The ordering is not bureaucratic: give antibiotics before the cultures are drawn and you sterilize the sample, losing the chance to identify the organism and target therapy. The other failure is the clock: every minute of delay to antibiotics raises mortality. Here the bundle is a state machine where `antibiotics` is reachable ONLY after `cultures_drawn` — there is no edge that lets the drug precede the draw. A memory invariant pins elapsed minutes into [0,60]: a bundle charted as completed past the hour is a rejected write, so \"we'll call it on-time\" cannot be recorded. `completed` is terminal.", "url": "https://soma-lang.dev/corpus/medical/sepsis_bundle.cell", "repo_path": "examples/corpus/medical/sepsis_bundle.cell", "lines": 147, "features": ["state_machine", "invariant", "try"], "cells": ["SepsisBundle", "SepsisTests"], "usage": ["soma verify examples/corpus/medical/sepsis_bundle.cell", "soma test   examples/corpus/medical/sepsis_bundle.cell", "soma run    examples/corpus/medical/sepsis_bundle.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/sterilization", "domain": "medical", "title": "AUTOCLAVE STERILIZATION — a failed cycle can never release instruments", "summary": "AUTOCLAVE STERILIZATION — a failed cycle can never release instruments as sterile Surgical instruments are sterilized in an autoclave: saturated steam at 121–134 °C held long enough to kill spores, verified by a biological indicator. The deadly shortcut is releasing a load as \"sterile\" when the cycle aborted (a steam fault, a failed indicator) — every patient that tray touches is exposed to surgical-site infection, and outbreaks have been traced to exactly this. The standard is unforgiving: a failed cycle means the whole load is reprocessed, never released. Here a load runs loaded → running → (held params met) → indicator_pass → released. Any parameter fault or a failed biological indicator routes to the TERMINAL `failed` state — there is no edge from `failed` to `released`. A memory invariant also pins the sterilization hold temperature into the validated band, so a probe reading 80 °C cannot be charted as a passing cycle. `soma verify` proves released is unreachable from failed.", "url": "https://soma-lang.dev/corpus/medical/sterilization.cell", "repo_path": "examples/corpus/medical/sterilization.cell", "lines": 159, "features": ["state_machine", "invariant", "try", "lambda"], "cells": ["Autoclave", "AutoclaveTests"], "usage": ["soma verify examples/corpus/medical/sterilization.cell", "soma test   examples/corpus/medical/sterilization.cell", "soma run    examples/corpus/medical/sterilization.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/surgical_checklist", "domain": "medical", "title": "SURGICAL SAFETY CHECKLIST — no incision before time-out, and the count", "summary": "SURGICAL SAFETY CHECKLIST — no incision before time-out, and the count must reconcile before you close The WHO Surgical Safety Checklist exists because of two recurring disasters: wrong-site surgery (operating on the wrong knee, the wrong patient) and retained foreign objects (a sponge or instrument left inside, requiring a second operation, sometimes fatal sepsis). The defenses are a pre-incision \"time-out\" (confirm patient, site, procedure) and a final instrument/sponge COUNT that must match before the surgeon closes. Here the operation is a state machine: you physically cannot reach `incision` without passing through `timeout_done`, and you cannot reach `closed` without `count_correct`. A memory invariant makes the count a conserved equation — sponges out must equal sponges in — so \"close with one still inside\" is a rejected write, not a postoperative X-ray surprise.", "url": "https://soma-lang.dev/corpus/medical/surgical_checklist.cell", "repo_path": "examples/corpus/medical/surgical_checklist.cell", "lines": 146, "features": ["state_machine", "invariant", "match", "try"], "cells": ["Surgery", "SurgeryTests"], "usage": ["soma verify examples/corpus/medical/surgical_checklist.cell", "soma test   examples/corpus/medical/surgical_checklist.cell", "soma run    examples/corpus/medical/surgical_checklist.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/transplant", "domain": "medical", "title": "ORGAN ALLOCATION — one organ, one recipient, and no taking it back once", "summary": "ORGAN ALLOCATION — one organ, one recipient, and no taking it back once it is in A donor organ is the scarcest thing in medicine and the lifecycle is unforgiving: an offer is made to one candidate, accepted, the organ is recovered and transplanted. The catastrophic bug is double-allocation — the same kidney \"offered\" to two centers, both accept, one patient is opened up for an organ that has already been sewn into someone else. UNOS allocation incidents have turned on exactly this kind of race. Here each organ is a state machine. From `offered` it can be accepted by exactly one recipient (recorded once); `transplanted` is TERMINAL — once the organ is in a body there is no offer, no re-allocation, no path back to the pool. `soma verify` proves transplanted is a sink and that the declined/expired dead-ends can't masquerade as available.", "url": "https://soma-lang.dev/corpus/medical/transplant.cell", "repo_path": "examples/corpus/medical/transplant.cell", "lines": 145, "features": ["state_machine", "try"], "cells": ["Transplant", "TransplantTests"], "usage": ["soma verify examples/corpus/medical/transplant.cell  # no resurrection", "soma test   examples/corpus/medical/transplant.cell", "soma run    examples/corpus/medical/transplant.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "medical/triage", "domain": "medical", "title": "EMERGENCY TRIAGE — the sickest patient is seen first, by construction", "summary": "EMERGENCY TRIAGE — the sickest patient is seen first, by construction ED overcrowding kills by inversion: a walk-in with a sprain gets a bed while a silent MI in the waiting room arrests. The Manchester / ESI triage standard fixes an ordering — level 1 (resuscitation) before level 5 (non-urgent) — but a queue implemented as plain FIFO quietly violates it the moment load spikes. Here \"the next patient is always the most acute waiting one\" is not a sort we hope ran; it is what `next_to_see` computes directly over the waiting set, and a patient's acuity is pinned to the ESI scale by a memory invariant (1..5). A bug that wrote acuity 0 or 9 — which would jump or sink someone in the order — is rejected at the slot.", "url": "https://soma-lang.dev/corpus/medical/triage.cell", "repo_path": "examples/corpus/medical/triage.cell", "lines": 123, "features": ["invariant", "try"], "cells": ["Triage", "TriageTests"], "usage": ["soma check examples/corpus/medical/triage.cell", "soma test  examples/corpus/medical/triage.cell", "soma run   examples/corpus/medical/triage.cell demo"], "verified": {"check": true, "test": true, "verify": true}, "verify": "1 passed, 1 warnings, 0 failures; temporal 0 passed, 0 failed"}, {"id": "records/address_book", "domain": "records", "title": "Address book: Contact records stored in a Map slot, round-tripped through storage, and queried", "summary": "Address book: Contact records stored in a Map slot, round-tripped through storage, and queried. Demonstrates record literals, dot-access, storing records in [persistent] map slots, and self-verifying tests.", "url": "https://soma-lang.dev/corpus/records/address_book.cell", "repo_path": "examples/corpus/records/address_book.cell", "lines": 49, "features": [], "cells": ["AddressBook", "AddressBookTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/bank", "domain": "records", "title": "Bank accounts as Account records kept in a persistent Map slot, with deposit/withdraw that read, mutate, and write the record back", "summary": "Bank accounts as Account records kept in a persistent Map slot, with deposit/withdraw that read, mutate, and write the record back. Shows the read-modify-write round-trip pattern and a negative (overdraft) path.", "url": "https://soma-lang.dev/corpus/records/bank.cell", "repo_path": "examples/corpus/records/bank.cell", "lines": 57, "features": [], "cells": ["Bank", "BankTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/bst", "domain": "records", "title": "Binary search tree built from Node records with nested `left`/`right` children", "summary": "Binary search tree built from Node records with nested `left`/`right` children. Demonstrates trees-of-records, recursive handlers over a record shape, and unit () as the empty subtree.", "url": "https://soma-lang.dev/corpus/records/bst.cell", "repo_path": "examples/corpus/records/bst.cell", "lines": 68, "features": ["pipeline"], "cells": ["BST", "BSTTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/config", "domain": "records", "title": "Nested config record with defaults, merge-style overrides, and a deep-path reader", "summary": "Nested config record with defaults, merge-style overrides, and a deep-path reader. Demonstrates a settings tree built from records and the ?? null-coalescing guard for optional fields.", "url": "https://soma-lang.dev/corpus/records/config.cell", "repo_path": "examples/corpus/records/config.cell", "lines": 58, "features": ["match"], "cells": ["Config", "ConfigTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/ecs", "domain": "records", "title": "Entity-Component shape: each Entity record carries a bag of components (position, velocity, health) as nested records", "summary": "Entity-Component shape: each Entity record carries a bag of components (position, velocity, health) as nested records. Demonstrates an entity-component data model, nested dot-mutation, and a physics \"tick\".", "url": "https://soma-lang.dev/corpus/records/ecs.cell", "repo_path": "examples/corpus/records/ecs.cell", "lines": 60, "features": ["pipeline", "lambda"], "cells": ["ECS", "ECSTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/employees", "domain": "records", "title": "Employee directory: records driving group_by / agg / inner_join style reporting", "summary": "Employee directory: records driving group_by / agg / inner_join style reporting. Demonstrates records as rows in analytical pipelines and a department roll-up.", "url": "https://soma-lang.dev/corpus/records/employees.cell", "repo_path": "examples/corpus/records/employees.cell", "lines": 54, "features": ["pipeline", "lambda"], "cells": ["Employees", "EmployeesTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/family_tree", "domain": "records", "title": "Family tree: Person records with a list of `children` records, walked recursively", "summary": "Family tree: Person records with a list of `children` records, walked recursively. Demonstrates a multi-way tree of records, recursive counting, and collecting a generation by depth.", "url": "https://soma-lang.dev/corpus/records/family_tree.cell", "repo_path": "examples/corpus/records/family_tree.cell", "lines": 71, "features": ["pipeline"], "cells": ["FamilyTree", "FamilyTreeTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/geometry", "domain": "records", "title": "Geometry: Point and Rect records with computed properties", "summary": "Geometry: Point and Rect records with computed properties. Demonstrates small value-records, deriving fields from nested records, and float tolerance in assertions.", "url": "https://soma-lang.dev/corpus/records/geometry.cell", "repo_path": "examples/corpus/records/geometry.cell", "lines": 46, "features": [], "cells": ["Geometry", "GeometryTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/inventory", "domain": "records", "title": "Inventory: a list of Item records with in-place quantity mutation, restock/sell operations, and aggregate reporting via pipelines", "summary": "Inventory: a list of Item records with in-place quantity mutation, restock/sell operations, and aggregate reporting via pipelines. Demonstrates building a list of records and mutating xs[i].field.", "url": "https://soma-lang.dev/corpus/records/inventory.cell", "repo_path": "examples/corpus/records/inventory.cell", "lines": 59, "features": ["pipeline", "lambda"], "cells": ["Inventory", "InventoryTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/json_roundtrip", "domain": "records", "title": "Records and JSON: serialize a record to a JSON string and parse it back", "summary": "Records and JSON: serialize a record to a JSON string and parse it back. Demonstrates to_json/from_json round-tripping — the record's _type tag is part of its data, so is_a still recognizes it after a full round-trip.", "url": "https://soma-lang.dev/corpus/records/json_roundtrip.cell", "repo_path": "examples/corpus/records/json_roundtrip.cell", "lines": 47, "features": [], "cells": ["JsonRecords", "JsonRecordsTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/kanban", "domain": "records", "title": "Kanban board: Card records stored by id in a Map slot, moved between columns by mutating a field and writing back", "summary": "Kanban board: Card records stored by id in a Map slot, moved between columns by mutating a field and writing back. Demonstrates records in a keyed store, a column roll-up, and counting by a record field.", "url": "https://soma-lang.dev/corpus/records/kanban.cell", "repo_path": "examples/corpus/records/kanban.cell", "lines": 55, "features": ["pipeline", "lambda"], "cells": ["Kanban", "KanbanTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/linkedlist", "domain": "records", "title": "Singly linked list built from Node records whose `next` field is either another Node or () for the tail", "summary": "Singly linked list built from Node records whose `next` field is either another Node or () for the tail. Demonstrates a recursive record chain and folding over it without any list builtins.", "url": "https://soma-lang.dev/corpus/records/linkedlist.cell", "repo_path": "examples/corpus/records/linkedlist.cell", "lines": 74, "features": [], "cells": ["LinkedList", "LinkedListTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/orders", "domain": "records", "title": "Order records with nested line-items, computed totals, and a state machine over the order lifecycle", "summary": "Order records with nested line-items, computed totals, and a state machine over the order lifecycle. Demonstrates records carrying lists of records, with() copy-update, and records that drive transitions.", "url": "https://soma-lang.dev/corpus/records/orders.cell", "repo_path": "examples/corpus/records/orders.cell", "lines": 58, "features": ["state_machine", "sum_type", "pipeline", "lambda"], "cells": ["OrderStatus", "Orders", "OrdersTest"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "records/playlist", "domain": "records", "title": "Playlist as an ordered list of Track records", "summary": "Playlist as an ordered list of Track records. Demonstrates building, reordering, and summarizing a list of records, plus sort_by/pluck over record fields and total-duration aggregation.", "url": "https://soma-lang.dev/corpus/records/playlist.cell", "repo_path": "examples/corpus/records/playlist.cell", "lines": 50, "features": ["pipeline", "lambda"], "cells": ["Playlist", "PlaylistTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/record_ops", "domain": "records", "title": "Functional record updates: with / without / merge produce new records without mutating the original", "summary": "Functional record updates: with / without / merge produce new records without mutating the original. Demonstrates immutable-style field updates and that the source record is left untouched.", "url": "https://soma-lang.dev/corpus/records/record_ops.cell", "repo_path": "examples/corpus/records/record_ops.cell", "lines": 51, "features": ["pipeline"], "cells": ["RecordOps", "RecordOpsTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/shapes_typed", "domain": "records", "title": "Typed record literals and runtime type tags", "summary": "Typed record literals and runtime type tags. Demonstrates is_a/is_type on record literals, type_of, and dispatching on a record's _type field rather than a sum type — records carry their own type name.", "url": "https://soma-lang.dev/corpus/records/shapes_typed.cell", "repo_path": "examples/corpus/records/shapes_typed.cell", "lines": 46, "features": [], "cells": ["Shapes", "ShapesTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "records/students", "domain": "records", "title": "Gradebook: Student records each holding a list of Score records", "summary": "Gradebook: Student records each holding a list of Score records. Shows records-within-records, averaging a nested list, and assigning a derived letter grade with a guarded match.", "url": "https://soma-lang.dev/corpus/records/students.cell", "repo_path": "examples/corpus/records/students.cell", "lines": 58, "features": ["pipeline", "match", "lambda"], "cells": ["Gradebook", "GradebookTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "safety_interlocks/autoclave_door", "domain": "safety_interlocks", "title": "AUTOCLAVE DOOR — a quick-opening door never unlocks under pressure", "summary": "AUTOCLAVE DOOR — a quick-opening door never unlocks under pressure. Quick-opening pressure vessel doors (autoclaves, sterilizers, curing vessels) have killed operators for a century the same way: residual pressure behind a door someone believed was vented, and the door becomes a projectile. ASME PCC interlocks demand the door cannot unlock until pressure is verifiably zero. Here {pressurized, door open} is not a state: steam is only admitted behind a locked door, and the lock releases only from `sealed_cold` — the exhaust edge zeroes the chamber BEFORE the unlock edge exists. The chamber ledger refuses any pressure beyond the 300 kPa nameplate.", "url": "https://soma-lang.dev/corpus/safety_interlocks/autoclave_door.cell", "repo_path": "examples/corpus/safety_interlocks/autoclave_door.cell", "lines": 96, "features": ["state_machine", "invariant", "try"], "cells": ["AutoclaveControl", "AutoclaveTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/blast_furnace_door", "domain": "safety_interlocks", "title": "BLAST FURNACE TOP — never open a door against live CO gas", "summary": "BLAST FURNACE TOP — never open a door against live CO gas. Blast furnace top gas is roughly a quarter carbon monoxide at positive pressure; opening an access door on a live furnace has gassed entire maintenance crews. The kill chain is isolation -> venting -> gas test, and every fatality is a skipped link. Here the door has no edge from any pressurized state: `live -> door_open` and `isolated -> door_open` do not exist, only `vented` reaches the door. The gas-test ledger is the final wall — entry is logged with the measured CO ppm, and the memory itself refuses a reading above the 30 ppm entry limit.", "url": "https://soma-lang.dev/corpus/safety_interlocks/blast_furnace_door.cell", "repo_path": "examples/corpus/safety_interlocks/blast_furnace_door.cell", "lines": 83, "features": ["state_machine", "invariant", "try"], "cells": ["FurnaceTop", "FurnaceTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/chlorine_dosing", "domain": "safety_interlocks", "title": "CHLORINE DOSING — no chemical feed without proven water flow", "summary": "CHLORINE DOSING — no chemical feed without proven water flow. The CDC logs hundreds of poolgoers hospitalized in chemical-controller incidents with one recurring shape: the recirculation pump stops, the chlorine feeder keeps running, and the stagnant line accumulates a slug that gasses the first swimmers when flow returns. The fix is a flow interlock: the feeder is DOWNSTREAM of proven flow in the state machine itself — `standby -> feeding` does not exist, and losing flow while feeding forces the feed-stop edge before the pump-stop edge. The residual ledger independently refuses any dose past the 4 ppm EPA maximum residual disinfectant level.", "url": "https://soma-lang.dev/corpus/safety_interlocks/chlorine_dosing.cell", "repo_path": "examples/corpus/safety_interlocks/chlorine_dosing.cell", "lines": 88, "features": ["state_machine", "invariant", "try"], "cells": ["ChlorineFeed", "FeedTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/conveyor_pullcord", "domain": "safety_interlocks", "title": "GRAIN CONVEYOR PULL-CORD — a latched trip, and a broken safety circuit that stays broken", "summary": "GRAIN CONVEYOR PULL-CORD — a latched trip, and a broken safety circuit that stays broken. Grain handling kills dozens every year; engulfment victims are often pulled in by a conveyor a coworker restarted while they were still in the boot pit. Two properties are structural here. Anti-restart: a pull-cord trip latches, and `tripped` has NO edge to `running` — the only exit is `reset_walked`, a state a human reaches by walking the belt line. Fail-safe wiring: the pull- cord loop is supervised, and a severed wire lands in `circuit_fault`, a TERMINAL state soma verify proves has no exit — a conveyor whose safety circuit is cut can never be software-restarted.", "url": "https://soma-lang.dev/corpus/safety_interlocks/conveyor_pullcord.cell", "repo_path": "examples/corpus/safety_interlocks/conveyor_pullcord.cell", "lines": 88, "features": ["state_machine", "invariant", "try"], "cells": ["ConveyorGuard", "ConveyorTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/crane_load_moment", "domain": "safety_interlocks", "title": "CRANE LOAD MOMENT — the tipping write is refused by the ledger", "summary": "CRANE LOAD MOMENT — the tipping write is refused by the ledger. \"Big Blue\", Miller Park, 1999: a 567-ton lift in wind put the crawler crane past its load moment and it came down across the stadium — 3 ironworkers dead. Load moment is load x radius against the rated chart; the killer is that each input looks fine alone. Here the computed moment percentage is written to a slot whose invariant tops out at 100: a lift plan that tips the crane is REJECTED AT THE WRITE, so the hoist edge is never taken. The machine adds the second wall — a crane cannot hoist from `parked`, and an out-of-chart plan leaves it safely in `rigged`.", "url": "https://soma-lang.dev/corpus/safety_interlocks/crane_load_moment.cell", "repo_path": "examples/corpus/safety_interlocks/crane_load_moment.cell", "lines": 90, "features": ["state_machine", "invariant", "try"], "cells": ["LoadMomentIndicator", "CraneTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/drawbridge", "domain": "safety_interlocks", "title": "DRAWBRIDGE — the span never moves while the deck is open to traffic", "summary": "DRAWBRIDGE — the span never moves while the deck is open to traffic. Bascule bridges have killed pedestrians and drivers who were still on the span when it began to rise — tenders raising on a green gate, cars driving around half-lowered barriers. The opening sequence is law: signals stop NEW traffic, gates physically close the deck, and only then may the span move. Here that order is the state machine itself — `traffic_flowing -> span_raised` does not exist, and a raised span has no edge back to traffic without first seating and re-gating. The span angle ledger refuses any value beyond the 75-degree mechanical stop.", "url": "https://soma-lang.dev/corpus/safety_interlocks/drawbridge.cell", "repo_path": "examples/corpus/safety_interlocks/drawbridge.cell", "lines": 85, "features": ["state_machine", "invariant", "try"], "cells": ["BridgeControl", "BridgeTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/gas_burner_purge", "domain": "safety_interlocks", "title": "GAS BURNER IGNITION — purge before spark, lockout is forever", "summary": "GAS BURNER IGNITION — purge before spark, lockout is forever. NFPA 86 exists because furnaces that spark into a fuel-laden chamber detonate: the prepurge (4+ air changes) is the single step operators skip when restarts are slow, and skipped purges are a recurring CSB explosion class. Here `off -> pilot_spark` simply does not exist: the only road to a spark runs through `purging` and `purge_done`. A failed ignition or flame loss lands in `lockout` — a TERMINAL state soma verify proves has no exit. Re-light means a human walks to the burner; software cannot talk its way out. The retry ledger caps trial-for- ignition attempts at 3 in memory itself.", "url": "https://soma-lang.dev/corpus/safety_interlocks/gas_burner_purge.cell", "repo_path": "examples/corpus/safety_interlocks/gas_burner_purge.cell", "lines": 82, "features": ["state_machine", "invariant", "try"], "cells": ["BurnerControl", "BurnerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/lockout_tagout", "domain": "safety_interlocks", "title": "LOCKOUT/TAGOUT — a machine with a personal lock on it cannot start", "summary": "LOCKOUT/TAGOUT — a machine with a personal lock on it cannot start. OSHA calls 1910.147 violations a perennial top-ten killer: maintenance inside a machine, someone hits start, the machine wins. The padlock works because ONLY its owner holds the key. Here `locked_out` has no edge to `running` — re-energizing exists only from `isolated`, and the handler that leaves `locked_out` refuses while any personal lock remains on the hasp. The lock ledger itself rejects a negative count (the classic double-remove bookkeeping bug) and more locks than the 6-hole hasp can hold.", "url": "https://soma-lang.dev/corpus/safety_interlocks/lockout_tagout.cell", "repo_path": "examples/corpus/safety_interlocks/lockout_tagout.cell", "lines": 91, "features": ["state_machine", "invariant", "try"], "cells": ["LotoControl", "LotoTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/mine_hoist", "domain": "safety_interlocks", "title": "MINE HOIST — no motion with the gate open, and a trip is forever", "summary": "MINE HOIST — no motion with the gate open, and a trip is forever. Markham Colliery, 1973: the hoist brake failed and the cage carrying 29 miners ran away down the shaft — 18 dead. Overwind and overspeed arrestors exist because a winder must be STOPPED by hardware, not promised to stop by software. Two structural walls here: the cage can only wind with its gates sealed (`gates_open -> winding` does not exist, and a moving cage cannot open its gates mid-shaft), and the overspeed trip is TERMINAL — soma verify proves `tripped` has no exit, so no command sequence ever winds a tripped hoist again. The speed ledger refuses any value past the 12 m/s arrestor setting.", "url": "https://soma-lang.dev/corpus/safety_interlocks/mine_hoist.cell", "repo_path": "examples/corpus/safety_interlocks/mine_hoist.cell", "lines": 86, "features": ["state_machine", "invariant", "try"], "cells": ["HoistControl", "HoistTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/pig_trap_closure", "domain": "safety_interlocks", "title": "PIPELINE PIG TRAP — the closure never opens against trapped pressure", "summary": "PIPELINE PIG TRAP — the closure never opens against trapped pressure. Pig launcher/receiver closures keep killing pipeliners the same way: the trap is valved off from the line, the gauge \"reads zero\" (or nobody looks), the yoke is swung — and residual gas behind the pig fires the closure door like a cannon breech. Industry recommended practice is a hard sequence: isolate, blow down, PROVE zero, then open. Here that sequence is the only path that exists: `in_service` and `isolated` have no edge to `door_open`; only `blown_down` does, and the blowdown edge zeroes the trap before the door edge appears. The trap gauge ledger refuses any write past the 6000 kPa rating.", "url": "https://soma-lang.dev/corpus/safety_interlocks/pig_trap_closure.cell", "repo_path": "examples/corpus/safety_interlocks/pig_trap_closure.cell", "lines": 99, "features": ["state_machine", "invariant", "try"], "cells": ["PigTrap", "PigTrapTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/pressure_relief", "domain": "safety_interlocks", "title": "PRESSURE RELIEF VALVE — a live vessel can never lose its relief path", "summary": "PRESSURE RELIEF VALVE — a live vessel can never lose its relief path. Williams Olefins, Geismar 2013: a reboiler was isolated from its relief valve, heat crept in, and the blocked-in vessel ruptured — 2 dead, 167 injured. The century-old version is the gagged boiler safety valve. Here the joint state (vessel pressure x relief path) is one machine, and the state {in service, relief blocked} does not exist: you can only block the relief valve for maintenance from the cold, offline state, and a blocked-relief vessel has no edge into service. The gauge ledger independently refuses pressure above MAWP.", "url": "https://soma-lang.dev/corpus/safety_interlocks/pressure_relief.cell", "repo_path": "examples/corpus/safety_interlocks/pressure_relief.cell", "lines": 88, "features": ["state_machine", "invariant", "try"], "cells": ["ReliefInterlock", "ReliefTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/railway_block", "domain": "safety_interlocks", "title": "RAILWAY BLOCK SIGNALING — two trains never share a block", "summary": "RAILWAY BLOCK SIGNALING — two trains never share a block. Ladbroke Grove (1999, 31 dead) and a century of telescoped carriages before it happen when a second train enters an occupied block. Here the collision state is unrepresentable: a block is a state machine with exactly `clear` and `occupied`, and `occupied -> occupied` does not exist — the second grant RAISES instead of being a flag you forgot to check. A train-count ledger is the independent second wall: the write of a 2 is refused by the memory itself.", "url": "https://soma-lang.dev/corpus/safety_interlocks/railway_block.cell", "repo_path": "examples/corpus/safety_interlocks/railway_block.cell", "lines": 80, "features": ["state_machine", "invariant", "try"], "cells": ["BlockSignal", "BlockTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/robot_cell_gate", "domain": "safety_interlocks", "title": "ROBOT CELL GATE — full-speed automation only behind a closed gate", "summary": "ROBOT CELL GATE — full-speed automation only behind a closed gate. A 21-year-old contractor died inside a robot cell at a German auto plant in 2015, struck by an arm that should never have been live with a person inside the fence. ISO 10218 guard interlocking says the gate and the robot mode are ONE state: here `auto_run` exists only behind a closed gate, opening the gate from auto requires the safety-stop edge FIRST, and there is no {gate open, full speed} state to race into. Inside the fence the robot may move only in teach mode, and the speed ledger structurally caps teach motion at the 250 mm/s collaborative limit — a faster write is refused by the memory.", "url": "https://soma-lang.dev/corpus/safety_interlocks/robot_cell_gate.cell", "repo_path": "examples/corpus/safety_interlocks/robot_cell_gate.cell", "lines": 84, "features": ["state_machine", "invariant", "try", "guard"], "cells": ["RobotCell", "RobotCellTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 3 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "safety_interlocks/two_hand_press", "domain": "safety_interlocks", "title": "TWO-HAND PRESS CONTROL — anti-tie-down, anti-repeat, structural", "summary": "TWO-HAND PRESS CONTROL — anti-tie-down, anti-repeat, structural. Mechanical power presses amputated thousands of hands a year before OSHA 1910.217. The classic defeat: tape one palm button down, feed the die with the free hand. Here the machine has NO path from `one_held` to `armed` — concurrent actuation (both buttons inside the 500 ms window) is the ONLY arming edge, so a tied-down button is a dead end that must be fully released. Anti-repeat is the same trick: `stroking` exits only to `released`, so holding both buttons cannot recycle the ram. The stroke ledger refuses a ram position outside the die set.", "url": "https://soma-lang.dev/corpus/safety_interlocks/two_hand_press.cell", "repo_path": "examples/corpus/safety_interlocks/two_hand_press.cell", "lines": 78, "features": ["state_machine", "invariant", "try"], "cells": ["PressControl", "PressTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "services/payments_approval", "domain": "services", "title": "PAYMENTS APPROVAL — a whole service in one file: a ledger that cannot", "summary": "PAYMENTS APPROVAL — a whole service in one file: a ledger that cannot overdraw, a payment lifecycle the verifier proves, an HTTP API that maps error kinds to status codes, and tests that run offline. What is PROVEN (soma verify + soma.toml): paid is unreachable without authorized; nothing follows rejected; every payment ends paid or rejected. What is ENFORCED: the balance never goes negative (invariant, checked on every write); a handler that fails is rolled back entirely, so a payment whose debit is refused stays exactly where it was.", "url": "https://soma-lang.dev/corpus/services/payments_approval.cell", "repo_path": "examples/corpus/services/payments_approval.cell", "lines": 165, "features": ["state_machine", "invariant", "http", "match", "try", "fail", "multi_cell", "service"], "cells": ["Ledger", "Payments", "PaymentsTests"], "usage": ["soma check  payments_approval.cell", "soma verify payments_approval.cell", "soma test   payments_approval.cell", "soma run    payments_approval.cell request POST /payments '{\"id\":\"p1\",\"amount\":250}'"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 2 warnings, 0 failures; temporal 7 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/services/soma.toml"}, {"id": "services/refund_agent", "domain": "services", "title": "REFUND AGENT — an LLM decides, the language decides what it may do", "summary": "REFUND AGENT — an LLM decides, the language decides what it may do. The model proposes approve / deny / escalate as JSON; its output becomes a sum type (malformed → Escalate, never a crash). The hard rules are not the model's to bend: a refund above the order amount or after 30 days is refused by guards on the edge to `paid`; the daily payout cap is a memory invariant; a refund above 20,000 cents needs a human (`approve()`), which tests script with `mock approve`. Proven: paid is unreachable without decided; nothing after denied. Proven too: the cost bound, because every think() has a literal max_tokens and runs once.", "url": "https://soma-lang.dev/corpus/services/refund_agent.cell", "repo_path": "examples/corpus/services/refund_agent.cell", "lines": 162, "features": ["state_machine", "invariant", "agent", "sum_type", "think", "match", "try", "guard", "fail", "cost", "tools"], "cells": ["Decision", "RefundAgent", "RefundTests"], "usage": ["soma check  refund_agent.cell      → cost: 'tokens' bound proven", "soma verify refund_agent.cell", "soma test   refund_agent.cell      → offline: think() and approve() are scripted"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/services/soma.toml"}, {"id": "services/warehouse_reservations", "domain": "services", "title": "WAREHOUSE RESERVATIONS — two cells: a stock ledger with hard bounds and a reservation lifecycle with a supervisor guard, behind one HTTP router", "summary": "WAREHOUSE RESERVATIONS — two cells: a stock ledger with hard bounds and a reservation lifecycle with a supervisor guard, behind one HTTP router. Proven (`soma verify --strict` is green): on-hand quantity stays in [0, 10000] per SKU and there are at most 500 SKUs — every writer narrows its value with a `require` before the one write, so the invariants hold by induction instead of being checked at run time; shipped requires picked AND held; released never ships; rejected and shipped are final (`* -> rejected except [shipped, released]`). Enforced at the transition: a reservation above 100 units only reaches `held` when a supervisor is named (a guard). A hold that would overdraw stock ends `rejected` and stock is untouched — the failing `try` block is rolled back to where it started.", "url": "https://soma-lang.dev/corpus/services/warehouse_reservations.cell", "repo_path": "examples/corpus/services/warehouse_reservations.cell", "lines": 187, "features": ["state_machine", "invariant", "http", "match", "try", "guard", "fail", "multi_cell", "service"], "cells": ["Stock", "Reservations", "WarehouseTests"], "usage": ["soma check  warehouse_reservations.cell", "soma verify --strict warehouse_reservations.cell", "soma test   warehouse_reservations.cell"], "verified": {"check": true, "test": true, "verify": true}, "verify": "22 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/services/soma.toml"}, {"id": "state_machines/document_review", "domain": "state_machines", "title": "Document editorial workflow with a typed (sum-type) state machine", "summary": "Document editorial workflow with a typed (sum-type) state machine. A draft is submitted for review; a reviewer either requests changes (back to draft) or approves; approved documents are published. The changes-requested loop is bounded by reaching `published` or `archived` from every state, so liveness holds.", "url": "https://soma-lang.dev/corpus/state_machines/document_review.cell", "repo_path": "examples/corpus/state_machines/document_review.cell", "lines": 59, "features": ["state_machine", "sum_type"], "cells": ["DocState", "Editorial", "EditorialTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/elevator", "domain": "state_machines", "title": "An elevator door + motion interlock", "summary": "An elevator door + motion interlock. Two facts the machine enforces: the car only moves when doors are shut, and doors only open when the car is idle. The cycle idle -> doors_open -> idle -> moving_up/down -> idle keeps the machine live; `idle` is the recurrent hub every state returns to.", "url": "https://soma-lang.dev/corpus/state_machines/elevator.cell", "repo_path": "examples/corpus/state_machines/elevator.cell", "lines": 60, "features": ["state_machine"], "cells": ["Elevator", "ElevatorTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "10 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/expense_approval", "domain": "state_machines", "title": "Multi-step expense-approval workflow with guarded transitions", "summary": "Multi-step expense-approval workflow with guarded transitions. A submitted expense needs manager sign-off; anything over a threshold also needs finance. Rejection at either gate sends it back to draft. Guards on the state machine encode the business rule: the manager_ok -> finance_review arrow is only taken for large amounts.", "url": "https://soma-lang.dev/corpus/state_machines/expense_approval.cell", "repo_path": "examples/corpus/state_machines/expense_approval.cell", "lines": 81, "features": ["state_machine", "invariant", "fail"], "cells": ["ExpenseApproval", "ExpenseTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/game_match", "domain": "state_machines", "title": "Online game-match lifecycle", "summary": "Online game-match lifecycle. lobby -> starting -> playing -> finished, with an abandoned escape from the early phases. A rematch flows finished -> lobby, but because both finished and abandoned are reachable terminals listed in [verify], the rematch loop does not break liveness. Memory holds the player roster.", "url": "https://soma-lang.dev/corpus/state_machines/game_match.cell", "repo_path": "examples/corpus/state_machines/game_match.cell", "lines": 81, "features": ["state_machine", "invariant", "match"], "cells": ["GameMatch", "GameMatchTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/media_player", "domain": "state_machines", "title": "A media-player transport state machine", "summary": "A media-player transport state machine. stopped -> playing <-> paused, with stop reachable from play/pause. A typed (sum-type) machine so an illegal transport command is caught statically by the variant name. This is a reactive cyclic system: the proof obligation is deadlock-freedom.", "url": "https://soma-lang.dev/corpus/state_machines/media_player.cell", "repo_path": "examples/corpus/state_machines/media_player.cell", "lines": 57, "features": ["state_machine", "sum_type"], "cells": ["Transport", "MediaPlayer", "MediaPlayerTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "9 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/order_lifecycle", "domain": "state_machines", "title": "Order lifecycle as a typed state machine", "summary": "Order lifecycle as a typed state machine. Demonstrates: a sum-typed `state` machine (states ARE variants, so a typo in transition() is a compile error), guarded transitions, and assert_fails on illegal moves. `soma verify` proves the machine always reaches a terminal (delivered or cancelled).", "url": "https://soma-lang.dev/corpus/state_machines/order_lifecycle.cell", "repo_path": "examples/corpus/state_machines/order_lifecycle.cell", "lines": 58, "features": ["state_machine", "sum_type"], "cells": ["OrderStatus", "OrderFlow", "OrderFlowTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 1 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/shipment_tracking", "domain": "state_machines", "title": "Parcel shipment tracking with a delivery-exception loop", "summary": "Parcel shipment tracking with a delivery-exception loop. created -> picked_up -> in_transit -> out_for_delivery -> delivered. A failed delivery attempt bounces out_for_delivery back to in_transit; a parcel can be returned_to_sender from in_transit. Both delivered and returned_to_sender are terminal, and reachable from every state.", "url": "https://soma-lang.dev/corpus/state_machines/shipment_tracking.cell", "repo_path": "examples/corpus/state_machines/shipment_tracking.cell", "lines": 67, "features": ["state_machine"], "cells": ["ShipmentTracker", "ShipmentTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "13 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/subscription_billing", "domain": "state_machines", "title": "Subscription billing state machine", "summary": "Subscription billing state machine. trialing -> active -> past_due (on a failed charge) -> active (recovery) or -> canceled. Active subscriptions can be canceled directly. The past_due -> active retry loop is bounded by `canceled` being reachable from every state, so liveness holds. Memory tracks the failed-charge count so the handler can escalate to cancellation.", "url": "https://soma-lang.dev/corpus/state_machines/subscription_billing.cell", "repo_path": "examples/corpus/state_machines/subscription_billing.cell", "lines": 93, "features": ["state_machine", "invariant"], "cells": ["Billing", "BillingTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "14 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/support_ticket", "domain": "state_machines", "title": "Support-ticket lifecycle with a reopen path", "summary": "Support-ticket lifecycle with a reopen path. open -> in_progress -> resolved -> closed, with a resolved -> reopened loop that funnels back to in_progress. The * -> closed catch-all and the reopened -> in_progress arrow keep the machine live: every state can still reach the terminal `closed`. assert_fails guards illegal skips.", "url": "https://soma-lang.dev/corpus/state_machines/support_ticket.cell", "repo_path": "examples/corpus/state_machines/support_ticket.cell", "lines": 60, "features": ["state_machine"], "cells": ["TicketDesk", "TicketTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "12 passed, 0 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/tcp_connection", "domain": "state_machines", "title": "A simplified TCP connection state machine (active-open path)", "summary": "A simplified TCP connection state machine (active-open path). closed -> syn_sent -> established -> fin_wait -> closed. This is a classic protocol automaton; the model checker proves that from any state the connection can return to `closed` (no half-open leaks) and that the handshake order cannot be skipped.", "url": "https://soma-lang.dev/corpus/state_machines/tcp_connection.cell", "repo_path": "examples/corpus/state_machines/tcp_connection.cell", "lines": 58, "features": ["state_machine", "sum_type"], "cells": ["TcpState", "TcpConnection", "TcpTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/thermostat", "domain": "state_machines", "title": "An HVAC thermostat control loop", "summary": "An HVAC thermostat control loop. A single machine cycles between idle, heating, and cooling based on the measured temperature versus a target band. This is a reactive (cyclic) system with no terminal state — the proof obligation is deadlock-freedom: the controller always has a legal next action.", "url": "https://soma-lang.dev/corpus/state_machines/thermostat.cell", "repo_path": "examples/corpus/state_machines/thermostat.cell", "lines": 75, "features": ["state_machine", "fail"], "cells": ["Thermostat", "ThermostatTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "5 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/traffic_interlock", "domain": "state_machines", "title": "A two-road traffic-light interlock proven safe by construction", "summary": "A two-road traffic-light interlock proven safe by construction. The single machine cycles ns_go -> ns_caution -> ew_go -> ew_caution and back, with an all_red emergency reachable from anywhere. Because no state ever has both roads green, the model checker proves the safety property `never = []` over a machine that can never deadlock.", "url": "https://soma-lang.dev/corpus/state_machines/traffic_interlock.cell", "repo_path": "examples/corpus/state_machines/traffic_interlock.cell", "lines": 62, "features": ["state_machine", "match"], "cells": ["TrafficInterlock", "TrafficTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "8 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/turnstile", "domain": "state_machines", "title": "A coin-operated turnstile — the textbook two-state machine, plus an out-of-service state reachable only via maintenance", "summary": "A coin-operated turnstile — the textbook two-state machine, plus an out-of-service state reachable only via maintenance. Demonstrates a cyclic machine (locked <-> unlocked) with a generic transition handler so we can assert_fails on a jump that the machine forbids (you cannot go straight from locked to out_of_service without unlocking first). NOTE: transitioning an instance to its CURRENT state is a silent no-op, not an error — only a move to a non-adjacent state is rejected.", "url": "https://soma-lang.dev/corpus/state_machines/turnstile.cell", "repo_path": "examples/corpus/state_machines/turnstile.cell", "lines": 76, "features": ["state_machine"], "cells": ["Turnstile", "TurnstileTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "7 passed, 4 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "state_machines/vending_machine", "domain": "state_machines", "title": "A vending machine state machine", "summary": "A vending machine state machine. idle -> collecting (first coin) -> (more coins) -> dispensing -> idle. A refund from collecting returns to idle. The machine tracks the inserted balance in memory and only dispenses once the price is met.", "url": "https://soma-lang.dev/corpus/state_machines/vending_machine.cell", "repo_path": "examples/corpus/state_machines/vending_machine.cell", "lines": 89, "features": ["state_machine", "invariant", "fail"], "cells": ["VendingMachine", "VendingTests"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 2 warnings, 0 failures; temporal 1 passed, 0 failed"}, {"id": "text/acronym", "domain": "text", "title": "Acronym / initials — first letter of each word, uppercased \"Portable Network Graphics\" -> \"PNG\"", "summary": "Acronym / initials — first letter of each word, uppercased \"Portable Network Graphics\" -> \"PNG\". Splits on spaces, drops empties, and collects the uppercased first character of each word. Demonstrates building a result by accumulating substring(w, 0, 1) over a filtered word list. Run: soma run acronym.cell --signal acronym \"Portable Network Graphics\"", "url": "https://soma-lang.dev/corpus/text/acronym.cell", "repo_path": "examples/corpus/text/acronym.cell", "lines": 43, "features": ["pipeline", "lambda"], "cells": ["Acronym", "AcronymTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/anagram", "domain": "text", "title": "Anagram check — same multiset of letters Two strings are anagrams iff sorting their letters yields the same string", "summary": "Anagram check — same multiset of letters Two strings are anagrams iff sorting their letters yields the same string. We lowercase, drop spaces, explode into a character list, sort it, and re-join. Demonstrates split/sort/join on character lists. Run: soma run anagram.cell --signal is_anagram \"listen\" \"silent\"", "url": "https://soma-lang.dev/corpus/text/anagram.cell", "repo_path": "examples/corpus/text/anagram.cell", "lines": 41, "features": [], "cells": ["Anagram", "AnagramTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/caesar", "domain": "text", "title": "Caesar cipher — shift letters using an alphabet lookup", "summary": "Caesar cipher — shift letters using an alphabet lookup Builds the shifted output by finding each character's position in the lowercase alphabet with index_of, rotating by the shift, and indexing back in. Non-letters pass through unchanged. Decrypt = encrypt with (26 - shift). Run: soma run caesar.cell --signal encrypt \"hello\" 3", "url": "https://soma-lang.dev/corpus/text/caesar.cell", "repo_path": "examples/corpus/text/caesar.cell", "lines": 49, "features": [], "cells": ["Caesar", "CaesarTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/csv", "domain": "text", "title": "CSV split/join — parse rows and project columns", "summary": "CSV split/join — parse rows and project columns Splits a CSV body into rows (by newline) and each row into fields (by comma), then maps header names to a list of record Maps. Demonstrates split on \"\\n\" and \",\", zipping headers to values, and join to re-serialize a row. Run: soma run csv.cell --signal parse \"name,age\\nAlice,30\\nBob,25\"", "url": "https://soma-lang.dev/corpus/text/csv.cell", "repo_path": "examples/corpus/text/csv.cell", "lines": 54, "features": ["pipeline", "lambda"], "cells": ["Csv", "CsvTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/csv_to_markdown", "domain": "text", "title": "CSV to Markdown table — render rows as a pipe-delimited table", "summary": "CSV to Markdown table — render rows as a pipe-delimited table Turns a CSV body into a GitHub-flavored Markdown table: a header row, a separator row of dashes, then one row per data line. Demonstrates splitting on newlines and commas, and assembling lines with join + interpolation. Run: soma run csv_to_markdown.cell --signal to_table \"name,age\\nAlice,30\"", "url": "https://soma-lang.dev/corpus/text/csv_to_markdown.cell", "repo_path": "examples/corpus/text/csv_to_markdown.cell", "lines": 49, "features": ["pipeline", "lambda"], "cells": ["CsvToMarkdown", "CsvToMarkdownTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/number_to_words", "domain": "text", "title": "Number to words — spell out integers 0..999 Composes English number words from ones/teens/tens tables", "summary": "Number to words — spell out integers 0..999 Composes English number words from ones/teens/tens tables. Demonstrates list-literal lookup tables indexed by digit, integer division with floor, and string assembly with trim to drop stray spaces. Run: soma run number_to_words.cell --signal spell 342", "url": "https://soma-lang.dev/corpus/text/number_to_words.cell", "repo_path": "examples/corpus/text/number_to_words.cell", "lines": 66, "features": [], "cells": ["NumberToWords", "NumberToWordsTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/pad_align", "domain": "text", "title": "Padding & alignment — left/right pad to a fixed width Builds padding by appending a fill character until the target width is met", "summary": "Padding & alignment — left/right pad to a fixed width Builds padding by appending a fill character until the target width is met. Used to right-align numbers and left-align labels into fixed columns. Demonstrates while-loop string growth and truncation via substring. Run: soma run pad_align.cell --signal pad_left \"42\" 5", "url": "https://soma-lang.dev/corpus/text/pad_align.cell", "repo_path": "examples/corpus/text/pad_align.cell", "lines": 52, "features": [], "cells": ["PadAlign", "PadAlignTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/palindrome", "domain": "text", "title": "Palindrome check — punctuation- and case-insensitive Strips everything but letters/digits, lowercases, then compares the cleaned string against its reverse", "summary": "Palindrome check — punctuation- and case-insensitive Strips everything but letters/digits, lowercases, then compares the cleaned string against its reverse. Demonstrates per-character filtering with s[i] and a descending range to build the reverse. Run: soma run palindrome.cell --signal is_palindrome \"A man, a plan, a canal: Panama\"", "url": "https://soma-lang.dev/corpus/text/palindrome.cell", "repo_path": "examples/corpus/text/palindrome.cell", "lines": 54, "features": [], "cells": ["Palindrome", "PalindromeTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/reverse_words", "domain": "text", "title": "Reverse word order — \"hello world\" -> \"world hello\" Splits on spaces, reverses the resulting list, and re-joins", "summary": "Reverse word order — \"hello world\" -> \"world hello\" Splits on spaces, reverses the resulting list, and re-joins. Also offers a per-word character reversal that keeps word positions. Demonstrates the difference between reversing the word list vs. reversing each word. Run: soma run reverse_words.cell --signal reverse_order \"the quick brown fox\"", "url": "https://soma-lang.dev/corpus/text/reverse_words.cell", "repo_path": "examples/corpus/text/reverse_words.cell", "lines": 46, "features": ["pipeline", "lambda"], "cells": ["ReverseWords", "ReverseWordsTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/rot13", "domain": "text", "title": "ROT13 — self-inverse letter rotation Rotates each letter by 13, preserving case; applying it twice restores the original", "summary": "ROT13 — self-inverse letter rotation Rotates each letter by 13, preserving case; applying it twice restores the original. Demonstrates two alphabet lookups (lower/upper), index_of for the source position, and the involution property in a test. Run: soma run rot13.cell --signal rot13 \"Hello, World\"", "url": "https://soma-lang.dev/corpus/text/rot13.cell", "repo_path": "examples/corpus/text/rot13.cell", "lines": 45, "features": [], "cells": ["Rot13", "Rot13Test"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/run_length", "domain": "text", "title": "Run-length encoding — compress repeated characters \"aaabbc\" -> \"a3b2c1\"", "summary": "Run-length encoding — compress repeated characters \"aaabbc\" -> \"a3b2c1\". Decoding walks the encoded string reading a letter followed by its digit-run count. Demonstrates per-char scanning, run counting, and reconstructing a string by repetition. Run: soma run run_length.cell --signal encode \"aaabbbcccd\"", "url": "https://soma-lang.dev/corpus/text/run_length.cell", "repo_path": "examples/corpus/text/run_length.cell", "lines": 66, "features": [], "cells": ["RunLength", "RunLengthTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/slugify", "domain": "text", "title": "Slugify — turn a title into a URL-safe slug", "summary": "Slugify — turn a title into a URL-safe slug Lowercases, keeps alphanumerics, turns every run of other characters into a single hyphen, and trims leading/trailing hyphens. Demonstrates a per-char accumulator with a \"last was separator\" flag to collapse runs. Run: soma run slugify.cell --signal slugify \"Hello, World! Foo--Bar\"", "url": "https://soma-lang.dev/corpus/text/slugify.cell", "repo_path": "examples/corpus/text/slugify.cell", "lines": 45, "features": [], "cells": ["Slugify", "SlugifyTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/substring_search", "domain": "text", "title": "Substring search — count and locate occurrences", "summary": "Substring search — count and locate occurrences Counts non-overlapping occurrences of a needle by repeatedly slicing past each match, and reports all start indices. Demonstrates index_of with a moving window via substring, and guarding against an empty needle. Run: soma run substring_search.cell --signal count_occurrences \"ababab\" \"ab\"", "url": "https://soma-lang.dev/corpus/text/substring_search.cell", "repo_path": "examples/corpus/text/substring_search.cell", "lines": 49, "features": [], "cells": ["SubstringSearch", "SubstringSearchTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/template", "domain": "text", "title": "Tiny template renderer — substitute [[key]] placeholders Fills each [[key]] in a template with its value", "summary": "Tiny template renderer — substitute [[key]] placeholders Fills each [[key]] in a template with its value. Keys and values are passed as two parallel lists (a Map *parameter* can't be key-iterated like a memory slot, so explicit lists are the portable idiom). We use square brackets because Soma string interpolation owns {curly} braces. Run: soma run template.cell --signal greet \"Bob\" \"Paris\"", "url": "https://soma-lang.dev/corpus/text/template.cell", "repo_path": "examples/corpus/text/template.cell", "lines": 43, "features": [], "cells": ["Template", "TemplateTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/title_case", "domain": "text", "title": "Title case — capitalize the first letter of every word Splits on spaces, uppercases each word's first character and lowercases the rest, then re-joins", "summary": "Title case — capitalize the first letter of every word Splits on spaces, uppercases each word's first character and lowercases the rest, then re-joins. Demonstrates substring slicing and per-word transforms mapped over the word list. Run: soma run title_case.cell --signal titlecase \"the QUICK brown fox\"", "url": "https://soma-lang.dev/corpus/text/title_case.cell", "repo_path": "examples/corpus/text/title_case.cell", "lines": 40, "features": ["pipeline", "lambda"], "cells": ["TitleCase", "TitleCaseTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/tokenizer", "domain": "text", "title": "Tokenizer — split text into normalized word tokens Lowercases the input, replaces punctuation with spaces, then splits on whitespace and drops empty fragments", "summary": "Tokenizer — split text into normalized word tokens Lowercases the input, replaces punctuation with spaces, then splits on whitespace and drops empty fragments. Demonstrates replace/lowercase/split and list filtering with a lambda. Run: soma run tokenizer.cell --signal tokenize \"Hello, World! Hello...\"", "url": "https://soma-lang.dev/corpus/text/tokenizer.cell", "repo_path": "examples/corpus/text/tokenizer.cell", "lines": 45, "features": ["pipeline", "lambda"], "cells": ["Tokenizer", "TokenizerTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/vowel_count", "domain": "text", "title": "Vowel / consonant counter Walks each character, classifying letters as vowels or consonants and ignoring everything else", "summary": "Vowel / consonant counter Walks each character, classifying letters as vowels or consonants and ignoring everything else. Demonstrates membership testing with contains() over a vowel set and returning a small summary Map. Run: soma run vowel_count.cell --signal analyze \"Hello World\"", "url": "https://soma-lang.dev/corpus/text/vowel_count.cell", "repo_path": "examples/corpus/text/vowel_count.cell", "lines": 55, "features": [], "cells": ["VowelCount", "VowelCountTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "text/word_frequency", "domain": "text", "title": "Word frequency — count occurrences of each word Splits a sentence into words and tallies each into a Map using a list-of words walk", "summary": "Word frequency — count occurrences of each word Splits a sentence into words and tallies each into a Map using a list-of words walk. Demonstrates building a frequency Map with get-or-default and in-place map writes. Run: soma run word_frequency.cell --signal frequency \"the cat the dog the\"", "url": "https://soma-lang.dev/corpus/text/word_frequency.cell", "repo_path": "examples/corpus/text/word_frequency.cell", "lines": 54, "features": [], "cells": ["WordFrequency", "WordFrequencyTest"], "verified": {"check": true, "test": true, "verify": true}}, {"id": "web/blog_tags", "domain": "web", "title": "Mini blog API with tag filtering", "summary": "Mini blog API with tag filtering. Posts carry a list of tags; GET /posts?tag=X filters in-memory using a pipe over stored records.", "url": "https://soma-lang.dev/corpus/web/blog_tags.cell", "repo_path": "examples/corpus/web/blog_tags.cell", "lines": 61, "features": ["http", "pipeline", "match", "lambda"], "cells": ["Blog", "BlogTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/contact_form", "domain": "web", "title": "Form handler with server-side validation", "summary": "Form handler with server-side validation. POST /contact validates each field and either stores the submission or returns a 422 with field errors.", "url": "https://soma-lang.dev/corpus/web/contact_form.cell", "repo_path": "examples/corpus/web/contact_form.cell", "lines": 54, "features": ["http", "match"], "cells": ["ContactForm", "ContactFormTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/counter_api", "domain": "web", "title": "Counter API: a persistent integer counter exposed over HTTP", "summary": "Counter API: a persistent integer counter exposed over HTTP. One fat `on request` routes GET/POST. State lives in a [persistent] slot. curl -X POST localhost:8080/inc ; curl localhost:8080/value", "url": "https://soma-lang.dev/corpus/web/counter_api.cell", "repo_path": "examples/corpus/web/counter_api.cell", "lines": 68, "features": ["http", "match"], "cells": ["CounterApi", "CounterApiTest"], "usage": ["soma serve counter_api.cell"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/feature_flags", "domain": "web", "title": "Feature-flag service: toggle named flags on/off, query state, list all", "summary": "Feature-flag service: toggle named flags on/off, query state, list all. Booleans stored as \"on\"/\"off\" strings in a persistent map.", "url": "https://soma-lang.dev/corpus/web/feature_flags.cell", "repo_path": "examples/corpus/web/feature_flags.cell", "lines": 61, "features": ["http", "match"], "cells": ["Flags", "FlagsTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/guestbook", "domain": "web", "title": "Guestbook: append-only signed entries, rendered as a small HTML page", "summary": "Guestbook: append-only signed entries, rendered as a small HTML page. The form POSTs name+message; entries are stored in an immutable log. curl -X POST localhost:8080/sign -d '{\"name\":\"Ada\",\"message\":\"hi\"}'", "url": "https://soma-lang.dev/corpus/web/guestbook.cell", "repo_path": "examples/corpus/web/guestbook.cell", "lines": 66, "features": ["http", "match"], "cells": ["Guestbook", "GuestbookTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/kv_store", "domain": "web", "title": "Key-value store API with namespaced keys and a bulk export endpoint", "summary": "Key-value store API with namespaced keys and a bulk export endpoint. PUT /kv/<key> sets, GET reads, DELETE removes, GET /kv exports all.", "url": "https://soma-lang.dev/corpus/web/kv_store.cell", "repo_path": "examples/corpus/web/kv_store.cell", "lines": 65, "features": ["http", "match"], "cells": ["KvStore", "KvStoreTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/leaderboard", "domain": "web", "title": "Leaderboard API: submit a score, get the ranked top-N", "summary": "Leaderboard API: submit a score, get the ranked top-N. Keeps the best score per player and returns a sorted slice.", "url": "https://soma-lang.dev/corpus/web/leaderboard.cell", "repo_path": "examples/corpus/web/leaderboard.cell", "lines": 86, "features": ["http", "pipeline", "match"], "cells": ["Leaderboard", "LeaderboardTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/metrics_api", "domain": "web", "title": "Metrics / health endpoint", "summary": "Metrics / health endpoint. Every request bumps a request counter; GET /health returns status + uptime-style fields, GET /metrics the tallies.", "url": "https://soma-lang.dev/corpus/web/metrics_api.cell", "repo_path": "examples/corpus/web/metrics_api.cell", "lines": 63, "features": ["http", "match"], "cells": ["Metrics", "MetricsTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/notes_crud", "domain": "web", "title": "CRUD JSON API over a persistent Map: notes with title + body", "summary": "CRUD JSON API over a persistent Map: notes with title + body. Returns Maps directly (auto-serialized to JSON) and 404 responses on miss. curl -X POST localhost:8080/api/notes -d '{\"title\":\"hi\",\"body\":\"world\"}'", "url": "https://soma-lang.dev/corpus/web/notes_crud.cell", "repo_path": "examples/corpus/web/notes_crud.cell", "lines": 77, "features": ["http", "match"], "cells": ["Notes", "NotesTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/paginated_list", "domain": "web", "title": "Paginated product list: GET /products?page=N&size=M slices a stored list", "summary": "Paginated product list: GET /products?page=N&size=M slices a stored list. Returns a Map with items + pagination metadata (total, page, pages).", "url": "https://soma-lang.dev/corpus/web/paginated_list.cell", "repo_path": "examples/corpus/web/paginated_list.cell", "lines": 57, "features": ["http", "match"], "cells": ["Catalog", "CatalogTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/poll_api", "domain": "web", "title": "Voting / poll API: fixed options, one counter per option, results sorted", "summary": "Voting / poll API: fixed options, one counter per option, results sorted. POST /vote/<option> increments; GET /results returns sorted tallies.", "url": "https://soma-lang.dev/corpus/web/poll_api.cell", "repo_path": "examples/corpus/web/poll_api.cell", "lines": 63, "features": ["http", "pipeline", "match", "lambda"], "cells": ["Poll", "PollTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/sessions", "domain": "web", "title": "Session/login toy: POST /login issues a token, GET /me/<token> returns the user, POST /logout invalidates it", "summary": "Session/login toy: POST /login issues a token, GET /me/<token> returns the user, POST /logout invalidates it. Tokens map to usernames.", "url": "https://soma-lang.dev/corpus/web/sessions.cell", "repo_path": "examples/corpus/web/sessions.cell", "lines": 58, "features": ["http", "match"], "cells": ["Sessions", "SessionsTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/site_router", "domain": "web", "title": "Multi-page static site: home, about, and a dynamic greeting route", "summary": "Multi-page static site: home, about, and a dynamic greeting route. Demonstrates html() pages, path captures, and a 404 fallthrough.", "url": "https://soma-lang.dev/corpus/web/site_router.cell", "repo_path": "examples/corpus/web/site_router.cell", "lines": 42, "features": ["http", "match"], "cells": ["Site", "SiteTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/todo_state", "domain": "web", "title": "Todo service backed by a typed state machine (sum type TodoStatus)", "summary": "Todo service backed by a typed state machine (sum type TodoStatus). Each todo transitions Pending -> InProgress -> Done, or * -> Cancelled.", "url": "https://soma-lang.dev/corpus/web/todo_state.cell", "repo_path": "examples/corpus/web/todo_state.cell", "lines": 82, "features": ["state_machine", "sum_type", "http", "match"], "cells": ["TodoStatus", "TodoService", "TodoServiceTest"], "verified": {"check": true, "test": true, "verify": true}, "verify": "11 passed, 1 warnings, 0 failures; temporal 2 passed, 0 failed", "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/url_shortener", "domain": "web", "title": "URL shortener: POST a long URL, get a short code; GET the code redirects", "summary": "URL shortener: POST a long URL, get a short code; GET the code redirects. Base36 code derived from a monotonic id. Hit count tracked per code. curl -X POST localhost:8080/shorten -d '{\"url\":\"https://soma.dev\"}' curl -i localhost:8080/r/<code>", "url": "https://soma-lang.dev/corpus/web/url_shortener.cell", "repo_path": "examples/corpus/web/url_shortener.cell", "lines": 75, "features": ["http", "match"], "cells": ["Shortener", "ShortenerTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}, {"id": "web/webhook_log", "domain": "web", "title": "Webhook receiver + event log", "summary": "Webhook receiver + event log. POST /hook/<source> appends an event; GET /events returns recent events newest-first with a bounded capacity.", "url": "https://soma-lang.dev/corpus/web/webhook_log.cell", "repo_path": "examples/corpus/web/webhook_log.cell", "lines": 71, "features": ["http", "pipeline", "match", "lambda"], "cells": ["Webhooks", "WebhooksTest"], "verified": {"check": true, "test": true, "verify": true}, "manifest": "https://soma-lang.dev/corpus/web/soma.toml"}]}