Scripts are where Varyonic discipline pays off most. A typical script starts small, accumulates side effects, and becomes untestable. The Varyonic approach structures scripts into five phases:
Resolve context → Decode inputs → Build plan → Execute effects → Emit report
Each phase is a pure function (except Execute) that returns typed data. Only main() calls system.exit() or writes to stderr. This makes every phase independently testable and every decision observable under mutation.
| Phase | Responsibility | Pure? | Returns |
|---|---|---|---|
| Resolve | Locate files, determine paths | Yes | data with resolved paths |
| Decode | Parse and validate inputs | Yes | Result[T, ScriptError] |
| Plan | Decide what work to do | Yes | data describing work items |
| Execute | Perform side effects | No | Result[Report, ScriptError] |
| Report | Format results for output | Yes | Structured report data |
main() is a thin shell that calls each phase, handles errors, and prints results.
generate-test-docsThe generate-test-docs script reads a JSON test inventory, renders Markdown docs through templates, and writes the output files. Here is what the old version looked like and how it was refactored.
Before (stringly typed, exit-in-helpers):
# Helpers call system.exit() and system.stderr() directly
def load_json(path: Str) -> Json {
let content = load_text_unsafely(path)
if content == "" {
system.stderr().write("error: cannot read " + path + "\n")
system.exit(1)
}
return Json.parse(content).unwrap()
}
def write_output(path: Str, content: Str) {
let result = fs.write_text(fs.write_path(path).unwrap(), content)
if result.is_err() {
system.stderr().write("error: cannot write " + path + "\n")
system.exit(1)
}
}
def main() {
# Path logic inlined and duplicated
let base = system.cwd()
let inv = load_json(base + "/ci-artifacts/test-inventory.json")
# Template rendering mixed with file writing
let engine = Template.create(base + "/programs/generate-test-docs/templates")
let rendered = engine.render("test-inventory.md.peb", inv)
write_output(base + "/website/content/docs/test-inventory.md", rendered)
let rendered2 = engine.render("test-matrix.md.peb", inv)
write_output(base + "/docs/test-matrix.md", rendered2)
print("Done")
}
Problems with this style:
| Problem | Consequence |
|---|---|
load_json and write_output call system.exit() | Tests cannot exercise error paths without killing the process. |
| No typed domain model | The JSON is passed around as an opaque Json value with no validation. |
| Planning and execution are interleaved | You cannot test "what would be generated" without actually writing files. |
| Mutation testing cannot kill mutants in error handling | Errors terminate the process, making mutants invisible. |
After (five-phase Varyonic structure):
import system
import path
import json
import template
# Phase 0: Domain types
data ScriptPaths {
repo_root: Str
template_dir: Str
inventory_json: Str
}
enum ScriptError {
Input(path: Str, message: Str)
Decode(field: Str, message: Str)
Render(template: Str, message: Str)
Output(path: Str, message: Str)
}
data Inventory {
suites: Dict[Str, SuiteTotals]
totals: InventoryTotals
}
data GenerationTarget {
template_name: Str
output_rel_path: Str
}
data GenerationPlan {
targets: List[GenerationTarget]
}
data GenerationReport {
files_generated: Int
output_paths: List[Str]
}
# Phase 1: Resolve context
def resolve_paths() -> ScriptPaths {
let sd = system.script_dir()
mut base: Str = system.cwd()
if sd is not None {
base = path.normalize(path.join(path.parent(sd), ".."))
}
return ScriptPaths(base,
path.join(base, "programs/generate-test-docs/templates"),
path.join(base, "ci-artifacts/test-inventory.json"))
}
# Phase 2: Decode inputs
def decode_inventory(inv: Json) -> Result[Inventory, ScriptError] {
let suites_obj = inv.get_object("suites")
if suites_obj is None {
return Err(ScriptError.Decode("suites", "missing required field"))
}
# ... validate and decode each field, returning Err on failure
return Ok(Inventory(suites_dict, totals))
}
# Phase 3: Build plan
def build_plan() -> GenerationPlan {
return GenerationPlan([
GenerationTarget("test-inventory.md.peb", "website/content/docs/test-inventory.md"),
GenerationTarget("test-matrix.md.peb", "docs/test-matrix.md")
])
}
# Phase 4: Execute effects
def run_generation(plan: GenerationPlan, paths: ScriptPaths,
inventory: Json) -> Result[GenerationReport, ScriptError] {
let engine = template.create(paths.template_dir)
mut {
generated: Int = 0
output_paths: List[Str] = []
}
for target in plan.targets {
# render + write, returning Err on failure
generated = generated + 1
output_paths = output_paths + [target.output_rel_path]
}
return Ok(GenerationReport(generated, output_paths))
}
# Phase 5: main (the only place with exit/stderr)
def main() {
let paths = resolve_paths()
let inv = load_inventory_json(paths.inventory_json)
# ... match on Err, write to stderr, exit(1)
let decoded = decode_inventory(inv.unwrap())
# ... match on Err, write to stderr, exit(1)
let plan = build_plan()
let report = run_generation(plan, paths, inv.unwrap())
# ... match on Err, write to stderr, exit(1)
print(f"Generated {report.unwrap().files_generated} files")
}
Testability. Each phase is a function that takes data and returns data. Tests call resolve_paths(), decode_inventory(), build_plan(), and run_generation() directly, with no mocking and no filesystem setup for the pure phases:
test "decode rejects missing suites" {
let inv = Json.parse("{\"totals\": {\"total_files\": 1, \"total_test_cases\": 2}}")
let result = decode_inventory(inv.unwrap())
observe result.is_err()
}
test "plan contains expected targets" {
let plan = build_plan()
observe plan.targets.len() == 2
}
Mutation resistance. Because every decision returns a value, mutation testing can kill mutants by asserting on that value. In the old style, a mutant that changes system.exit(1) to system.exit(0) is invisible to tests because the process dies either way. In the new style, a mutant that changes ScriptError.Decode to ScriptError.Input is caught by a test that matches on the error variant.
LLM-assisted maintenance. An LLM modifying this script can:
| Action | Benefit |
|---|---|
Add a ScriptError variant | The compiler flags every match that needs updating |
Add a GenerationTarget | The execution loop stays unchanged |
Add checks to decode_inventory | Pure function with clear inputs and outputs |
The phase boundaries act as natural seams. An LLM does not need to understand the whole script to safely modify one phase.