government

commit 29fbe69f4da4ce1dc5603c685ced1955b2808761

tree

parent:
844f0e3dd48aea4963c188d8ad2ed9749ed3e7f0

nmyk <nick@nmyk.io>

2026-11-14T16:36:40-05:00

use .gov.lisp extension for govlisp files

diff --git a/DESIGN.md b/DESIGN.md
index fb3feb506650a010b332f89dc85f699e8c32dd58..29154b0ca938183f5bb412de813e3fe6437afc5e 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -33,7 +33,7 @@ A `.gov` file is one UTF-8 text file of concatenated PEM `CERTIFICATE` blocks: a trust anchor first, then one certificate per tree depth, top-down.
 
 - **Block 0** is the trust anchor (self-signed). It carries no policies.
 - **Blocks 1..n** are the certification path. Certificate *i* is issued by certificate *i−1* and carries every node at depth *i* of the tree. So *n* equals the program's AST depth.
-- Text outside PEM blocks is ignored, as PEM allows. This gives free header comments, e.g. the original Lisp source.
+- Text outside PEM blocks is ignored, as PEM allows. The compiler writes nothing there by default (the program's name is already in every subject as `O=`). With `-source` it writes the original Lisp source, indented so no line of it can start a PEM block. The source is opt-in because the certs alone are the program, and the source may hold comments or code the author does not want to publish.
 - Any non-`CERTIFICATE` PEM block is an error.
 - Anchor-first order is deliberate: reading the file top to bottom reads the tree top to bottom. (Conventional PEM bundles are leaf-first.)
 
@@ -323,16 +323,16 @@ | `government run prog.gov` | Ratify, decode, evaluate, print results |
 | `government verify prog.gov` | Ratify and decode only; print the certificate of ratification; exit 0 if the program is lawful |
 | `government tree prog.gov` | Print the policy tree, with `GOV` abbreviated, payloads decoded and notes shown |
 | `government decompile prog.gov` | Print equivalent Lisp source, notes restored as comments |
-| `government compile prog.lisp -o prog.gov` | Run the transpiler (`-key`, `-author`, `-seed`, `-effective`, `-expires`, `-name`) |
+| `government compile prog.gov.lisp -o prog.gov` | Run the transpiler (`-key`, `-author`, `-seed`, `-effective`, `-expires`, `-name`, `-source`) |
 | `government repeal prog.gov -depth i -o repeal.crl` | Write a CRL repealing depth i (`-key`, `-reason`, `-at`, `-next-update`) |
 
 Shared flags: `-at <RFC 3339 time>`, `-anchor <cert or public key PEM>`, `-crl <file>` (repeatable), `-max-nodes <n>`.
 
-A second command, `govlisp`, runs Lisp source directly, with no certificates: `govlisp` alone is a REPL (multi-line forms, errors reported without ending the session), and `govlisp prog.lisp` runs a file, printing each non-`define` value and reporting the first error at its source line and column.
+GOVERNMENT's Lisp source files use the extension `.gov.lisp`. A second command, `govlisp`, runs Lisp source directly, with no certificates: `govlisp` alone is a REPL (multi-line forms, errors reported without ending the session), and `govlisp prog.gov.lisp` runs a file, printing each non-`define` value and reporting the first error at its source line and column.
 
 ## Transpiler and test suite
 
-Every language test is a plain `.lisp` file with expected results in comments; the runner transpiles it to `.gov` bytes and runs the full interpreter pipeline on them.
+Every language test is a plain `.gov.lisp` file with expected results in comments; the runner transpiles it to `.gov` bytes and runs the full interpreter pipeline on them.
 
 ### `lisp2gov` pipeline
 
@@ -342,7 +342,7 @@ 3. **Number** nodes in pre-order, starting at 1.
 4. **Layer**: compute n = max depth and each node's depth. No padding is written: `anyPolicy` makes the validator copy shallow leaves down.
 5. **Assign**: cert 1 lists the top-level nodes; certs 2..n list `anyPolicy`, plus any node that carries notes; each parent→child edge becomes a mapping in the parent's cert.
 6. **Sign**: take the author key (or the default seed), derive one Ed25519 key per depth, build the anchor and certs 1..n, and hand-encode certificatePolicies and policyMappings.
-7. **Emit** PEM, with the original source as a header comment above the first block.
+7. **Emit** PEM, with the original source above the first block if `-source` is given.
 
 The same source and flags always give the same bytes.
 
@@ -351,7 +351,7 @@
 After a top-level form, `;=> value` asserts its printed value, and `;=! text` asserts an error whose message contains `text`. In test mode, an error ends only that form, so one file can hold many error cases.
 
 ```lisp
-; testdata/scoping.lisp  (lexical, not dynamic)
+; testdata/scoping.gov.lisp  (lexical, not dynamic)
 (define x 1)
 (define f (lambda () x))
 (define g (lambda (x) (f)))
@@ -360,14 +360,14 @@ (define x 2)          ;=! immutable
 ((lambda (x) (define y (+ x 1)) (define z (+ y 1)) z) 1)   ;=> 3
 ((lambda () (define a (lambda () (b))) (define b (lambda () 1)) (a)))   ;=! unbound
 
-; testdata/truthiness.lisp
+; testdata/truthiness.gov.lisp
 (and F (car '()))     ;=> F
 (or F 7)              ;=> 7
 (if 0 'true 'false)   ;=> true
 (if F 1)              ;=> ()
 (not 0)               ;=> F
 
-; testdata/strings.lisp
+; testdata/strings.gov.lisp
 (strlen "héllo")        ;=> 5
 (strcat "gov" "ern" "ment")   ;=> "government"
 (str? "")             ;=> T
@@ -378,8 +378,8 @@ ### Test categories
 
 | Category | Form | Checks |
 | --- | --- | --- |
-| Language | `testdata/*.lisp` | All semantics: arithmetic, comparisons, truthiness, `if`, `quote`, lists, `define`, closures, scoping, recursion, higher-order functions, strings and Unicode |
-| Shape stress | `testdata/*.lisp` | 200-deep nesting (201 certs), 1,000-argument calls, wide `quote`d lists, shared subexpressions |
+| Language | `testdata/*.gov.lisp` | All semantics: arithmetic, comparisons, truthiness, `if`, `quote`, lists, `define`, closures, scoping, recursion, higher-order functions, strings and Unicode |
+| Shape stress | `testdata/*.gov.lisp` | 200-deep nesting (201 certs), 1,000-argument calls, wide `quote`d lists, shared subexpressions |
 | Round trip | Go test over every `testdata` file | `gov2lisp(lisp2gov(src))` equals the normalized source, comments included |
 | Ratification | Go table test that mutates a valid chain | Flipped signature byte, reordered certs, dropped mapping, orphaned policy, mapping in cert n, `anyPolicy` missing from a cert 2..n or asserted in cert 1, a list node with no elements, unknown critical extension; each expects a specific error |
 | Civic | Go table test | Runs before, inside and after an `-effective`/`-expires` window; repeal of each depth; scheduled repeal; stale CRL; CRL signed by the wrong key; `-anchor` pin across a re-ratified version; notes over 200 characters; default-key warning |
diff --git a/PLAN.md b/PLAN.md
index 6c2af0e54b34e30a38351d15ef9310aa4c50ff02..a193832a6cf7656845d8a1efffe18f845ccd58ad 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -15,7 +15,7 @@
 **Review conventions**
 
 - Every step ends with `go test ./...` green. No step depends on a later one.
-- Tests come with the code: Go table tests for internals, `testdata/*.lisp` files for language behavior.
+- Tests come with the code: Go table tests for internals, `testdata/*.gov.lisp` files for language behavior.
 - Each commit message names its step number, e.g. `step 12: tail calls via trampoline`.
 - Standard library only (Go 1.24+). The one-off prototype from the design phase is not reused.
 
@@ -23,7 +23,7 @@ ### Phases at a glance
 
 | Phase | Steps | Milestone at the end |
 | --- | --- | --- |
-| 1. Lisp core | 1–13 | `testdata/*.lisp` passes, run straight from source text |
+| 1. Lisp core | 1–13 | `testdata/*.gov.lisp` passes, run straight from source text |
 | 2. AST and OIDs | 14–17 | Any program converts to a layered, padded OID tree and back |
 | 3. Building certificates | 18–22 | `government compile` writes a `.gov` file that `openssl` can print |
 | 4. Ratification | 23–26 | A tampered, expired or misordered `.gov` file is rejected |
@@ -87,11 +87,11 @@     - Build: rewrite `Eval` as a loop that continues in place for `if` branches and closure bodies (a trampoline).
     - Learn: proper tail calls; why a naive recursive evaluator overflows the Go stack.
     - Done when: a tail-recursive countdown from 1,000,000 completes.
 13. **Errors and the source-mode test runner**
-    - Build: typed errors with codes (`E-UNBOUND`, `E-ARITY`, …) and an optional source location; a test runner that reads `testdata/*.lisp`, parses `;=>` and `;=!` annotations, and runs each top-level form through reader + evaluator.
+    - Build: typed errors with codes (`E-UNBOUND`, `E-ARITY`, …) and an optional source location; a test runner that reads `testdata/*.gov.lisp`, parses `;=>` and `;=!` annotations, and runs each top-level form through reader + evaluator.
     - Learn: designing errors as data; golden-style tests that read like documentation.
     - Done when: the design doc's example test files all pass. **Milestone: the language works.**
 
-**Extra: the `govlisp` REPL** (`cmd/govlisp`). Added between Phases 1 and 2. `govlisp` with no arguments is an interactive REPL; `govlisp prog.lisp` runs a file. A form may span lines: the reader marks syntax errors caused only by input ending early as incomplete, and the REPL reads another line instead of reporting them. Errors name the failing subexpression and keep the session going.
+**Extra: the `govlisp` REPL** (`cmd/govlisp`). Added between Phases 1 and 2. `govlisp` with no arguments is an interactive REPL; `govlisp prog.gov.lisp` runs a file. A form may span lines: the reader marks syntax errors caused only by input ending early as incomplete, and the REPL reads another line instead of reporting them. Errors name the failing subexpression and keep the session going.
 
 ## Phase 2: The AST and OID encoding (steps 14–17)
 
@@ -135,9 +135,9 @@     - Build: hand-encode `certificatePolicies` (OID `2.5.29.32`) as a SEQUENCE of PolicyInformation, OIDs only for now, leaving room for qualifiers in Phase 7. Cert 1 lists the top-level nodes; certs 2..n list `anyPolicy` (`2.5.29.32.0`).
     - Learn: policy OIDs as assertions a CA makes about a certificate, which is the hook GOVERNMENT abuses. Read RFC 5280 §4.2.1.4.
     - Done when: `ParseCertificate` returns the OIDs in `Policies`, including one with the 128-bit `GOV` arc.
 22. **The transpiler** (`lisp2gov`, `cmd/government`)
-    - Build: `Compile(src) ([]byte, error)`: read, build the tree, layer, then one cert per depth (cert 1 with the top-level nodes, the rest with `anyPolicy`), each with the mappings for its depth's outgoing edges; per-depth keys from the seed; PEM with the source as a header comment. Wire up `government compile`.
+    - Build: `Compile(src) ([]byte, error)`: read, build the tree, layer, then one cert per depth (cert 1 with the top-level nodes, the rest with `anyPolicy`), each with the mappings for its depth's outgoing edges; per-depth keys from the seed; PEM, with the source above the first block if `-source` is given. Wire up `government compile`.
     - Learn: how a certification path is a chain of issuer→subject links; how a whole program becomes n+1 signed objects.
-    - Done when: `government compile examples/sq.lisp -o sq.gov` writes a file that `openssl x509` can print block by block, and compiling twice gives identical bytes. **Milestone: GOVERNMENT programs exist.**
+    - Done when: `government compile examples/sq.gov.lisp -o sq.gov` writes a file that `openssl x509` can print block by block, and compiling twice gives identical bytes. **Milestone: GOVERNMENT programs exist.**
 
 ## Phase 4: Ratification (steps 23–26)
 
@@ -179,7 +179,7 @@     - Done when: deleting one mapping from a valid file gives an error (a gap in the node ids, or a list node left with no elements), not a shorter program, except for the subtree with the highest ids, which the test documents.
 30. **The full pipeline** (`cmd/government`)
     - Build: `government run`: load → ratify → policy graph → `Unlayer` → `FromTree` → evaluate; errors carry the node OID and depth; exit codes 1 and 2. Switch the test runner to compile every `testdata` file and run the resulting bytes.
     - Learn: how the stages compose into a compiler-like pipeline with a trust boundary in the middle.
-    - Done when: every `testdata/*.lisp` file passes through the full pipeline with no test changes. **Milestone: GOVERNMENT runs.**
+    - Done when: every `testdata/*.gov.lisp` file passes through the full pipeline with no test changes. **Milestone: GOVERNMENT runs.**
 
 ## Phase 6: Tooling (steps 31–32)
 
diff --git a/ast/tree_test.go b/ast/tree_test.go
index b4d30a2fb62d3a2ed4d2a33faa333611add77d52..91812066cf4f057122e296b89f96818f255cac1f 100644
--- a/ast/tree_test.go
+++ b/ast/tree_test.go
@@ -103,7 +103,7 @@ 	}
 }
 
 func TestRoundTripTestdata(t *testing.T) {
-	files, err := filepath.Glob("../testdata/*.lisp")
+	files, err := filepath.Glob("../testdata/*.gov.lisp")
 	if err != nil || len(files) == 0 {
 		t.Fatalf("no testdata: %v", err)
 	}
diff --git a/ast/unlayer_test.go b/ast/unlayer_test.go
index 282069502f252b92b545e4d82d1caf12ed850b40..099e9045bb5754bb04421330691f0c6fe8b410df 100644
--- a/ast/unlayer_test.go
+++ b/ast/unlayer_test.go
@@ -67,7 +67,7 @@ 	}
 }
 
 func TestUnlayerRoundTripTestdata(t *testing.T) {
-	files, err := filepath.Glob("../testdata/*.lisp")
+	files, err := filepath.Glob("../testdata/*.gov.lisp")
 	if err != nil || len(files) == 0 {
 		t.Fatalf("no testdata: %v", err)
 	}
diff --git a/cmd/government/compile.go b/cmd/government/compile.go
new file mode 100644
index 0000000000000000000000000000000000000000..185d2cf3a97e29c742e67a0c90665e65f94ed0b8
--- /dev/null
+++ b/cmd/government/compile.go
@@ -0,0 +1,87 @@
+package main
+
+import (
+	"errors"
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"strings"
+
+	"government/lisp2gov"
+	"government/sexpr"
+)
+
+func compile(args []string, stdout, stderr io.Writer) int {
+	fs := flag.NewFlagSet("compile", flag.ContinueOnError)
+	fs.SetOutput(stderr)
+	out := fs.String("o", "", "write the program to `file` instead of standard output")
+	name := fs.String("name", "", "program name for the certs' O= field (default: the source file's name without .gov.lisp)")
+	withSource := fs.Bool("source", false, "copy the Lisp source into the file's header")
+	fs.Usage = func() {
+		fmt.Fprintln(stderr, "usage: government compile prog.gov.lisp [-o prog.gov] [-name name] [-source]")
+		fs.PrintDefaults()
+	}
+	positional, err := parseInterspersed(fs, args)
+	if err != nil {
+		return exitInvalid
+	}
+	if len(positional) != 1 {
+		fs.Usage()
+		return exitInvalid
+	}
+	path := positional[0]
+
+	src, err := os.ReadFile(path)
+	if err != nil {
+		fmt.Fprintln(stderr, err)
+		return exitInvalid
+	}
+	if *name == "" {
+		base := filepath.Base(path)
+		*name = strings.TrimSuffix(base, ".gov.lisp")
+		if *name == base {
+			*name = strings.TrimSuffix(base, filepath.Ext(base))
+		}
+	}
+	program, err := lisp2gov.Compile(string(src), lisp2gov.Options{Name: *name, IncludeSource: *withSource})
+	if err != nil {
+		var se *sexpr.SyntaxError
+		if errors.As(err, &se) {
+			fmt.Fprintf(stderr, "%s:%v\n", path, se)
+		} else {
+			fmt.Fprintf(stderr, "%s: %v\n", path, err)
+		}
+		return exitInvalid
+	}
+
+	if *out == "" {
+		_, err = stdout.Write(program)
+	} else {
+		err = os.WriteFile(*out, program, 0o644)
+	}
+	if err != nil {
+		fmt.Fprintln(stderr, err)
+		return exitInvalid
+	}
+	return exitOK
+}
+
+// parseInterspersed lets flags come before or after the file name, as in
+// "government compile prog.gov.lisp -o prog.gov". The flag package alone stops
+// at the first argument that is not a flag.
+func parseInterspersed(fs *flag.FlagSet, args []string) ([]string, error) {
+	var positional []string
+	for {
+		if err := fs.Parse(args); err != nil {
+			return nil, err
+		}
+		args = fs.Args()
+		if len(args) == 0 {
+			return positional, nil
+		}
+		positional = append(positional, args[0])
+		args = args[1:]
+	}
+}
diff --git a/cmd/government/main.go b/cmd/government/main.go
index a6b99a21b0548a6fb159734cc27532d965408d50..a3a1efbf4ed01be38d5cd71778835645d7485037 100644
--- a/cmd/government/main.go
+++ b/cmd/government/main.go
@@ -1,26 +1,49 @@
 // Command government runs GOVERNMENT programs.
 //
-// Only the usage message exists so far. The subcommands (run, verify, tree,
-// decompile, compile, repeal) arrive in later steps of PLAN.md.
+// Only compile exists so far. The other subcommands arrive in later steps
+// of PLAN.md.
 package main
 
 import (
 	"fmt"
+	"io"
 	"os"
 )
 
+const (
+	exitOK      = 0
+	exitInvalid = 2
+)
+
 const usage = `usage: government <command> [arguments]
 
-commands (not yet implemented):
+commands:
+  compile    transpile Lisp source to .gov
+
+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
-  compile    transpile Lisp source to .gov
   repeal     write a CRL repealing one depth of a program
 `
 
 func main() {
-	fmt.Fprint(os.Stderr, usage)
-	os.Exit(2)
+	os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
+}
+
+func run(args []string, stdout, stderr io.Writer) int {
+	if len(args) == 0 {
+		fmt.Fprint(stderr, usage)
+		return exitInvalid
+	}
+	switch args[0] {
+	case "compile":
+		return compile(args[1:], stdout, stderr)
+	case "help", "-h", "-help", "--help":
+		fmt.Fprint(stdout, usage)
+		return exitOK
+	}
+	fmt.Fprintf(stderr, "government: unknown command %q\n\n%s", args[0], usage)
+	return exitInvalid
 }
diff --git a/cmd/government/main_test.go b/cmd/government/main_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0095087d5c7215bde630ab7e821d231437dda9bd
--- /dev/null
+++ b/cmd/government/main_test.go
@@ -0,0 +1,75 @@
+package main
+
+import (
+	"bytes"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+func runCmd(args ...string) (code int, stdout, stderr string) {
+	var out, errb bytes.Buffer
+	code = run(args, &out, &errb)
+	return code, out.String(), errb.String()
+}
+
+func TestCompileExample(t *testing.T) {
+	dir := t.TempDir()
+	a, b := filepath.Join(dir, "a.gov"), filepath.Join(dir, "b.gov")
+	if code, _, stderr := runCmd("compile", "../../examples/sq.gov.lisp", "-o", a); code != exitOK {
+		t.Fatalf("exit %d: %s", code, stderr)
+	}
+	if code, _, stderr := runCmd("compile", "-o", b, "../../examples/sq.gov.lisp"); code != exitOK {
+		t.Fatalf("exit %d: %s", code, stderr)
+	}
+	x, _ := os.ReadFile(a)
+	y, _ := os.ReadFile(b)
+	if len(x) == 0 || !bytes.Equal(x, y) {
+		t.Error("two compiles of sq.gov.lisp differ")
+	}
+	if !strings.HasPrefix(string(x), "-----BEGIN CERTIFICATE-----") {
+		t.Errorf("text before the first block: %.60q", x)
+	}
+}
+
+func TestCompileSourceFlag(t *testing.T) {
+	code, stdout, stderr := runCmd("compile", "-source", "../../examples/sq.gov.lisp")
+	if code != exitOK {
+		t.Fatalf("exit %d: %s", code, stderr)
+	}
+	if !strings.HasPrefix(stdout, "    ; sq.gov.lisp: the square of a number.\n    (define sq (lambda (x) (* x x)))\n") {
+		t.Errorf("source missing: %.120q", stdout)
+	}
+}
+
+func TestCompileToStdout(t *testing.T) {
+	code, stdout, _ := runCmd("compile", "../../examples/sq.gov.lisp")
+	if code != exitOK || !strings.Contains(stdout, "-----BEGIN CERTIFICATE-----") {
+		t.Errorf("exit %d, output %.60q", code, stdout)
+	}
+}
+
+func TestCompileErrors(t *testing.T) {
+	dir := t.TempDir()
+	bad := filepath.Join(dir, "bad.gov.lisp")
+	os.WriteFile(bad, []byte("(+ 1\n  (* 2"), 0o644)
+
+	tests := []struct {
+		args []string
+		want string
+	}{
+		{[]string{"compile", bad}, "bad.gov.lisp:"},
+		{[]string{"compile", filepath.Join(dir, "missing.gov.lisp")}, "no such file"},
+		{[]string{"compile"}, "usage"},
+		{[]string{"compile", "a.gov.lisp", "b.gov.lisp"}, "usage"},
+		{[]string{"frobnicate"}, "unknown command"},
+		{nil, "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)
+		}
+	}
+}
diff --git a/cmd/govlisp/main.go b/cmd/govlisp/main.go
index e4a18621d89b1398fb969f0b1e17c4d46ff4b5ea..395007c10921b253eda00c2ff0c1c3db7b294965 100644
--- a/cmd/govlisp/main.go
+++ b/cmd/govlisp/main.go
@@ -2,7 +2,7 @@ // Command govlisp runs GOVERNMENT programs straight from Lisp source, with
 // no certificates involved.
 //
 //	govlisp              interactive REPL
-//	govlisp prog.lisp    run a file, printing the value of each non-define form
+//	govlisp prog.gov.lisp    run a file, printing the value of each non-define form
 //
 // The REPL has no line editing; wrap it with rlwrap for history and arrow
 // keys.
@@ -31,7 +31,7 @@ 		os.Exit(repl(os.Stdin, os.Stdout, isTerminal(os.Stdin)))
 	case 2:
 		os.Exit(runFile(os.Args[1], os.Stdout, os.Stderr))
 	default:
-		fmt.Fprintln(os.Stderr, "usage: govlisp [file.lisp]")
+		fmt.Fprintln(os.Stderr, "usage: govlisp [file.gov.lisp]")
 		os.Exit(exitSyntax)
 	}
 }
diff --git a/cmd/govlisp/main_test.go b/cmd/govlisp/main_test.go
index 3a711ee50dbadacf350a412b97bd10f707305184..08b0e287031d1d43ebd94c017eacf9eb3fbf6d3c 100644
--- a/cmd/govlisp/main_test.go
+++ b/cmd/govlisp/main_test.go
@@ -83,13 +83,13 @@ 		name, src, stdout, stderr string
 		code                      int
 	}{
 		{"ok", "(define x 2)\n(* x 21)\n'done\n", "42\ndone\n", "", exitOK},
-		{"runtime error", "(define f (lambda (l) (car l)))\n1\n(f\n  ())\n2\n", "1\n", "prog.lisp:1:23: E-TYPE: car needs a pair, got ()\n", exitRuntime},
-		{"syntax error", "1\n(+ 2\n", "", "prog.lisp:2:1: unterminated list\n", exitSyntax},
+		{"runtime error", "(define f (lambda (l) (car l)))\n1\n(f\n  ())\n2\n", "1\n", "prog.gov.lisp:1:23: E-TYPE: car needs a pair, got ()\n", exitRuntime},
+		{"syntax error", "1\n(+ 2\n", "", "prog.gov.lisp:2:1: unterminated list\n", exitSyntax},
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			dir := t.TempDir()
-			path := filepath.Join(dir, "prog.lisp")
+			path := filepath.Join(dir, "prog.gov.lisp")
 			if err := os.WriteFile(path, []byte(tt.src), 0o644); err != nil {
 				t.Fatal(err)
 			}
diff --git a/examples/sq.gov.lisp b/examples/sq.gov.lisp
new file mode 100644
index 0000000000000000000000000000000000000000..3b277b5e6fe614ad4ebc799f7cc5a473f74220fc
--- /dev/null
+++ b/examples/sq.gov.lisp
@@ -0,0 +1,3 @@
+; sq.gov.lisp: the square of a number.
+(define sq (lambda (x) (* x x)))
+(sq 12)
diff --git a/internal/lisptest/lisptest_test.go b/internal/lisptest/lisptest_test.go
index b795a8794bb584d5ed2f7a7355b76a0f67e64ef8..fe25e8b6ee4efe4897238d452a7373cb19d0c107 100644
--- a/internal/lisptest/lisptest_test.go
+++ b/internal/lisptest/lisptest_test.go
@@ -16,7 +16,7 @@ 	r.errors = append(r.errors, fmt.Sprintf(format, args...))
 }
 
 func TestAnnotationsAttachToPrecedingForm(t *testing.T) {
-	f, err := Parse("t.lisp", `
+	f, err := Parse("t.gov.lisp", `
 (define x 1)
 x            ;=> 1
 (car
@@ -46,13 +46,13 @@ }
 
 func TestParseErrors(t *testing.T) {
 	tests := []struct{ src, want string }{
-		{";=> 1\n(+ 1 0)", "t.lisp:1:1: annotation before any form"},
-		{"1 ;=> 1\n;=> 1", "t.lisp:2:1: second annotation for the form at 1:1"},
-		{"1 ;=>", "t.lisp:1:3: empty annotation"},
-		{"(1", "t.lisp:1:1: unterminated list"},
+		{";=> 1\n(+ 1 0)", "t.gov.lisp:1:1: annotation before any form"},
+		{"1 ;=> 1\n;=> 1", "t.gov.lisp:2:1: second annotation for the form at 1:1"},
+		{"1 ;=>", "t.gov.lisp:1:3: empty annotation"},
+		{"(1", "t.gov.lisp:1:1: unterminated list"},
 	}
 	for _, tt := range tests {
-		if _, err := Parse("t.lisp", tt.src); err == nil || err.Error() != tt.want {
+		if _, err := Parse("t.gov.lisp", tt.src); err == nil || err.Error() != tt.want {
 			t.Errorf("Parse(%q) error = %v, want %q", tt.src, err, tt.want)
 		}
 	}
@@ -61,7 +61,7 @@
 // Every kind of mismatch is reported, with the failing subexpression's
 // position, and evaluation continues past failures.
 func TestRunReportsFailures(t *testing.T) {
-	f, err := Parse("t.lisp", `(+ 1 1)      ;=> 3
+	f, err := Parse("t.gov.lisp", `(+ 1 1)      ;=> 3
 (+ 1 1)      ;=! overflow
 (car '())    ;=> 1
 (/ 1 0)      ;=! not a function
@@ -75,11 +75,11 @@ 	}
 	r := &recorder{}
 	Run(r, f, eval.NewTopLevel())
 	want := []string{
-		"t.lisp:1:1: (+ 1 1)\n\tgot  2\n\twant 3",
-		"t.lisp:2:1: (+ 1 1)\n\tgot value 2, want an error containing \"overflow\"",
-		"t.lisp:3:1: (car (quote ()))\n\tunexpected error E-TYPE: car needs a pair, got () (at 3:1: (car (quote ())))",
-		"t.lisp:4:1: (/ 1 0)\n\tgot error E-ARITH: division by zero (at 4:1: (/ 1 0)), want one containing \"not a function\"",
-		"t.lisp:5:1: (+ 1 (car 5))\n\tunexpected error E-TYPE: car needs a pair, got 5 (at 6:4: (car 5))",
+		"t.gov.lisp:1:1: (+ 1 1)\n\tgot  2\n\twant 3",
+		"t.gov.lisp:2:1: (+ 1 1)\n\tgot value 2, want an error containing \"overflow\"",
+		"t.gov.lisp:3:1: (car (quote ()))\n\tunexpected error E-TYPE: car needs a pair, got () (at 3:1: (car (quote ())))",
+		"t.gov.lisp:4:1: (/ 1 0)\n\tgot error E-ARITH: division by zero (at 4:1: (/ 1 0)), want one containing \"not a function\"",
+		"t.gov.lisp:5:1: (+ 1 (car 5))\n\tunexpected error E-TYPE: car needs a pair, got 5 (at 6:4: (car 5))",
 	}
 	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"))
diff --git a/lisp2gov/cert.go b/lisp2gov/cert.go
index 747452fcf569e9c16bb4bc1b0af422d993f9cb5c..def76b0c3d305f2cc81832fceb48d9d444d96eca 100644
--- a/lisp2gov/cert.go
+++ b/lisp2gov/cert.go
@@ -11,9 +11,6 @@ 	"encoding/pem"
 	"fmt"
 	"math/big"
 	"time"
-
-	"government/ast"
-	"government/sexpr"
 )
 
 // The default window in force. 9999-12-31 is RFC 5280's value for a
@@ -116,8 +113,6 @@ 	sum := sha256.Sum256(pub)
 	return sum[:20]
 }
 
-// encodePEM writes the certs as PEM blocks after a header. Text outside
-// PEM blocks is ignored by readers, so the header can carry the source.
 func encodePEM(header string, certs []*x509.Certificate) []byte {
 	var b bytes.Buffer
 	b.WriteString(header)
@@ -126,44 +121,3 @@ 		pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: c.Raw})
 	}
 	return b.Bytes()
 }
-
-// firstProgram is the step-18 experiment: a program whose forms are all
-// atoms, so its tree has depth 1. That needs only the anchor and cert 1,
-// with each form as a policy, and no mappings, so Go can write every byte
-// itself. Compile replaces it once the policy extensions are hand-encoded.
-func firstProgram(seed [32]byte, name, src string) ([]byte, error) {
-	forms, err := sexpr.ReadAll(src)
-	if err != nil {
-		return nil, err
-	}
-	tree, err := ast.ToTree(forms)
-	if err != nil {
-		return nil, err
-	}
-	layers, err := ast.Layer(tree)
-	if err != nil {
-		return nil, err
-	}
-	if layers.Depth() != 1 {
-		return nil, fmt.Errorf("firstProgram handles depth 1 only; %q has depth %d", src, layers.Depth())
-	}
-	var policies []x509.OID
-	for _, n := range layers.Nodes[0] {
-		oid, err := n.OID()
-		if err != nil {
-			return nil, err
-		}
-		policies = append(policies, oid)
-	}
-
-	anchor, err := newAnchor(seed, name)
-	if err != nil {
-		return nil, err
-	}
-	cert1, err := newCert(seed, name, 1, true, policies, nil, anchor)
-	if err != nil {
-		return nil, err
-	}
-	header := "; " + name + ".gov\n" + src + "\n\n"
-	return encodePEM(header, []*x509.Certificate{anchor.cert, cert1.cert}), nil
-}
diff --git a/lisp2gov/cert_test.go b/lisp2gov/cert_test.go
index bbe0559b88cf38d6e858c99f069de51f73fc50e3..6055f0bfd3d07fa1dd8e6fd379c00fc0464bb53f 100644
--- a/lisp2gov/cert_test.go
+++ b/lisp2gov/cert_test.go
@@ -17,7 +17,7 @@
 // answer compiles the program 42, the smallest kind of GOVERNMENT program:
 // one atom, so one cert below the anchor.
 func answer() ([]byte, error) {
-	return firstProgram(DefaultSeed, "answer", "42")
+	return Compile("42", Options{Name: "answer"})
 }
 
 func parsePEM(t *testing.T, b []byte) []*x509.Certificate {
@@ -162,9 +162,3 @@ 	if ns != ast.NSInt || id != 1 || text != "42" {
 		t.Errorf("cert 1's policy decodes to %s #%d %q, want integer #1 \"42\"", ns, id, text)
 	}
 }
-
-func TestFirstProgramRejectsDeeperPrograms(t *testing.T) {
-	if _, err := firstProgram(DefaultSeed, "deep", "(+ 1 2)"); err == nil {
-		t.Error("a depth-2 program compiled without policy mappings")
-	}
-}
diff --git a/lisp2gov/compile.go b/lisp2gov/compile.go
new file mode 100644
index 0000000000000000000000000000000000000000..a867d52f3550ec0f51a69bfbbe3dfb73eeb5b96e
--- /dev/null
+++ b/lisp2gov/compile.go
@@ -0,0 +1,120 @@
+package lisp2gov
+
+import (
+	"crypto/x509"
+	"fmt"
+	"strings"
+
+	"government/ast"
+	"government/sexpr"
+)
+
+type Options struct {
+	// Name is the program's name, written into every cert's subject as
+	// O=<name>. It defaults to "program".
+	Name string
+	// Seed derives every signing key. nil means DefaultSeed, which is
+	// public, so anyone can rebuild or forge the program.
+	Seed *[32]byte
+	// IncludeSource copies the Lisp source into the file's header. It is
+	// off by default: the certs alone are the program, and the source
+	// may hold comments or code the author does not want to publish.
+	IncludeSource bool
+}
+
+// Compile turns Lisp source into the bytes of a .gov file. The same source
+// and options always give the same bytes. A syntax error is returned as the
+// reader's *sexpr.SyntaxError, so callers can report its position.
+func Compile(src string, opts Options) ([]byte, error) {
+	certs, err := compileCerts(src, opts)
+	if err != nil {
+		return nil, err
+	}
+	return encodePEM(header(src, opts.IncludeSource), certs), nil
+}
+
+func (o Options) name() string {
+	if o.Name == "" {
+		return "program"
+	}
+	return o.Name
+}
+
+func (o Options) seed() [32]byte {
+	if o.Seed == nil {
+		return DefaultSeed
+	}
+	return *o.Seed
+}
+
+// compileCerts builds the anchor and one cert per depth. Cert 1 lists the
+// top-level forms; certs 2..n list only anyPolicy, so every node below
+// depth 1 exists in the policy tree only because a mapping in the cert
+// above names it.
+func compileCerts(src string, opts Options) ([]*x509.Certificate, error) {
+	forms, err := sexpr.ReadAll(src)
+	if err != nil {
+		return nil, err
+	}
+	tree, err := ast.ToTree(forms)
+	if err != nil {
+		return nil, err
+	}
+	layers, err := ast.Layer(tree)
+	if err != nil {
+		return nil, err
+	}
+
+	name, seed := opts.name(), opts.seed()
+	prev, err := newAnchor(seed, name)
+	if err != nil {
+		return nil, err
+	}
+	certs := []*x509.Certificate{prev.cert}
+	n := layers.Depth()
+	for i := 1; i <= n; i++ {
+		policies := []x509.OID{anyPolicy}
+		if i == 1 {
+			policies = nil
+			for _, node := range layers.Nodes[0] {
+				oid, err := node.OID()
+				if err != nil {
+					return nil, err
+				}
+				policies = append(policies, oid)
+			}
+		}
+		mappings, err := mappingsFor(layers.Edges[i-1])
+		if err != nil {
+			return nil, err
+		}
+		next, err := newCert(seed, name, i, i == n, policies, mappings, prev)
+		if err != nil {
+			return nil, fmt.Errorf("cert %d: %w", i, err)
+		}
+		certs = append(certs, next.cert)
+		prev = next
+	}
+	return certs, nil
+}
+
+// header is the text above the first PEM block: nothing, or with
+// IncludeSource the Lisp source. Readers ignore text outside PEM blocks, so
+// the source can travel with the program. Every source line is indented,
+// which also means no line of it can start a PEM block, even if the source
+// happens to contain "-----BEGIN".
+func header(src string, includeSource bool) string {
+	if !includeSource {
+		return ""
+	}
+	var b strings.Builder
+	for _, line := range strings.Split(strings.TrimRight(src, "\n"), "\n") {
+		if line == "" {
+			b.WriteString("\n")
+			continue
+		}
+		b.WriteString("    " + line + "\n")
+	}
+	b.WriteString("\n")
+	return b.String()
+}
diff --git a/lisp2gov/compile_test.go b/lisp2gov/compile_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5c9710d988c567243c72fc6310bbaa766fc00884
--- /dev/null
+++ b/lisp2gov/compile_test.go
@@ -0,0 +1,127 @@
+package lisp2gov
+
+import (
+	"bytes"
+	"errors"
+	"os"
+	"path/filepath"
+	"testing"
+
+	"government/sexpr"
+)
+
+func TestCompileTestdata(t *testing.T) {
+	files, err := filepath.Glob("../testdata/*.gov.lisp")
+	if err != nil || len(files) == 0 {
+		t.Fatalf("no testdata: %v", err)
+	}
+	for _, file := range files {
+		src, err := os.ReadFile(file)
+		if err != nil {
+			t.Fatal(err)
+		}
+		a, err := Compile(string(src), Options{Name: filepath.Base(file)})
+		if err != nil {
+			t.Errorf("%s: %v", file, err)
+			continue
+		}
+		b, _ := Compile(string(src), Options{Name: filepath.Base(file)})
+		if !bytes.Equal(a, b) {
+			t.Errorf("%s: two compiles differ", file)
+		}
+		certs := parsePEM(t, a)
+		for i := 1; i < len(certs); i++ {
+			if err := certs[i].CheckSignatureFrom(certs[i-1]); err != nil {
+				t.Errorf("%s: cert %d: %v", file, i, err)
+			}
+		}
+	}
+}
+
+func TestCompileDepth(t *testing.T) {
+	for _, tt := range []struct {
+		src   string
+		certs int
+	}{
+		{"42", 2},
+		{"(+ 1 2)", 3},
+		{"(+ 1 (* 2 3))", 4},
+		{"1 (a (b (c)))", 5},
+	} {
+		out, err := Compile(tt.src, Options{})
+		if err != nil {
+			t.Fatal(err)
+		}
+		if got := len(parsePEM(t, out)); got != tt.certs {
+			t.Errorf("%s: %d certs, want %d", tt.src, got, tt.certs)
+		}
+	}
+}
+
+func TestCompileOptions(t *testing.T) {
+	a, _ := Compile("(+ 1 2)", Options{Name: "a"})
+	b, _ := Compile("(+ 1 2)", Options{Name: "b"})
+	if bytes.Equal(a, b) {
+		t.Error("name has no effect")
+	}
+	if got := parsePEM(t, b)[2].Subject.Organization[0]; got != "b" {
+		t.Errorf("O = %q, want b", got)
+	}
+
+	seed := [32]byte{7}
+	c, _ := Compile("(+ 1 2)", Options{Name: "a", Seed: &seed})
+	if bytes.Equal(a, c) {
+		t.Error("seed has no effect")
+	}
+	if err := parsePEM(t, c)[1].CheckSignatureFrom(parsePEM(t, a)[0]); err == nil {
+		t.Error("a cert from one seed verifies under another seed's anchor")
+	}
+}
+
+func TestCompileHeaderCannotInjectBlocks(t *testing.T) {
+	src := "; -----BEGIN CERTIFICATE-----\n; AAAA\n; -----END CERTIFICATE-----\n\"\n-----BEGIN CERTIFICATE-----\n\"\n"
+	out, err := Compile(src, Options{IncludeSource: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	// The program is one string atom: anchor plus one cert, nothing more.
+	if got := len(parsePEM(t, out)); got != 2 {
+		t.Errorf("%d PEM blocks, want 2", got)
+	}
+}
+
+func TestCompileErrors(t *testing.T) {
+	_, err := Compile("(+ 1", Options{})
+	var se *sexpr.SyntaxError
+	if !errors.As(err, &se) {
+		t.Errorf("unfinished form: error %v is not a *sexpr.SyntaxError", err)
+	}
+	if _, err := Compile("; only a comment\n", Options{}); err == nil {
+		t.Error("a program with no forms compiled")
+	}
+}
+
+func TestCompileSourceIsOptIn(t *testing.T) {
+	src := "; secret plan\n(+ 1 2)\n"
+	without, err := Compile(src, Options{Name: "p"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if bytes.Contains(without, []byte("secret plan")) || bytes.Contains(without, []byte("(+ 1 2)")) {
+		t.Errorf("source in output by default:\n%.80s", without)
+	}
+	with, err := Compile(src, Options{Name: "p", IncludeSource: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !bytes.Contains(with, []byte("    ; secret plan\n    (+ 1 2)\n")) {
+		t.Errorf("source missing with IncludeSource:\n%.120s", with)
+	}
+	// The header is the only difference; the certs are the same.
+	a, b := parsePEM(t, without), parsePEM(t, with)
+	for i := range a {
+		if !bytes.Equal(a[i].Raw, b[i].Raw) {
+			t.Errorf("cert %d differs", i)
+		}
+	}
+}
diff --git a/lisp2gov/extensions_test.go b/lisp2gov/extensions_test.go
index 65b9dee083216c5c0efc23b00b425b1330ccba78..7b8f31f533ee25679d07a498b5e3069e8437a030 100644
--- a/lisp2gov/extensions_test.go
+++ b/lisp2gov/extensions_test.go
@@ -47,51 +47,23 @@ 		t.Error("empty policyMappings accepted; RFC 5280 requires at least one")
 	}
 }
 
-// buildChain makes the full chain for src by hand, ahead of Compile in
-// step 22: cert 1 lists the top-level nodes, the rest assert anyPolicy,
-// and every cert but the last carries its layer's mappings.
 func buildChain(t *testing.T, src string) ([]*x509.Certificate, ast.Layers) {
 	t.Helper()
-	forms, err := sexpr.ReadAll(src)
+	certs, err := compileCerts(src, Options{Name: "mappings"})
 	if err != nil {
 		t.Fatal(err)
 	}
-	tree, err := ast.ToTree(forms)
+	forms, err := sexpr.ReadAll(src)
 	if err != nil {
 		t.Fatal(err)
 	}
-	layers, err := ast.Layer(tree)
+	tree, err := ast.ToTree(forms)
 	if err != nil {
 		t.Fatal(err)
 	}
-	prev, err := newAnchor(DefaultSeed, "mappings")
+	layers, err := ast.Layer(tree)
 	if err != nil {
 		t.Fatal(err)
-	}
-	certs := []*x509.Certificate{prev.cert}
-	n := layers.Depth()
-	for i := 1; i <= n; i++ {
-		policies := []x509.OID{anyPolicy}
-		if i == 1 {
-			policies = nil
-			for _, node := range layers.Nodes[0] {
-				oid, err := node.OID()
-				if err != nil {
-					t.Fatal(err)
-				}
-				policies = append(policies, oid)
-			}
-		}
-		mappings, err := mappingsFor(layers.Edges[i-1])
-		if err != nil {
-			t.Fatal(err)
-		}
-		next, err := newCert(DefaultSeed, "mappings", i, i == n, policies, mappings, prev)
-		if err != nil {
-			t.Fatal(err)
-		}
-		certs = append(certs, next.cert)
-		prev = next
 	}
 	return certs, layers
 }
diff --git a/lisp2gov/testdata/answer.gov b/lisp2gov/testdata/answer.gov
index 64f893d1027ef6982fbbc935a2347c889d527776..84366b1d67213b5170c330ef1150c0f0daa7c636 100644
--- a/lisp2gov/testdata/answer.gov
+++ b/lisp2gov/testdata/answer.gov
@@ -1,6 +1,3 @@
-; answer.gov
-42
-
 -----BEGIN CERTIFICATE-----
 MIIBbjCCASCgAwIBAgIBATAFBgMrZXAwLTEPMA0GA1UEChMGYW5zd2VyMRowGAYD
 VQQDExFHT1ZFUk5NRU5UIEFuY2hvcjAgFw0wMDAxMDEwMDAwMDBaGA85OTk5MTIz
diff --git a/lisp_test.go b/lisp_test.go
index d256de0e017c5e48a086ec0a4a91d183a9cba81d..0f0703cf23f7c4a4a37763587a83ac5b5a0472a9 100644
--- a/lisp_test.go
+++ b/lisp_test.go
@@ -9,16 +9,16 @@ 	"government/eval"
 	"government/internal/lisptest"
 )
 
-// TestLispFiles runs every testdata/*.lisp file straight from source text.
+// 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.
 func TestLispFiles(t *testing.T) {
-	paths, err := filepath.Glob("testdata/*.lisp")
+	paths, err := filepath.Glob("testdata/*.gov.lisp")
 	if err != nil {
 		t.Fatal(err)
 	}
 	if len(paths) == 0 {
-		t.Fatal("no testdata/*.lisp files found")
+		t.Fatal("no testdata/*.gov.lisp files found")
 	}
 	for _, path := range paths {
 		t.Run(filepath.Base(path), func(t *testing.T) {