government

commit da006f04d8870dcf444b3b0380729d78f076b2ea

tree

parent:
acb25bc2dcb663eb679fb19123bf0471f5c3c349

nmyk <nick@nmyk.io>

2026-11-14T17:18:12-05:00

implement government run

diff --git a/DESIGN.md b/DESIGN.md
index a6c9586e9407bd1b9bcdd58ad44c56f97b014f2f..0efe165ed484fceb1e177f358ed4c4100ad51666 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -302,6 +302,7 @@ | `cmd/government` | CLI |
 | `ratify` | PEM loading; path validation (§6.1.3 a–c, 6.1.4 k–n); critical-extension check |
 | `policy` | RFC 9618 policy graph; strict check; node budget |
 | `ast` | Graph to AST: skipping copies, ordering, OID decoding, structural errors |
+| `program` | The whole load path: ratify, policy graph, decode; maps runtime errors back to node OIDs |
 | `eval` | Values, environments, special forms, builtins, trampoline for tail calls |
 | `sexpr` | Lisp reader and printer, shared by the transpiler, decompiler and tests |
 | `lisp2gov` | Transpiler: s-expressions to `.gov` |
diff --git a/cmd/government/main.go b/cmd/government/main.go
index a3a1efbf4ed01be38d5cd71778835645d7485037..f9c7b6bcc7106d10c10075fede0f63fff380c0d2 100644
--- a/cmd/government/main.go
+++ b/cmd/government/main.go
@@ -1,6 +1,6 @@
 // Command government runs GOVERNMENT programs.
 //
-// Only compile exists so far. The other subcommands arrive in later steps
+// Only compile and run exist so far. The other subcommands arrive in later steps
 // of PLAN.md.
 package main
 
@@ -10,8 +10,11 @@ 	"io"
 	"os"
 )
 
+// Exit codes: a runtime error is 1; anything that stops a program from
+// running at all (bad usage, a refused or undecodable file) is 2.
 const (
 	exitOK      = 0
+	exitRuntime = 1
 	exitInvalid = 2
 )
 
@@ -19,9 +22,9 @@ const usage = `usage: government <command> [arguments]
 
 commands:
   compile    transpile Lisp source to .gov
+  run        ratify, decode and evaluate a .gov program
 
 not yet implemented:
-  run        ratify, decode and evaluate a .gov program
   verify     ratify and decode only
   tree       print the policy tree
   decompile  print equivalent Lisp source
@@ -40,6 +43,8 @@ 	}
 	switch args[0] {
 	case "compile":
 		return compile(args[1:], stdout, stderr)
+	case "run":
+		return runProgram(args[1:], stdout, stderr)
 	case "help", "-h", "-help", "--help":
 		fmt.Fprint(stdout, usage)
 		return exitOK
diff --git a/cmd/government/run.go b/cmd/government/run.go
new file mode 100644
index 0000000000000000000000000000000000000000..843c10bc83e4e3f0d2f24a37e535c411306384df
--- /dev/null
+++ b/cmd/government/run.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+	"flag"
+	"fmt"
+	"io"
+	"os"
+
+	"government/policy"
+	"government/program"
+)
+
+func runProgram(args []string, stdout, stderr io.Writer) int {
+	fs := flag.NewFlagSet("run", flag.ContinueOnError)
+	fs.SetOutput(stderr)
+	at := addAtFlag(fs)
+	anchor := addAnchorFlag(fs)
+	maxNodes := fs.Int("max-nodes", policy.DefaultMaxNodes, "refuse programs whose policy graph needs more than `n` nodes")
+	fs.Usage = func() {
+		fmt.Fprintln(stderr, "usage: government run prog.gov [-at time] [-anchor file] [-max-nodes n]")
+		fs.PrintDefaults()
+	}
+	positional, err := parseInterspersed(fs, args)
+	if err != nil {
+		return exitInvalid
+	}
+	if len(positional) != 1 {
+		fs.Usage()
+		return exitInvalid
+	}
+	path := positional[0]
+
+	data, err := os.ReadFile(path)
+	if err != nil {
+		fmt.Fprintln(stderr, err)
+		return exitInvalid
+	}
+	p, err := program.Load(data, program.Options{At: at.Time(), Pin: anchor.Pin(), MaxNodes: *maxNodes})
+	if err != nil {
+		fmt.Fprintf(stderr, "%s: %v\n", path, err)
+		return exitInvalid
+	}
+	if err := p.Run(stdout); err != nil {
+		fmt.Fprintf(stderr, "%s: %s\n", path, p.Describe(err))
+		return exitRuntime
+	}
+	return exitOK
+}
diff --git a/cmd/government/run_test.go b/cmd/government/run_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7fbc92e9d5b2845f39b9dc4945e1f41c1c52114c
--- /dev/null
+++ b/cmd/government/run_test.go
@@ -0,0 +1,78 @@
+package main
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+func compileTo(t *testing.T, dir, name, src string, extra ...string) string {
+	t.Helper()
+	lisp := filepath.Join(dir, name+".gov.lisp")
+	gov := filepath.Join(dir, name+".gov")
+	os.WriteFile(lisp, []byte(src), 0o644)
+	args := append([]string{"compile", lisp, "-o", gov}, extra...)
+	if code, _, stderr := runCmd(args...); code != exitOK {
+		t.Fatalf("compile: exit %d: %s", code, stderr)
+	}
+	return gov
+}
+
+func TestRunExample(t *testing.T) {
+	gov := filepath.Join(t.TempDir(), "sq.gov")
+	if code, _, stderr := runCmd("compile", "../../examples/sq.gov.lisp", "-o", gov); code != exitOK {
+		t.Fatal(stderr)
+	}
+	code, stdout, stderr := runCmd("run", gov)
+	if code != exitOK || stdout != "144\n" {
+		t.Errorf("exit %d, stdout %q, stderr %q", code, stdout, stderr)
+	}
+}
+
+func TestRunRuntimeError(t *testing.T) {
+	gov := compileTo(t, t.TempDir(), "bad", "1\n(car '())\n2\n")
+	code, stdout, stderr := runCmd("run", gov)
+	if code != exitRuntime || stdout != "1\n" || !strings.Contains(stderr, "E-TYPE: car needs a pair, got () at GOV.0.2.1 (depth 1)") {
+		t.Errorf("exit %d, stdout %q, stderr %q", code, stdout, stderr)
+	}
+}
+
+func TestRunRefusals(t *testing.T) {
+	dir := t.TempDir()
+	gov := compileTo(t, dir, "p", "(+ 1 2)")
+	data, _ := os.ReadFile(gov)
+	tampered := filepath.Join(dir, "tampered.gov")
+	i := strings.LastIndex(string(data), "-----END")
+	broken := []byte(string(data))
+	broken[i-5] ^= 1 // a base64 character near the end: inside the signature
+	os.WriteFile(tampered, broken, 0o644)
+
+	tests := []struct {
+		args []string
+		want string
+	}{
+		{[]string{"run", gov, "-at", "1999-01-01T00:00:00Z"}, "E-NOT-IN-FORCE"},
+		{[]string{"run", gov, "-max-nodes", "2"}, "E-TOO-LARGE"},
+		{[]string{"run", gov, "-at", "yesterday"}, "RFC 3339"},
+		{[]string{"run", tampered}, "E-"},
+		{[]string{"run", filepath.Join(dir, "missing.gov")}, "no such file"},
+		{[]string{"run"}, "usage"},
+	}
+	for _, tt := range tests {
+		code, _, stderr := runCmd(tt.args...)
+		if code != exitInvalid || !strings.Contains(stderr, tt.want) {
+			t.Errorf("%v: exit %d, stderr %q; want exit %d mentioning %q", tt.args, code, stderr, exitInvalid, tt.want)
+		}
+	}
+}
+
+func TestRunWithAnchor(t *testing.T) {
+	dir := t.TempDir()
+	mine := compileTo(t, dir, "mine", "(+ 1 2)")
+	other := compileTo(t, dir, "other", "(* 2 3)")
+	if code, stdout, stderr := runCmd("run", "-anchor", mine, other); code != exitOK || stdout != "6\n" {
+		// Same default seed, so the same author: the pin matches.
+		t.Errorf("same author: exit %d, %q, %q", code, stdout, stderr)
+	}
+}
diff --git a/internal/lisptest/lisptest.go b/internal/lisptest/lisptest.go
index a18e54cdf0cbb6355005cee2bc07948f3c5512f0..dfdc12cb554daaabc92eb8f2a1ef54c62bd589a9 100644
--- a/internal/lisptest/lisptest.go
+++ b/internal/lisptest/lisptest.go
@@ -149,3 +149,20 @@ 		return s[:max-3] + "..."
 	}
 	return s
 }
+
+// WithForms returns a copy of f whose cases evaluate forms instead of the
+// forms read from source, keeping each case's annotation and position.
+// The test runner uses it to run a file's compiled .gov program against
+// the expectations written in its source.
+func (f *File) WithForms(forms []sexpr.Value) (*File, error) {
+	if len(forms) != len(f.Cases) {
+		return nil, fmt.Errorf("%s: %d forms for %d cases", f.Name, len(forms), len(f.Cases))
+	}
+	g := *f
+	g.Cases = make([]Case, len(f.Cases))
+	for i, c := range f.Cases {
+		c.Form = forms[i]
+		g.Cases[i] = c
+	}
+	return &g, nil
+}
diff --git a/internal/lisptest/lisptest_test.go b/internal/lisptest/lisptest_test.go
index fe25e8b6ee4efe4897238d452a7373cb19d0c107..a7f3ef0c5dde7cb914441c00df8d64eddbcffcbd 100644
--- a/internal/lisptest/lisptest_test.go
+++ b/internal/lisptest/lisptest_test.go
@@ -2,6 +2,7 @@ package lisptest
 
 import (
 	"fmt"
+	"government/sexpr"
 	"strings"
 	"testing"
 
@@ -85,3 +86,24 @@ 	if strings.Join(r.errors, "\n---\n") != strings.Join(want, "\n---\n") {
 		t.Errorf("reported:\n%s\n\nwant:\n%s", strings.Join(r.errors, "\n---\n"), strings.Join(want, "\n---\n"))
 	}
 }
+
+func TestWithForms(t *testing.T) {
+	f, err := Parse("t.gov.lisp", "(+ 1 1) ;=> 2\n(car 1) ;=! needs a pair\n")
+	if err != nil {
+		t.Fatal(err)
+	}
+	other, err := sexpr.ReadAll("(+ 1 1) (car 1)")
+	if err != nil {
+		t.Fatal(err)
+	}
+	g, err := f.WithForms(other)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if g.Cases[0].Form != other[0] || g.Cases[1].Want != "needs a pair" || f.Cases[0].Form == other[0] {
+		t.Error("WithForms did not swap the forms and keep the annotations")
+	}
+	if _, err := f.WithForms(other[:1]); err == nil {
+		t.Error("a form count mismatch was accepted")
+	}
+}
diff --git a/lisp_test.go b/lisp_test.go
index 0f0703cf23f7c4a4a37763587a83ac5b5a0472a9..0fb2dfb7ad899223b066c547f15288ca2d183c67 100644
--- a/lisp_test.go
+++ b/lisp_test.go
@@ -3,15 +3,20 @@
 import (
 	"os"
 	"path/filepath"
+	"reflect"
 	"testing"
+	"time"
 
 	"government/eval"
 	"government/internal/lisptest"
+	"government/lisp2gov"
+	"government/program"
 )
 
-// TestLispFiles runs every testdata/*.gov.lisp file straight from source text.
-// Step 5.4 switches this to compiling each file to .gov and running the
-// result.
+// TestLispFiles compiles every testdata/*.gov.lisp file to a .gov program,
+// runs that program through the whole pipeline (ratify, policy graph,
+// decode, evaluate), and checks each form against the expectation written
+// in the source.
 func TestLispFiles(t *testing.T) {
 	paths, err := filepath.Glob("testdata/*.gov.lisp")
 	if err != nil {
@@ -30,7 +35,24 @@ 			f, err := lisptest.Parse(path, string(src))
 			if err != nil {
 				t.Fatal(err)
 			}
-			lisptest.Run(t, f, eval.NewTopLevel())
+			data, err := lisp2gov.Compile(string(src), lisp2gov.Options{})
+			if err != nil {
+				t.Fatal(err)
+			}
+			p, err := program.Load(data, program.Options{At: time.Now()})
+			if err != nil {
+				t.Fatal(err)
+			}
+			compiled, err := f.WithForms(p.Forms)
+			if err != nil {
+				t.Fatal(err)
+			}
+			for i, c := range f.Cases {
+				if !reflect.DeepEqual(c.Form, p.Forms[i]) {
+					t.Errorf("%s:%v: the program decodes to a different form", path, c.Pos)
+				}
+			}
+			lisptest.Run(t, compiled, eval.NewTopLevel())
 		})
 	}
 }
diff --git a/program/program.go b/program/program.go
new file mode 100644
index 0000000000000000000000000000000000000000..17d183e3bcbf53c58cea38bc9f59cebf4a1aa31c
--- /dev/null
+++ b/program/program.go
@@ -0,0 +1,129 @@
+// Package program is the whole path from a .gov file to something the
+// evaluator can run: ratify the chain, rebuild the policy graph, decode it
+// into a tree, and turn the tree into values.
+//
+// It is also the trust boundary. Everything before Load returns is checking
+// untrusted bytes; everything after it runs code that passed every check.
+package program
+
+import (
+	"fmt"
+	"io"
+	"time"
+
+	"government/ast"
+	"government/eval"
+	"government/policy"
+	"government/ratify"
+	"government/sexpr"
+)
+
+// ErrDecode: the policy graph is valid but does not decode to a program,
+// e.g. a list node with no elements.
+const ErrDecode = "E-DECODE"
+
+type Error struct {
+	Code string
+	Msg  string
+}
+
+func (e *Error) Error() string { return e.Code + ": " + e.Msg }
+
+type Options struct {
+	At       time.Time
+	Pin      ratify.Pin
+	MaxNodes int
+}
+
+// Program is a ratified, decoded program.
+type Program struct {
+	Forms   []sexpr.Value
+	origins ast.Origins
+	depth   map[*ast.Node]int
+}
+
+// Load runs every check on a .gov file and decodes it. Any error it returns
+// means the program may not run: a ratify, policy or decode error.
+func Load(data []byte, opts Options) (*Program, error) {
+	certs, err := ratify.Ratify(data, ratify.Options{At: opts.At, Pin: opts.Pin})
+	if err != nil {
+		return nil, err
+	}
+	g, err := policy.Program(certs, policy.Options{MaxNodes: opts.MaxNodes})
+	if err != nil {
+		return nil, err
+	}
+	layers, err := g.Layers()
+	if err != nil {
+		return nil, &Error{ErrDecode, err.Error()}
+	}
+	tree, err := ast.Unlayer(layers)
+	if err != nil {
+		return nil, &Error{ErrDecode, err.Error()}
+	}
+	forms, origins, err := ast.FromTree(tree)
+	if err != nil {
+		return nil, &Error{ErrDecode, err.Error()}
+	}
+	p := &Program{Forms: forms, origins: origins, depth: map[*ast.Node]int{}}
+	var walk func(n *ast.Node, d int)
+	walk = func(n *ast.Node, d int) {
+		p.depth[n] = d
+		for _, c := range n.Children {
+			walk(c, d+1)
+		}
+	}
+	for _, f := range tree.Forms {
+		walk(f, 1)
+	}
+	return p, nil
+}
+
+// Locate names where an evaluation error happened: the OID of the
+// innermost list being evaluated and its depth, which is the cert that
+// holds it. A .gov program has no line numbers; this is its equivalent.
+func (p *Program) Locate(err error) string {
+	e, ok := err.(*eval.Error)
+	if !ok {
+		return ""
+	}
+	pair, ok := e.Expr.(*sexpr.Pair)
+	if !ok {
+		return ""
+	}
+	n, ok := p.origins[pair]
+	if !ok {
+		return ""
+	}
+	return fmt.Sprintf("%s (depth %d)", n, p.depth[n])
+}
+
+// Run evaluates the forms in order, printing the value of each one that is
+// not a define, and stops at the first error.
+func (p *Program) Run(out io.Writer) error {
+	top := eval.NewTopLevel()
+	for _, form := range p.Forms {
+		v, err := top.Eval(form)
+		if err != nil {
+			return err
+		}
+		if !IsDefine(form) {
+			fmt.Fprintln(out, sexpr.Print(v))
+		}
+	}
+	return nil
+}
+
+// Describe formats an evaluation error with its location, as `government
+// run` prints it.
+func (p *Program) Describe(err error) string {
+	if where := p.Locate(err); where != "" {
+		return err.Error() + " at " + where
+	}
+	return err.Error()
+}
+
+func IsDefine(form sexpr.Value) bool {
+	pair, ok := form.(*sexpr.Pair)
+	return ok && pair.Car == sexpr.Value(sexpr.Symbol("define"))
+}
diff --git a/program/program_test.go b/program/program_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a96c09d6dc1441f53f6e52af39326952ca3c8df4
--- /dev/null
+++ b/program/program_test.go
@@ -0,0 +1,77 @@
+package program
+
+import (
+	"bytes"
+	"errors"
+	"strings"
+	"testing"
+	"time"
+
+	"government/lisp2gov"
+	"government/ratify"
+)
+
+var now = time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
+
+func load(t *testing.T, src string) *Program {
+	t.Helper()
+	data, err := lisp2gov.Compile(src, lisp2gov.Options{})
+	if err != nil {
+		t.Fatal(err)
+	}
+	p, err := Load(data, Options{At: now})
+	if err != nil {
+		t.Fatal(err)
+	}
+	return p
+}
+
+func TestRun(t *testing.T) {
+	p := load(t, "(define sq (lambda (x) (* x x))) (sq 12) \"done\"")
+	var out bytes.Buffer
+	if err := p.Run(&out); err != nil {
+		t.Fatal(err)
+	}
+	if got, want := out.String(), "144\n\"done\"\n"; got != want {
+		t.Errorf("output %q, want %q", got, want)
+	}
+}
+
+func TestErrorsNameTheirOID(t *testing.T) {
+	// Node ids: (#1 define#2 f#3 (#4 lambda#5 (#6 x#7) (#8 +#9 x#10 z#11)))
+	// (#12 f#13 1#14). The failing list is (+ x z), node 8, at depth 3.
+	p := load(t, "(define f (lambda (x) (+ x z))) (f 1)")
+	err := p.Run(&bytes.Buffer{})
+	if err == nil {
+		t.Fatal("no error")
+	}
+	got := p.Describe(err)
+	want := "E-UNBOUND: no statute for symbol z at GOV.0.8.1 (depth 3)"
+	if got != want {
+		t.Errorf("got  %s\nwant %s", got, want)
+	}
+}
+
+func TestLoadRefusals(t *testing.T) {
+	data, err := lisp2gov.Compile("(+ 1 2)", lisp2gov.Options{})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := Load(data, Options{At: time.Date(1999, 1, 1, 0, 0, 0, 0, time.UTC)}); !hasCode(err, ratify.ErrNotInForce) {
+		t.Errorf("before the window: %v", err)
+	}
+	pin, _ := ratify.LoadPin(data)
+	seed := [32]byte{9}
+	other, _ := lisp2gov.Compile("(+ 1 2)", lisp2gov.Options{Seed: &seed})
+	if _, err := Load(other, Options{At: now, Pin: pin}); !hasCode(err, ratify.ErrForeign) {
+		t.Errorf("foreign: %v", err)
+	}
+	if _, err := Load(data, Options{At: now, MaxNodes: 2}); err == nil || !strings.Contains(err.Error(), "E-TOO-LARGE") {
+		t.Errorf("budget: %v", err)
+	}
+}
+
+func hasCode(err error, code string) bool {
+	var e *ratify.Error
+	return errors.As(err, &e) && e.Code == code
+}