refactor: testing from the beginning. a journey in 150k lines of tests to none

This commit is contained in:
sam committed 2026-10-03 21:16:25 +10:00
1 parent ba37e37e53
commit ff424b70ac
651 files changed
-146443

No files matched your search

-158
View File
@@ -1,158 +0,0 @@
package main
import (
"path/filepath"
"strings"
"testing"
)
// TestClassify covers the three-state rule plus the staleness rule that runs
// in the opposite direction. The staleness cases are the important ones: an
// allowlist that permits something which is no longer true is how a gate
// quietly stops checking anything.
func TestClassify(t *testing.T) {
subjects := []Subject{
{Name: "Svc/Consumed", Evidence: "proto:x", Consumed: true, Consumer: "internal/infrastructure/staterpc/client.go:41"},
{Name: "Svc/Declared", Evidence: "proto:y", Consumed: false},
{Name: "Svc/Bare", Evidence: "proto:z", Consumed: false},
{Name: "Svc/FreshlyConsumed", Evidence: "proto:w", Consumed: true, Consumer: "internal/foo/bar.go:9"},
}
declarations := Declarations{Surfaces: map[string]map[string]Declaration{
"proto/state/v1": {
"Svc/Declared": {Reason: "no consumer yet; extraction is planned", Tracker: "archie-core-8cda.4"},
"Svc/FreshlyConsumed": {Reason: "was unconsumed at audit time", Tracker: "archie-core-8cda.6"},
"Svc/Gone": {Reason: "surface removed it", Tracker: "archie-core-8cda.7"},
},
}}
findings := classify("proto/state/v1", subjects, declarations)
got := map[string]Class{}
for _, finding := range findings {
got[finding.Subject] = finding.Class
}
want := map[string]Class{
"Svc/Consumed": Consumed,
"Svc/Declared": DeclaredUnconsumed,
"Svc/Bare": Undeclared,
"Svc/FreshlyConsumed": Stale,
"Svc/Gone": Stale,
}
for subject, class := range want {
if got[subject] != class {
t.Errorf("classify(%q) = %q, want %q", subject, got[subject], class)
}
}
if len(findings) != len(want) {
t.Errorf("classify produced %d findings, want %d", len(findings), len(want))
}
}
// TestClassifyDeclaredEntryKeepsProvenance asserts the reason and tracker
// survive classification, because the declaration file is the only place the
// debt is legible.
func TestClassifyDeclaredEntryKeepsProvenance(t *testing.T) {
subjects := []Subject{{Name: "Svc/Declared"}}
declarations := Declarations{Surfaces: map[string]map[string]Declaration{
"s": {"Svc/Declared": {Reason: "the consequence, stated", Tracker: "archie-core-abc.1"}},
}}
findings := classify("s", subjects, declarations)
if len(findings) != 1 {
t.Fatalf("got %d findings, want 1", len(findings))
}
if findings[0].Evidence != "the consequence, stated" {
t.Errorf("evidence = %q, want the reason", findings[0].Evidence)
}
if findings[0].Tracker != "archie-core-abc.1" {
t.Errorf("tracker = %q, want the bead id", findings[0].Tracker)
}
}
// TestUndeclaredCountCountsOnlyFindings asserts a healthy surface contributes
// zero, so a strict run over a fully-declared surface passes.
func TestUndeclaredCountCountsOnlyFindings(t *testing.T) {
findings := []Finding{
{Subject: "a", Class: Consumed},
{Subject: "b", Class: DeclaredUnconsumed},
{Subject: "c", Class: Undeclared},
{Subject: "d", Class: Stale},
}
if got := UndeclaredCount(findings); got != 2 {
t.Errorf("UndeclaredCount = %d, want 2 (undeclared + stale)", got)
}
}
// TestLoadDeclarationsMissingFileIsEmpty asserts an absent allowlist is the
// correct starting state: every unconsumed subject becomes undeclared, which
// is the honest first report rather than a silent pass. The path is never
// created, so no file content is involved.
func TestLoadDeclarationsMissingFileIsEmpty(t *testing.T) {
declarations, err := loadDeclarations(filepath.Join(t.TempDir(), "absent.json"))
if err != nil {
t.Fatalf("loadDeclarations(absent) error = %v, want nil", err)
}
if len(declarations.Surfaces) != 0 {
t.Errorf("surfaces = %v, want empty", declarations.Surfaces)
}
}
// TestParseDeclarations covers the decoding rules in memory, so no file is
// authored and no formatting of an external file can affect the outcome.
func TestParseDeclarations(t *testing.T) {
t.Run("an empty object is usable", func(t *testing.T) {
declarations, err := parseDeclarations(strings.NewReader("{}"))
if err != nil {
t.Fatalf("error = %v, want nil", err)
}
if declarations.Surfaces == nil {
t.Error("surfaces = nil, want a non-nil empty map so a lookup cannot panic")
}
})
t.Run("entries are decoded", func(t *testing.T) {
declarations, err := parseDeclarations(strings.NewReader(
`{"surfaces":{"s":{"Svc/Method":{"reason":"because","tracker":"abc.1"}}}}`,
))
if err != nil {
t.Fatalf("error = %v, want nil", err)
}
entry := declarations.Surfaces["s"]["Svc/Method"]
if entry.Reason != "because" || entry.Tracker != "abc.1" {
t.Errorf("entry = %+v, want the reason and tracker preserved", entry)
}
})
t.Run("malformed input is rejected", func(t *testing.T) {
// A broken allowlist must fail loudly rather than degrading to "no
// declarations", which would turn every declared entry into a finding
// nobody could clear.
if _, err := parseDeclarations(strings.NewReader("{not json")); err == nil {
t.Error("error = nil, want a parse failure")
}
})
}
// TestStripJSComments pins the behaviour the extractor depends on: a commented
// call must not read as a live consumer, and a literal that merely looks like a
// comment must survive intact.
func TestStripJSComments(t *testing.T) {
for _, tc := range []struct{ name, src, want string }{
{"line comment goes", "a // gone\nb", "a \nb"},
{"newline survives a line comment", "a // gone\nb", "a \nb"},
{"block comment goes", "a/* gone */b", "ab"},
{"unterminated block comment eats the tail", "a/* gone", "a"},
{"comment marker inside a string survives", `f("// not a comment")`, `f("// not a comment")`},
{"block marker inside a string survives", `f("/* kept */")`, `f("/* kept */")`},
{"template literal survives", "f(`/* kept */`)", "f(`/* kept */`)"},
{"escaped quote does not end the literal", `f("a\"// kept")`, `f("a\"// kept")`},
{"unterminated literal keeps its tail", `f("abc`, `f("abc`},
{"adjacent literals", `a("x")+b('y')`, `a("x")+b('y')`},
{"code either side of a block comment", "a/*x*/b/*y*/c", "abc"},
} {
t.Run(tc.name, func(t *testing.T) {
if got := stripJSComments(tc.src); got != tc.want {
t.Fatalf("stripJSComments(%q) = %q, want %q", tc.src, got, tc.want)
}
})
}
}
-300
View File
@@ -1,300 +0,0 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestNormalize(t *testing.T) {
tests := []struct {
name string
in string
want string
}{
{"bare package", "internal/config", "internal/config"},
{"trailing slash", "internal/policy/", "internal/policy"},
{"file", "internal/daemon/daemon.go", "internal/daemon/daemon.go"},
{"go wildcard", "internal/infrastructure/...", "internal/infrastructure"},
{"package and symbol", "internal/config.Config", "internal/config.Config"},
{"sentence punctuation", "internal/store,", "internal/store"},
{"line number", "internal/store/store.go:120", "internal/store/store.go"},
{"deep wildcard", "internal/domain/...", "internal/domain"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := normalize(tc.in); got != tc.want {
t.Fatalf("normalize(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
func TestCandidates(t *testing.T) {
tests := []struct {
name string
in string
want []string
}{
{"package with symbol drops the symbol", "internal/config.Config", []string{"internal/config.Config", "internal/config"}},
{"file keeps only itself", "internal/daemon/daemon.go", []string{"internal/daemon/daemon.go"}},
{"bare package", "internal/webui", []string{"internal/webui"}},
{"dotted directory is not a symbol", "internal/domain/eda/module", []string{"internal/domain/eda/module"}},
{"test cited with its package drops the test name", "internal/app/archieui/TestFoo", []string{"internal/app/archieui/TestFoo", "internal/app/archieui"}},
{"lowercase final segment is a package, not a symbol", "internal/domain/curator", []string{"internal/domain/curator"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := candidates(tc.in)
if len(got) != len(tc.want) {
t.Fatalf("candidates(%q) = %v, want %v", tc.in, got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Fatalf("candidates(%q) = %v, want %v", tc.in, got, tc.want)
}
}
})
}
}
// treeFor builds the tracked-path set a citation resolves against, without
// touching the filesystem: resolution is defined by what git tracks, so a test
// asserts the definition rather than one machine's leftover directories.
func treeFor(files ...string) *trackedTree {
tree := &trackedTree{files: map[string]bool{}, dirs: map[string]bool{}}
for _, file := range files {
tree.files[file] = true
for dir := filepath.Dir(file); dir != "." && dir != "/" && dir != ""; dir = filepath.Dir(dir) {
tree.dirs[dir] = true
}
}
return tree
}
func TestResolves(t *testing.T) {
tree := treeFor(
"internal/config/config.go",
"internal/daemon/daemon.go",
"internal/webui/api_logs.go",
"internal/app/archieui/run.go",
"internal/domain/workflow/workflow.go",
)
tests := []struct {
name string
in string
want bool
}{
{"package directory", "internal/webui", true},
{"nested package directory", "internal/domain/workflow", true},
{"file", "internal/daemon/daemon.go", true},
{"package and symbol resolves via the package", "internal/config.Config", true},
{"package cited without the .go file present", "internal/daemon", true},
{"moved package", "internal/memory", false},
{"deleted file", "internal/app/archied/config_update.go", false},
{"never built", "internal/policy", false},
{"whole package tree", "internal", true},
{"file-shape template resolves against a sibling", "internal/webui/api_", true},
{"test cited with its package resolves via the package", "internal/app/archieui/TestComposeUIServerHoldsNoDaemonState", true},
{"file-shape template with no sibling", "internal/webui/nothing_", false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := tree.resolves(tc.in); got != tc.want {
t.Fatalf("resolves(%q) = %v, want %v", tc.in, got, tc.want)
}
})
}
}
// TestResolvesIgnoresTheFilesystem is the regression for the bug this gate
// shipped with. Resolution was a filesystem stat, so a directory left behind by
// a checkout that removed its files -- internal/gate, internal/gate/gateeval --
// resolved on the machine that had the leftovers and resolved nothing in CI.
// The gate passed locally and failed in CI on the same commit, and a baseline
// generated that way is worthless in either direction.
func TestResolvesIgnoresTheFilesystem(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "internal", "gate", "gateeval"), 0o750); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(root, "internal", "config"), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "internal", "config", "config.go"), []byte("package config\n"), 0o600); err != nil {
t.Fatal(err)
}
tree := treeFor("internal/config/config.go")
if tree.resolves("internal/gate") {
t.Error("an empty directory on disk resolved; resolution must come from the tracked tree")
}
if tree.resolves("internal/gate/gateeval") {
t.Error("an empty nested directory on disk resolved; resolution must come from the tracked tree")
}
if !tree.resolves("internal/config") {
t.Error("a tracked package did not resolve")
}
}
// TestNewTrackedTreeReadsGit covers the git half: the tree is what the
// repository holds, so a file present on disk but never added is invisible, and
// an empty directory is invisible in both worlds.
func TestNewTrackedTreeReadsGit(t *testing.T) {
root := t.TempDir()
git := func(args ...string) {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", args...)
cmd.Dir = root
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
git("init", "-q")
git("config", "user.email", "test@example.test")
git("config", "user.name", "test")
if err := os.MkdirAll(filepath.Join(root, "internal", "tracked"), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "internal", "tracked", "x.go"), []byte("package tracked\n"), 0o600); err != nil {
t.Fatal(err)
}
git("add", "internal/tracked/x.go")
// Neither of these is in the repository: one is ignored-by-absence, the
// other is what a checkout that removed a package leaves behind.
if err := os.WriteFile(filepath.Join(root, "internal", "untracked.go"), []byte("package internal\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(root, "internal", "gate", "gateeval"), 0o750); err != nil {
t.Fatal(err)
}
tree, err := newTrackedTree(t.Context(), root)
if err != nil {
t.Fatalf("newTrackedTree: %v", err)
}
if !tree.resolves("internal/tracked") {
t.Error("a tracked package did not resolve")
}
if tree.resolves("internal/untracked.go") {
t.Error("an untracked file resolved; the tree is what the repository holds, not what is on disk")
}
if tree.resolves("internal/gate") {
t.Error("an empty directory resolved; it is not in the repository")
}
}
// TestAnalyseSeparatesNewDriftFromKnownDebt pins the gate's core distinction: a
// citation already broken before this change must not fail the build, while one
// that dangles now must.
func TestAnalyseSeparatesNewDriftFromKnownDebt(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "docs", "architecture"), 0o750); err != nil {
t.Fatal(err)
}
body := "See `internal/webui` and `internal/memory`.\nAlso `internal/nats` and `internal/config`.\n"
if err := os.WriteFile(filepath.Join(root, "docs", "architecture", "page.md"), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
tree := treeFor("internal/config/config.go", "internal/webui/server.go")
got, err := analyse(root, "docs", tree, map[string]bool{"internal/memory": true})
if err != nil {
t.Fatal(err)
}
if len(got.newDrift) != 1 || got.newDrift[0].Path != "internal/nats" {
t.Fatalf("newDrift = %v, want exactly internal/nats", got.newDrift)
}
if got.newDrift[0].Line != 2 {
t.Fatalf("newDrift line = %d, want 2", got.newDrift[0].Line)
}
if got.known != 1 {
t.Fatalf("known = %d, want 1 (internal/memory is allowlisted)", got.known)
}
if got.scanned != 2 {
t.Fatalf("scanned = %d, want 2 (internal/webui, internal/config)", got.scanned)
}
if len(got.stale) != 0 {
t.Fatalf("stale = %v, want none", got.stale)
}
}
// TestAnalyseFlagsAnAllowlistEntryThatResolvesAgain keeps the burn-down list
// honest: once the code comes back, the exemption must go.
func TestAnalyseFlagsAnAllowlistEntryThatResolvesAgain(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "docs"), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "docs", "p.md"), []byte("`internal/policy`\n"), 0o600); err != nil {
t.Fatal(err)
}
got, err := analyse(root, "docs", treeFor("internal/policy/policy.go"), map[string]bool{"internal/policy": true})
if err != nil {
t.Fatal(err)
}
if len(got.stale) != 1 || got.stale[0] != "internal/policy" {
t.Fatalf("stale = %v, want [internal/policy]", got.stale)
}
if len(got.newDrift) != 0 {
t.Fatalf("newDrift = %v, want none", got.newDrift)
}
}
// TestScanSkipsGeneratedAndNonMarkdown guards the double-count: the generated
// dev-docs artifact embeds every page body, so scanning it would inflate both
// the findings and the baseline.
func TestScanSkipsGeneratedAndNonMarkdown(t *testing.T) {
root := t.TempDir()
for _, dir := range []string{"docs/architecture", "docs/data/generated"} {
if err := os.MkdirAll(filepath.Join(root, dir), 0o750); err != nil {
t.Fatal(err)
}
}
write := func(rel, body string) {
t.Helper()
if err := os.WriteFile(filepath.Join(root, rel), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
write("docs/architecture/page.md", "`internal/gone`\n")
write("docs/data/generated/dev-docs.json", "{\"body\":\"internal/also-gone\"}\n")
write("docs/notes.txt", "internal/not-markdown\n")
got, err := scan(root, "docs")
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Path != "internal/gone" {
t.Fatalf("scan = %v, want exactly [internal/gone]", got)
}
}
func TestReadBaseline(t *testing.T) {
root := t.TempDir()
p := filepath.Join(root, "baseline.txt")
body := "# a comment\n\ninternal/store\ninternal/memory \n"
if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
got, err := readBaseline(p)
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || !got["internal/store"] || !got["internal/memory"] {
t.Fatalf("readBaseline = %v, want internal/store and internal/memory", got)
}
}
// TestReadBaselineMissingIsEmpty lets the tool run before a baseline exists.
func TestReadBaselineMissingIsEmpty(t *testing.T) {
got, err := readBaseline(filepath.Join(t.TempDir(), "absent.txt"))
if err != nil {
t.Fatal(err)
}
if len(got) != 0 {
t.Fatalf("readBaseline = %v, want empty", got)
}
}
-518
View File
@@ -1,518 +0,0 @@
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/invopop/jsonschema"
)
type contractWithConflictingDefinition struct {
Value conflictingDefinition `json:"value"`
}
type conflictingDefinition struct {
Value string `json:"value"`
}
func TestRunWritesDeterministicContractData(t *testing.T) {
repoRoot := filepath.Clean("../..")
outputDir := t.TempDir()
outputs := []string{
filepath.Join(outputDir, "first.json"),
filepath.Join(outputDir, "second.json"),
}
for _, output := range outputs {
if err := run(repoRoot, output); err != nil {
t.Fatalf("run(%q) error = %v", output, err)
}
}
first, err := os.ReadFile(outputs[0])
if err != nil {
t.Fatalf("read first output: %v", err)
}
second, err := os.ReadFile(outputs[1])
if err != nil {
t.Fatalf("read second output: %v", err)
}
if !bytes.Equal(first, second) {
t.Fatal("repeated generation produced different bytes")
}
var data struct {
GeneratedBy string `json:"generatedBy"`
Schemas map[string]json.RawMessage `json:"schemas"`
}
if err := json.Unmarshal(first, &data); err != nil {
t.Fatalf("decode generated data: %v", err)
}
if data.GeneratedBy != "tools/docsgen" {
t.Fatalf("generatedBy = %q, want %q", data.GeneratedBy, "tools/docsgen")
}
for _, name := range []string{
"AgentExecutionRequest",
"AgentExecutionResult",
"MessageEvent",
} {
if _, ok := data.Schemas[name]; !ok {
t.Errorf("schemas[%q] is missing", name)
}
}
for name, schema := range data.Schemas {
assertSchemaRefsResolve(t, name, schema, data.Schemas)
}
}
func TestRunHonoursAbsoluteOutputPath(t *testing.T) {
repoRoot := filepath.Clean("../..")
outputDir := t.TempDir()
originalDir, err := os.Getwd()
if err != nil {
t.Fatalf("get working directory: %v", err)
}
for _, name := range []string{"first.yaml", "second.yaml"} {
output := filepath.Join(outputDir, name)
if err := run(repoRoot, output); err != nil {
t.Fatalf("run(%q) error = %v", name, err)
}
if _, err := os.Stat(output); err != nil {
t.Fatalf("generated output %q: %v", name, err)
}
}
currentDir, err := os.Getwd()
if err != nil {
t.Fatalf("get restored working directory: %v", err)
}
if currentDir != originalDir {
t.Fatalf("working directory = %q, want %q", currentDir, originalDir)
}
}
func TestCollectSchemaRejectsDuplicatePublishedName(t *testing.T) {
reflector := &jsonschema.Reflector{ExpandedStruct: true}
schemas := map[string]any{}
const name = "PublishedContract"
if err := collectSchema(reflector, schemas, name, reflect.TypeFor[struct {
First string `json:"first"`
}]()); err != nil {
t.Fatalf("collect first schema: %v", err)
}
err := collectSchema(reflector, schemas, name, reflect.TypeFor[struct {
Second int `json:"second"`
}]())
if err == nil {
t.Fatal("collect duplicate schema returned nil error")
}
}
func TestCollectSchemaRejectsConflictingDefinition(t *testing.T) {
reflector := &jsonschema.Reflector{ExpandedStruct: true}
schemas := map[string]any{
"conflictingDefinition": map[string]any{"type": "integer"},
}
err := collectSchema(
reflector,
schemas,
"PublishedContract",
reflect.TypeFor[contractWithConflictingDefinition](),
)
if err == nil {
t.Fatal("collect conflicting definition returned nil error")
}
if !strings.Contains(err.Error(), `conflicting schema definition "conflictingDefinition"`) {
t.Fatalf("collect conflicting definition error = %q", err)
}
}
func TestRunReportsFilesystemAndSourceErrors(t *testing.T) {
repoRoot := filepath.Clean("../..")
blocker := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(blocker, []byte("occupied"), 0o600); err != nil {
t.Fatalf("create blocker: %v", err)
}
tests := []struct {
name string
root string
output string
contains string
}{
{
name: "missing source tree",
root: t.TempDir(),
output: filepath.Join(t.TempDir(), "contracts.json"),
contains: "load Go comments",
},
{
name: "output parent is a file",
root: repoRoot,
output: filepath.Join(blocker, "contracts.json"),
contains: "create output directory",
},
{
name: "output is a directory",
root: repoRoot,
output: t.TempDir(),
contains: "write ",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := run(test.root, test.output)
if err == nil {
t.Fatal("run() returned nil error")
}
if !bytes.Contains([]byte(err.Error()), []byte(test.contains)) {
t.Fatalf("run() error = %q, want substring %q", err, test.contains)
}
})
}
}
func TestCheckAcceptsTheCommittedArtifact(t *testing.T) {
repoRoot := filepath.Clean("../..")
if err := check(repoRoot, defaultOutputPath); err != nil {
t.Fatalf("check(%q) error = %v; committed generated data is stale", defaultOutputPath, err)
}
}
func TestCheckReportsChangedSchema(t *testing.T) {
repoRoot := filepath.Clean("../..")
output := filepath.Join(t.TempDir(), "contracts.json")
if err := run(repoRoot, output); err != nil {
t.Fatalf("run() error = %v", err)
}
mutateGeneratedData(t, output, func(data map[string]any) {
schemas := mapAt(t, data, "schemas")
mapAt(t, schemas, "AgentExecutionResult")["title"] = "tampered"
})
err := check(repoRoot, output)
if err == nil {
t.Fatal("check() returned nil error for a changed artifact")
}
for _, want := range []string{"changed", "AgentExecutionResult", "agentexec.Result"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("check() error = %q, want substring %q", err, want)
}
}
}
func TestCheckReportsRemovedSchema(t *testing.T) {
repoRoot := filepath.Clean("../..")
output := filepath.Join(t.TempDir(), "contracts.json")
if err := run(repoRoot, output); err != nil {
t.Fatalf("run() error = %v", err)
}
mutateGeneratedData(t, output, func(data map[string]any) {
delete(mapAt(t, data, "schemas"), "MessageEvent")
})
err := check(repoRoot, output)
if err == nil {
t.Fatal("check() returned nil error for a removed schema")
}
if !strings.Contains(err.Error(), "MessageEvent") {
t.Errorf("check() error = %q, want the removed schema named", err)
}
}
func TestCheckReportsMissingArtifact(t *testing.T) {
repoRoot := filepath.Clean("../..")
output := filepath.Join(t.TempDir(), "contracts.json")
err := check(repoRoot, output)
if err == nil {
t.Fatal("check() returned nil error for a missing artifact")
}
if !strings.Contains(err.Error(), "missing") {
t.Fatalf("check() error = %q, want it to report a missing artifact", err)
}
if _, statErr := os.Stat(output); statErr == nil {
t.Fatal("check() created the missing artifact instead of reporting it")
}
}
func TestParseOptions(t *testing.T) {
tests := []struct {
name string
args []string
wantMode mode
wantOut string
wantErr string
}{
{name: "write by default", wantMode: modeWrite, wantOut: defaultOutputPath},
{name: "check first", args: []string{"check"}, wantMode: modeCheck, wantOut: defaultOutputPath},
{
name: "check with flags",
args: []string{"check", "--repo-root", ".."},
wantMode: modeCheck,
wantOut: defaultOutputPath,
},
{
name: "check honours out",
args: []string{"check", "--out", "/tmp/artifacts.json"},
wantMode: modeCheck,
wantOut: "/tmp/artifacts.json",
},
{
name: "check after flags would otherwise silently write",
args: []string{"--repo-root", "..", "check"},
wantErr: "unexpected argument",
},
{name: "misspelled subcommand", args: []string{"chekc"}, wantErr: "unexpected argument"},
{
name: "stray trailing argument",
args: []string{"--out", "/tmp/artifacts.json", "stray"},
wantErr: "unexpected argument",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := parseOptions(test.args)
if test.wantErr != "" {
if err == nil {
t.Fatalf("parseOptions(%q) returned nil error, want %q", test.args, test.wantErr)
}
if !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("parseOptions(%q) error = %q, want substring %q", test.args, err, test.wantErr)
}
return
}
if err != nil {
t.Fatalf("parseOptions(%q) error = %v", test.args, err)
}
if got.mode != test.wantMode {
t.Errorf("parseOptions(%q).mode = %v, want %v", test.args, got.mode, test.wantMode)
}
if got.out != test.wantOut {
t.Errorf("parseOptions(%q).out = %q, want %q", test.args, got.out, test.wantOut)
}
})
}
}
func TestSchemaProvenanceFollowsNestedDefinitions(t *testing.T) {
schemas := map[string]any{
"Root": map[string]any{
"properties": map[string]any{
"middle": map[string]any{"$ref": "#/schemas/Middle"},
},
},
"Middle": map[string]any{
"properties": map[string]any{
"leaf": map[string]any{"$ref": "#/schemas/Leaf"},
},
},
"Leaf": map[string]any{"type": "string"},
}
provenance := schemaProvenance(schemas, map[string]string{"Root": "example.Root"})
if got := provenance["Root"]; got != "example.Root" {
t.Errorf("provenance[Root] = %q, want the root definition", got)
}
if got := provenance["Middle"]; got != "reached from example.Root" {
t.Errorf("provenance[Middle] = %q, want it reached from the root", got)
}
// Leaf is reachable only through Middle. A one-level walk misses it, and the
// report then claims no authoritative definition exists.
if got := provenance["Leaf"]; got != "reached from example.Root" {
t.Errorf("provenance[Leaf] = %q, want it reached from the root transitively", got)
}
}
func TestObsoleteArtifactsReportsUnownedFileInAnOwnedDirectory(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "docs", "data", "generated")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("create generated dir: %v", err)
}
for name, body := range map[string]string{
"contracts.json": "{}\n", // owned
"orphaned.json": "{}\n", // obsolete
"notes.txt": "not json\n",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
problems := obsoleteArtifacts(root, dir)
if len(problems) != 1 {
t.Fatalf("obsoleteArtifacts() = %q, want exactly the orphan", problems)
}
if !strings.Contains(problems[0], "orphaned.json") || !strings.Contains(problems[0], "obsolete") {
t.Fatalf("obsoleteArtifacts() = %q, want the orphan named", problems)
}
}
func TestObsoleteArtifactsNeverJudgesAnUnownedDirectory(t *testing.T) {
root := t.TempDir()
// An arbitrary --out location: the JSON beside the artifact belongs to
// whoever put it there, and docsgen must not claim it as its own.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "someone-elses.json"), []byte("{}\n"), 0o600); err != nil {
t.Fatalf("write foreign json: %v", err)
}
if problems := obsoleteArtifacts(root, dir); len(problems) != 0 {
t.Fatalf("obsoleteArtifacts() = %q, want none for an unowned directory", problems)
}
}
func TestCheckNeverModifiesTheWorkingTree(t *testing.T) {
repoRoot := filepath.Clean("../..")
outputDir := t.TempDir()
output := filepath.Join(outputDir, "contracts.json")
if err := run(repoRoot, output); err != nil {
t.Fatalf("run() error = %v", err)
}
mutateGeneratedData(t, output, func(data map[string]any) {
data["generatedBy"] = "tampered"
})
before, err := os.ReadFile(output)
if err != nil {
t.Fatalf("read before: %v", err)
}
beforeInfo, err := os.Stat(output)
if err != nil {
t.Fatalf("stat before: %v", err)
}
if err := check(repoRoot, output); err == nil {
t.Fatal("check() returned nil error for a changed artifact")
}
after, err := os.ReadFile(output)
if err != nil {
t.Fatalf("read after: %v", err)
}
if !bytes.Equal(before, after) {
t.Fatal("check() rewrote the artifact under test")
}
afterInfo, err := os.Stat(output)
if err != nil {
t.Fatalf("stat after: %v", err)
}
if beforeInfo.Mode() != afterInfo.Mode() {
t.Fatalf("check() changed the artifact mode: %v -> %v", beforeInfo.Mode(), afterInfo.Mode())
}
if entries, err := os.ReadDir(outputDir); err != nil {
t.Fatalf("read output dir: %v", err)
} else if len(entries) != 1 {
t.Fatalf("check() left %d files in the output dir, want 1", len(entries))
}
}
func mutateGeneratedData(t *testing.T, path string, mutate func(map[string]any)) {
t.Helper()
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
var data map[string]any
if err := json.Unmarshal(raw, &data); err != nil {
t.Fatalf("decode %s: %v", path, err)
}
mutate(data)
body, err := json.MarshalIndent(data, "", " ")
if err != nil {
t.Fatalf("encode %s: %v", path, err)
}
if err := os.WriteFile(path, append(body, '\n'), 0o600); err != nil {
t.Fatalf("write %s: %v", path, err)
}
}
func TestRewriteRef(t *testing.T) {
tests := map[string]string{
"definition": "#/schemas/Contract",
"external": "https://example.com/schema.json",
"empty name": "#/$defs/",
}
for name, want := range tests {
t.Run(name, func(t *testing.T) {
input := want
if name == "definition" {
input = "#/$defs/Contract"
}
if got := rewriteRef(input); got != want {
t.Fatalf("rewriteRef(%q) = %q, want %q", input, got, want)
}
})
}
}
func assertSchemaRefsResolve(
t *testing.T,
name string,
raw json.RawMessage,
schemas map[string]json.RawMessage,
) {
t.Helper()
var value any
if err := json.Unmarshal(raw, &value); err != nil {
t.Fatalf("decode schema %q: %v", name, err)
}
walkJSON(value, func(ref string) {
const prefix = "#/schemas/"
if !strings.HasPrefix(ref, "#") {
return
}
if !strings.HasPrefix(ref, prefix) {
t.Errorf("schema %q contains unresolved local reference %q", name, ref)
return
}
target := ref[len(prefix):]
if _, ok := schemas[target]; !ok {
t.Errorf("schema %q references missing schema %q", name, target)
}
})
}
func walkJSON(value any, visitRef func(string)) {
switch node := value.(type) {
case map[string]any:
for key, child := range node {
if key == "$ref" {
if ref, ok := child.(string); ok {
visitRef(ref)
}
continue
}
walkJSON(child, visitRef)
}
case []any:
for _, child := range node {
walkJSON(child, visitRef)
}
}
}
// mapAt returns the nested object at key, failing the test rather than panicking
// when the generated artifact does not have the shape the case assumes.
func mapAt(t *testing.T, parent map[string]any, key string) map[string]any {
t.Helper()
child, ok := parent[key].(map[string]any)
if !ok {
t.Fatalf("%s is %T, want an object", key, parent[key])
}
return child
}
-380
View File
@@ -1,380 +0,0 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// documentFor is the generated artifact for one set.
func documentFor(t *testing.T, generated []setDocument, set docSet) document {
t.Helper()
for _, entry := range generated {
if entry.Set.Name == set.Name {
return entry.Document
}
}
t.Fatalf("no %s set was generated", set.Name)
return document{}
}
// TestTheSplitIsByAudience pins the two sets against the real tree. The public
// set is a decision page by page, so its contents are listed: a page joining or
// leaving what a customer reads has to be acknowledged here rather than sliding
// onto the site. The development set is a rule rather than a list, because a PRD
// is added most weeks and pinning a count would make this test a chore that
// teaches nothing.
func TestTheSplitIsByAudience(t *testing.T) {
generated, err := load("../..")
if err != nil {
t.Fatalf("load: %v", err)
}
public := documentFor(t, generated, publicDocs)
development := documentFor(t, generated, developmentDocs)
publicURLs := urlSet(t, public)
if len(publicURLs) != 3 {
t.Errorf("public set = %v, want the landing page and two guides", sortedKeys(publicURLs))
}
for _, want := range []string{"/docs/", "/docs/guides/first-playbook/", "/docs/guides/pr-review-benchmark/"} {
if !publicURLs[want] {
t.Errorf("%s is not in the public set", want)
}
}
developmentURLs := urlSet(t, development)
for _, want := range []string{
"/dev/architecture/",
"/dev/architecture/organisation/",
"/dev/development/",
"/dev/prds/ui-service-boundary/",
// Selective PRD publication is gone: an open PRD is a development page like
// any other, which is what removes the pressure that published five of them
// to keep citations from settled architecture alive.
"/dev/prds/curator-sampler-wave1/",
} {
if !developmentURLs[want] {
t.Errorf("%s is not in the development set", want)
}
}
// Neither set may carry the other's pages, and neither may carry a held-back
// tree.
for url := range publicURLs {
if strings.HasPrefix(url, "/docs/architecture/") || strings.HasPrefix(url, "/docs/prds/") {
t.Errorf("%s is in the public set; architecture/ and prds/ are development pages", url)
}
}
for url := range developmentURLs {
if !strings.HasPrefix(url, "/dev/") {
t.Errorf("%s is in the development set but is not served under its base", url)
}
}
for _, held := range []string{"archive/", "inspiration/", "news/", "github-token/"} {
for _, url := range append(sortedKeys(publicURLs), sortedKeys(developmentURLs)...) {
if strings.Contains(url, held) {
t.Errorf("%s is published; it is held back deliberately", url)
}
}
}
}
// urlSet indexes a set's pages by url, asserting on the way that each carries the
// body a renderer needs.
func urlSet(t *testing.T, doc document) map[string]bool {
t.Helper()
urls := map[string]bool{}
for _, entry := range doc.Pages {
urls[entry.URL] = true
if entry.Body == "" {
t.Errorf("%s carries no body; the artifact is the source a renderer needs", entry.URL)
}
if !strings.HasPrefix(entry.Body, "#") {
t.Errorf("%s body does not start with a heading: %q", entry.URL, firstLine(entry.Body))
}
}
return urls
}
func sortedKeys(urls map[string]bool) []string {
keys := make([]string, 0, len(urls))
for url := range urls {
keys = append(keys, url)
}
return keys
}
func firstLine(body string) string {
line, _, _ := strings.Cut(body, "\n")
return line
}
// TestPageURLsAreTheStaticSitePaths: every existing link points at the
// directory-style path a static site produces, so the artifact has to reproduce
// it exactly rather than inventing a cleaner one. The base is the one its set is
// served under.
func TestPageURLsAreTheStaticSitePaths(t *testing.T) {
for _, tc := range []struct{ relative, want string }{
{"index.md", "/docs/"},
{"guides/first-playbook.md", "/docs/guides/first-playbook/"},
{"guides/nested/deep.md", "/docs/guides/nested/deep/"},
{"architecture/index.md", "/dev/architecture/"},
{"architecture/organisation.md", "/dev/architecture/organisation/"},
{"prds/config-schema.md", "/dev/prds/config-schema/"},
} {
if got := pageURL(tc.relative); got != tc.want {
t.Errorf("pageURL(%q) = %q, want %q", tc.relative, got, tc.want)
}
}
}
// TestNavMirrorsTheLayout: the tree is derived from the directory structure, so a
// page added under a directory appears in the sidebar without a second edit or a
// hand-maintained navigation entry.
func TestNavMirrorsTheLayout(t *testing.T) {
nav := navFor([]page{
{URL: "/docs/", Title: "Archie"},
{URL: "/docs/guides/first-playbook/", Title: "Building your first playbook binding"},
}, publicDocs.URLPrefix)
if len(nav) != 2 {
t.Fatalf("nav = %+v, want home plus one group", nav)
}
if nav[0].URL != "/docs/" {
t.Errorf("first entry = %+v, want the home page", nav[0])
}
// A directory holding one page is still a group: collapsing it would be a
// shape this artifact invented rather than one it reports.
guides := nav[1]
if guides.Title != "Guides" || len(guides.Items) != 1 || guides.Items[0].URL != "/docs/guides/first-playbook/" {
t.Errorf("guides = %+v, want a group wrapping its single page", guides)
}
// The development set has no page of its own at its base, so its sidebar opens
// with the sections rather than a home link.
devNav := navFor([]page{
{URL: "/dev/architecture/", Title: "Architecture"},
{URL: "/dev/architecture/organisation/", Title: "Organisation"},
{URL: "/dev/architecture/policy/", Title: "Policy"},
{URL: "/dev/prds/config-schema/", Title: "Config schema"},
}, developmentDocs.URLPrefix)
if len(devNav) != 2 {
t.Fatalf("nav = %+v, want the two sections and no home entry", devNav)
}
architecture := devNav[0]
if architecture.Title != "Architecture" || architecture.URL != "/dev/architecture/" {
t.Errorf("group = %+v, want the section with its own landing page", architecture)
}
if len(architecture.Items) != 2 || architecture.Items[0].Title != "Organisation" {
t.Errorf("items = %+v, want the section's pages in order", architecture.Items)
}
}
// TestCheckFailsOnAStaleArtifactAndLeavesTheTreeAlone: check is what runs in the
// gate, so it has to fail on a source edit that never reached an artifact without
// writing anything itself. A stale development artifact fails it exactly as a
// stale public one does; before both were checked, a change to a development page
// could land with no artifact carrying it.
func TestCheckFailsOnAStaleArtifactAndLeavesTheTreeAlone(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "docs", "index.md"), "# Archie\n\nHello.\n")
writeFile(t, filepath.Join(root, "docs", "architecture", "policy.md"), "# Policy\n\nRules.\n")
writeFile(t, filepath.Join(root, "docs", "archive", "old.md"), "# Old\n\nSuperseded.\n")
if err := check(root); err == nil {
t.Fatal("check(missing) = nil, want a failure: no artifact is committed")
}
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check after write = %v, want it to pass", err)
}
stale := filepath.Join(root, "docs", "data", "generated", "dev-docs.json")
writeFile(t, stale, "{}\n")
if err := check(root); err == nil {
t.Fatal("check(stale development artifact) = nil, want a failure")
}
before, err := os.ReadFile(stale)
if err != nil {
t.Fatal(err)
}
if string(before) != "{}\n" {
t.Fatalf("check rewrote the artifact: %q", before)
}
generated, err := load(root)
if err != nil {
t.Fatal(err)
}
if pages := documentFor(t, generated, publicDocs).Pages; len(pages) != 1 {
t.Fatalf("public pages = %d, want the landing page alone", len(pages))
}
if pages := documentFor(t, generated, developmentDocs).Pages; len(pages) != 1 {
t.Fatalf("development pages = %d, want the architecture page alone (archive/ is held back)", len(pages))
}
}
// TestUntrackedPagesDoNotReachTheArtifact pins why the artifact is derived from
// the commit rather than from the working tree. docs:artifact:check runs in the
// gate and reads the sources from disk, so an untracked page under docs/ made
// the committed artifact look stale. The gate then demanded a regeneration that
// was already correct, and that regeneration would have committed a page no
// commit carries. It cost two sessions in one day: a migration branch, and an
// unrelated writer adding a PRD.
func TestUntrackedPagesDoNotReachTheArtifact(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "docs", "index.md"), "# Archie\n\nHello.\n")
writeFile(t, filepath.Join(root, "docs", "architecture", "policy.md"), "# Policy\n\nRules.\n")
gitIn(t, root, "init", "--quiet")
gitIn(t, root, "add", "docs/index.md", "docs/architecture/policy.md")
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
// Untracked: no commit carries it, so the committed artifact is not required
// to contain it and check must not claim the artifact is stale.
writeFile(t, filepath.Join(root, "docs", "prds", "scratch.md"), "# Scratch\n\nNot committed.\n")
if err := check(root); err != nil {
t.Fatalf("check with an untracked page = %v, want it to pass", err)
}
// Staged: this commit is about to carry it, so the artifact must too.
gitIn(t, root, "add", "docs/prds/scratch.md")
if err := check(root); err == nil {
t.Fatal("check with a staged page = nil, want a failure: the artifact does not carry it")
}
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check after regenerating for the staged page = %v, want it to pass", err)
}
}
// gitIn runs one git command in dir, failing loudly rather than skipping: task
// check already requires git for proto:lint, so a test that quietly passed
// without it would be asserting nothing.
func gitIn(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...)
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=docsite", "GIT_AUTHOR_EMAIL=docsite@example.invalid",
"GIT_COMMITTER_NAME=docsite", "GIT_COMMITTER_EMAIL=docsite@example.invalid",
)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
// TestLinksResolveAcrossSetsAndFailOutsideThem pins both halves of link handling.
// An intra-docs link becomes the target page's url, using the same rule that
// builds the target's url, so a citation that crosses from one set to the other
// lands on the base its target is actually served under. Anchors and
// scheme-qualified links pass through. A link whose target neither set carries
// fails the load, naming the file, the line and the target, because a hopeful
// rewrite would hide a 404 rather than report it.
func TestLinksResolveAcrossSetsAndFailOutsideThem(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "docs", "architecture", "organisation.md"),
"# Organisation\n\nBack [home](../index.md).\n")
writeFile(t, filepath.Join(root, "docs", "archive", "old.md"), "# Old\n")
writeFile(t, filepath.Join(root, "docs", "index.md"),
"# Archie\n\nSee [Organisation](architecture/organisation.md#organisation).\n\n[Old](archive/old.md) is held back.\n")
_, err := load(root)
if err == nil {
t.Fatal("load = nil, want a refusal: a page links into archive/, which is held back")
}
for _, want := range []string{"index.md:5", "archive/old.md", "not in the published set"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error = %q, want it to contain %q", err, want)
}
}
// The same tree without the out-of-set link: each link becomes the target page's
// url, under the target's own base.
writeFile(t, filepath.Join(root, "docs", "index.md"),
"# Archie\n\nSee [Organisation](architecture/organisation.md#organisation), [OpenAI](https://openai.com/) and [below](#anchors).\n")
generated, err := load(root)
if err != nil {
t.Fatalf("load: %v", err)
}
index := bodyOf(t, documentFor(t, generated, publicDocs), "/docs/")
for _, want := range []string{
"(/dev/architecture/organisation/#organisation)",
"(https://openai.com/)",
"(#anchors)",
} {
if !strings.Contains(index, want) {
t.Errorf("public body = %q, want it to contain %q", index, want)
}
}
organisation := bodyOf(t, documentFor(t, generated, developmentDocs), "/dev/architecture/organisation/")
if !strings.Contains(organisation, "(/docs/)") {
t.Errorf("development body = %q, want the link back to the public landing page", organisation)
}
}
func bodyOf(t *testing.T, doc document, url string) string {
t.Helper()
for _, entry := range doc.Pages {
if entry.URL == url {
return entry.Body
}
}
t.Fatalf("no page at %s", url)
return ""
}
// TestFragmentsAreValidatedAgainstTheTargetsHeadings: a link can resolve to a page
// and still be broken, because a fragment that matches no heading lands the reader
// at the top of a long document with no indication why. The slug rule mirrors a
// Markdown renderer's table of contents, so the ids it accepts are the ids the
// rendered page carries.
func TestFragmentsAreValidatedAgainstTheTargetsHeadings(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "docs", "architecture", "decisions.md"),
"# Decisions\n\n## 5. Memory placement and storage\n\n## Bindings & secrets\n")
writeFile(t, filepath.Join(root, "docs", "index.md"),
"# Archie\n\n[Good](architecture/decisions.md#5-memory-placement-and-storage).\n\n[Bad](architecture/decisions.md#5).\n")
_, err := load(root)
if err == nil {
t.Fatal("load = nil, want a refusal: #5 matches no heading on the target page")
}
for _, want := range []string{"index.md:5", "#5", "no such heading"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error = %q, want it to contain %q", err, want)
}
}
if strings.Contains(err.Error(), "#5-memory-placement-and-storage") {
t.Errorf("error = %q, want only the broken fragment named", err)
}
// A fragment that does match, including one whose heading has punctuation and an
// ampersand, passes and is carried verbatim.
writeFile(t, filepath.Join(root, "docs", "index.md"),
"# Archie\n\n[Good](architecture/decisions.md#5-memory-placement-and-storage).\n\n[Also](architecture/decisions.md#bindings-secrets).\n")
generated, err := load(root)
if err != nil {
t.Fatalf("load: %v", err)
}
if index := bodyOf(t, documentFor(t, generated, publicDocs), "/docs/"); !strings.Contains(index, "(/dev/architecture/decisions/#bindings-secrets)") {
t.Errorf("resolved body = %q, want the ampersand heading's slug", index)
}
}
-165
View File
@@ -1,165 +0,0 @@
package main
import (
"strings"
"testing"
)
const sampleChangelog = `# Changelog
## [1.31.0] - 2026-09-22
### archied — A heading
- one bullet
## [1.30.0] - 2026-09-20
Just prose.
## [Unreleased]
Future work.
## Licence
Not a release section.
`
func TestParseChangelogReadsReleaseSections(t *testing.T) {
got, err := parseChangelog(sampleChangelog)
if err != nil {
t.Fatalf("parseChangelog error = %v", err)
}
if len(got) != 2 {
t.Fatalf("got %d releases, want 2: %+v", len(got), got)
}
first := got[0]
if first.Version != "1.31.0" || first.Date != "2026-09-22" {
t.Fatalf("first release version/date = %q/%q", first.Version, first.Date)
}
if first.Body != "### archied — A heading\n\n- one bullet" {
t.Fatalf("first release body = %q", first.Body)
}
if got[1].Version != "1.30.0" || got[1].Body != "Just prose." {
t.Fatalf("second release = %+v", got[1])
}
}
func TestParseChangelogSkipsUnreleased(t *testing.T) {
got, err := parseChangelog(sampleChangelog)
if err != nil {
t.Fatalf("parseChangelog error = %v", err)
}
for _, r := range got {
if r.Version == "Unreleased" {
t.Fatal("Unreleased was published as a release")
}
}
}
func TestParseChangelogRejectsMalformedInput(t *testing.T) {
tests := []struct {
name string
source string
wantSub string
}{
{
name: "release heading without a date",
source: "## [1.2.0]\n\nNotes.\n",
wantSub: "no date",
},
{
name: "release heading with an invalid date",
source: "## [1.2.0] - 2026-9-2\n\nNotes.\n",
wantSub: "not a release heading",
},
{
name: "release without notes",
source: "## [1.2.0] - 2026-01-01\n",
wantSub: "no notes",
},
{
name: "relative markdown link",
source: "## [1.2.0] - 2026-01-01\n\nSee [the guide](guides/first-playbook.md).\n",
wantSub: "relative link",
},
{
name: "relative image link",
source: "## [1.2.0] - 2026-01-01\n\n![shot](images/shot.png)\n",
wantSub: "relative link",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := parseChangelog(tt.source)
if err == nil {
t.Fatal("expected an error")
}
if !strings.Contains(err.Error(), tt.wantSub) {
t.Fatalf("error = %q, want it to mention %q", err, tt.wantSub)
}
})
}
}
func TestParseChangelogAllowsAbsoluteLinks(t *testing.T) {
source := `## [1.2.0] - 2026-01-01
- [vulnerability](https://pkg.go.dev/vuln/GO-2026-6443), [anchor](#section),
[root](/absolute), [angle](<https://example.com>), [mail](mailto:a@b.c).
`
if _, err := parseChangelog(source); err != nil {
t.Fatalf("parseChangelog error = %v", err)
}
}
func TestParseChangelogKeepsFencedHeadingsInTheBody(t *testing.T) {
source := "## [1.2.0] - 2026-01-01\n\n```sh\n## not a heading\n```\n\n- after the fence\n"
got, err := parseChangelog(source)
if err != nil {
t.Fatalf("parseChangelog error = %v", err)
}
if len(got) != 1 {
t.Fatalf("got %d releases, want 1", len(got))
}
want := "```sh\n## not a heading\n```\n\n- after the fence"
if got[0].Body != want {
t.Fatalf("body = %q, want %q", got[0].Body, want)
}
}
func TestCompareVersions(t *testing.T) {
tests := []struct {
a, b string
want int
}{
{"1.9.10", "1.9.9", 1},
{"1.10.0", "1.9.0", 1},
{"2.0.0", "1.99.99", 1},
{"1.0.0", "2.0.0", -1},
{"1.9.0", "1.9.0", 0},
{"1.2.3", "1.2.3-rc1", 1},
}
for _, tt := range tests {
if got := compareVersions(tt.a, tt.b); got != tt.want {
t.Fatalf("compareVersions(%q, %q) = %d, want %d", tt.a, tt.b, got, tt.want)
}
}
}
func TestSortReleasesNewestFirstThenVersion(t *testing.T) {
releases := []release{
{Version: "1.9.9", Date: "2026-09-22"},
{Version: "1.30.0", Date: "2026-09-20"},
{Version: "1.9.10", Date: "2026-09-22"},
{Version: "1.31.0", Date: "2026-09-22"},
}
sortReleases(releases)
want := []string{"1.31.0", "1.9.10", "1.9.9", "1.30.0"}
for i, w := range want {
if releases[i].Version != w {
t.Fatalf("position %d = %s, want %s (all: %+v)", i, releases[i].Version, w, releases)
}
}
}
-160
View File
@@ -1,160 +0,0 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
const changelogFixture = `# Changelog
## [1.31.0] - 2026-09-22
### archied — Gateway
- gateway bullet
`
func writeChangelog(t *testing.T, root, body string) {
t.Helper()
if err := os.WriteFile(filepath.Join(root, changelogPath), []byte(body), 0o644); err != nil {
t.Fatalf("write %s: %v", changelogPath, err)
}
}
func readFile(t *testing.T, root, name string) []byte {
t.Helper()
body, err := os.ReadFile(filepath.Join(root, name))
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
return body
}
func TestWriteThenCheckIsClean(t *testing.T) {
root := t.TempDir()
writeChangelog(t, root, changelogFixture)
if err := write(root); err != nil {
t.Fatalf("write error = %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check after write error = %v", err)
}
}
func TestWriteIsIdempotent(t *testing.T) {
root := t.TempDir()
writeChangelog(t, root, changelogFixture)
if err := write(root); err != nil {
t.Fatalf("first write error = %v", err)
}
first := readFile(t, root, releasesJSONPath)
if err := write(root); err != nil {
t.Fatalf("second write error = %v", err)
}
if second := readFile(t, root, releasesJSONPath); string(second) != string(first) {
t.Fatalf("second write changed %s", releasesJSONPath)
}
}
func TestCheckReportsAStaleChangelog(t *testing.T) {
root := t.TempDir()
writeChangelog(t, root, changelogFixture)
if err := write(root); err != nil {
t.Fatalf("write error = %v", err)
}
writeChangelog(t, root, changelogFixture+"\n## [1.32.0] - 2026-09-23\n\n- newer bullet\n")
err := check(root)
if err == nil {
t.Fatal("check accepted a committed tree that lags the changelog")
}
for _, want := range []string{"task news", releasesJSONPath} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("error = %q, want it to mention %q", err, want)
}
}
}
func TestCheckIgnoresRetiredMarkdownAdapters(t *testing.T) {
root := t.TempDir()
writeChangelog(t, root, changelogFixture)
if err := write(root); err != nil {
t.Fatalf("write error = %v", err)
}
stale := filepath.Join(root, "docs", "news", "9.9.9.md")
if err := os.WriteFile(stale, []byte("gone from the changelog\n"), 0o644); err != nil {
t.Fatalf("write stale page: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check considered a retired Markdown adapter: %v", err)
}
}
func TestCheckIgnoresRetiredComponentMarkdownLayout(t *testing.T) {
root := t.TempDir()
writeChangelog(t, root, changelogFixture)
if err := write(root); err != nil {
t.Fatalf("write error = %v", err)
}
retired := filepath.Join(root, "docs", "news", "archied", "1.31.0.md")
if err := os.MkdirAll(filepath.Dir(retired), 0o755); err != nil {
t.Fatalf("create retired directory: %v", err)
}
if err := os.WriteFile(retired, []byte("old layout\n"), 0o644); err != nil {
t.Fatalf("write retired page: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check considered a retired component Markdown adapter: %v", err)
}
}
func TestWriteLeavesOtherNewsFilesAlone(t *testing.T) {
root := t.TempDir()
writeChangelog(t, root, changelogFixture)
if err := write(root); err != nil {
t.Fatalf("write error = %v", err)
}
announcement := filepath.Join(root, "docs", "news", "announcement.md")
if err := os.WriteFile(announcement, []byte("hand-written\n"), 0o644); err != nil {
t.Fatalf("write announcement: %v", err)
}
if err := write(root); err != nil {
t.Fatalf("second write error = %v", err)
}
if _, err := os.Stat(announcement); err != nil {
t.Fatalf("write removed a hand-written news page: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check rejected a hand-written news page it does not own: %v", err)
}
}
func TestRealChangelogParses(t *testing.T) {
releases, err := load(filepath.Join("..", ".."))
if err != nil {
t.Fatalf("load the real changelog: %v", err)
}
if len(releases) == 0 {
t.Fatal("the real changelog produced no releases")
}
seen := map[string]bool{}
for _, r := range releases {
if r.Version == "" || r.Date == "" || r.Body == "" {
t.Fatalf("incomplete release: %+v", r)
}
if seen[r.Version] {
t.Fatalf("version %s appears twice in the merged history", r.Version)
}
seen[r.Version] = true
}
}
-123
View File
@@ -1,123 +0,0 @@
package main
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
func sampleReleases() []release {
return []release{
{Version: "1.31.0", Date: "2026-09-22", Body: "### archied — Gateway\n\n- a bullet\n\n### archie-agent\n\n- a runtime bullet"},
{Version: "1.30.0", Date: "2026-09-20", Body: "Prose."},
}
}
func TestRenderEmitsTheCanonicalJSON(t *testing.T) {
files, err := render(sampleReleases())
if err != nil {
t.Fatalf("render error = %v", err)
}
body, ok := files[releasesJSONPath]
if !ok {
t.Fatalf("render produced no %s (files: %v)", releasesJSONPath, keys(files))
}
var decoded []release
if err := json.Unmarshal(body, &decoded); err != nil {
t.Fatalf("canonical JSON does not decode into []release: %v", err)
}
if !reflect.DeepEqual(decoded, sampleReleases()) {
t.Fatalf("round trip = %+v, want %+v", decoded, sampleReleases())
}
}
func TestRenderJSONKeepsHTMLCharactersReadable(t *testing.T) {
releases := []release{{
Version: "1.0.0", Date: "2026-01-01",
Body: "a -> b and <memory>",
}}
files, err := render(releases)
if err != nil {
t.Fatalf("render error = %v", err)
}
got := string(files[releasesJSONPath])
for _, want := range []string{"a -> b", "<memory>"} {
if !strings.Contains(got, want) {
t.Fatalf("canonical JSON escaped %q:\n%s", want, got)
}
}
}
func TestRenderWritesCanonicalArtifactsOnly(t *testing.T) {
files, err := render(sampleReleases())
if err != nil {
t.Fatalf("render error = %v", err)
}
for _, path := range []string{
"docs/news/releases.json",
"docs/news/redirects.json",
} {
if _, ok := files[path]; !ok {
t.Fatalf("render did not produce %s (files: %v)", path, keys(files))
}
}
if len(files) != 2 {
t.Fatalf("render produced %d files, want 2: %v", len(files), keys(files))
}
}
func TestRenderRedirectsEveryRetiredComponentURL(t *testing.T) {
files, err := render(sampleReleases())
if err != nil {
t.Fatalf("render error = %v", err)
}
var table map[string]string
if err := json.Unmarshal(files[redirectsJSONPath], &table); err != nil {
t.Fatalf("redirect table does not decode: %v", err)
}
want := map[string]string{
"/news/archied/1.31.0/": "/news/1.31.0/",
"/news/archie/1.31.0/": "/news/1.31.0/",
"/news/archied/1.30.0/": "/news/1.30.0/",
"/news/archie/1.30.0/": "/news/1.30.0/",
}
if !reflect.DeepEqual(table, want) {
t.Fatalf("redirect table = %v, want %v", table, want)
}
}
func TestRenderIsDeterministic(t *testing.T) {
first, err := render(sampleReleases())
if err != nil {
t.Fatalf("first render error = %v", err)
}
second, err := render(sampleReleases())
if err != nil {
t.Fatalf("second render error = %v", err)
}
if !reflect.DeepEqual(first, second) {
t.Fatal("two renders of the same releases differ")
}
}
func TestRenderHandlesNoReleases(t *testing.T) {
files, err := render(nil)
if err != nil {
t.Fatalf("render error = %v", err)
}
if got := string(files[releasesJSONPath]); got != "[]\n" {
t.Fatalf("empty canonical JSON = %q, want %q", got, "[]\n")
}
if got := string(files[redirectsJSONPath]); got != "{}\n" {
t.Fatalf("empty redirect table = %q, want %q", got, "{}\n")
}
}
func keys(m map[string][]byte) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}
-165
View File
@@ -1,165 +0,0 @@
package main
import "testing"
// TestLintRejectsSessionBoundWriting covers each rule's triggering shape and a
// nearby sentence it must not fire on, so a pattern tightened later cannot
// quietly stop catching the thing it exists for.
func TestLintRejectsSessionBoundWriting(t *testing.T) {
for _, tc := range []struct {
name string
doc string
rule string
}{
{
name: "line citation",
doc: "The pin happens in `internal/daemon/daemon.go:1485`.",
rule: "line-citation",
},
{
name: "markdown line citation",
doc: "The rule is stated in `event-sources-and-reactions.md:61-63`.",
rule: "line-citation",
},
{
name: "self-referential line range",
doc: "See this document's Dedup section, lines 155-159.",
rule: "line-citation",
},
{
name: "dated status heading",
doc: "**Status 2026-09-05: resolved** per the decision below.",
rule: "dated-status",
},
{
name: "dated verification",
doc: "Verified directly, 2026-09-03: the interface has no send method.",
rule: "dated-status",
},
{
name: "date before the verb",
doc: "`event-sources-and-reactions.md` (2026-08-22, decided) ruled that",
rule: "dated-status",
},
{
name: "dated survey",
doc: "### Candidate comparison (surveyed 2026-09-03, pkg.go.dev)",
rule: "dated-status",
},
{
name: "dated settlement",
doc: "### The two decisions (settled 2026-09-19, decided by position)",
rule: "dated-status",
},
{
name: "progress claim",
doc: "The coordinator is not yet wired into production task intake.",
rule: "progress-claim",
},
{
name: "readiness claim",
doc: "Forge is ready to implement once the ledger lands.",
rule: "progress-claim",
},
{
name: "phase progress",
doc: "Phase 2 is complete and Phase 3 starts next.",
rule: "phase-progress",
},
{
name: "temporal hedge",
doc: "`[notify]` today is one webhook URL, read in one place.",
rule: "temporal-hedge",
},
{
name: "session artefact",
doc: "Grounded by a crew investigation pass.",
rule: "session-artefact",
},
} {
t.Run(tc.name, func(t *testing.T) {
findings := Lint("x.md", tc.doc)
if len(findings) == 0 {
t.Fatalf("Lint(%q) found nothing, want %s", tc.doc, tc.rule)
}
if findings[0].Rule != tc.rule {
t.Fatalf("rule = %q, want %q", findings[0].Rule, tc.rule)
}
})
}
}
// TestLintAcceptsDurableWriting: the rules target decay, not subject matter. A
// PRD may name a file, describe a phased plan, and carry its own status header.
func TestLintAcceptsDurableWriting(t *testing.T) {
for _, tc := range []struct{ name, doc string }{
{"file without a line", "The pin happens in `internal/daemon/daemon.go`, in `Daemon.resolveWorkflowID`."},
{"phases as design", "Phase 1 extracts the State Store. Phase 2 extracts the Gateway."},
{"status header field", "**Status:** Draft"},
{"date header field", "**Date:** 2026-09-03"},
{"blocked-on header field", "**Blocked on:** `archie-core-t2db.24`"},
{"a decision that names a date format", "Timestamps are stored as 2026-09-03 in the ledger."},
{"bead id as a pointer", "Resolves `archie-core-t2db.19`; supersedes the earlier shape."},
{"a dependency that exists is evidence", "`channels.Channel` already exists, so the position reuses it."},
} {
t.Run(tc.name, func(t *testing.T) {
if findings := Lint("x.md", tc.doc); len(findings) != 0 {
t.Fatalf("Lint(%q) = %v, want no findings", tc.doc, findings)
}
})
}
}
// TestLintRequiresACanonicalStatus: RULES.md gives three statuses, and a
// free-text one is where "Implemented (wiring landed)" hid a progress report.
func TestLintRequiresACanonicalStatus(t *testing.T) {
for _, tc := range []struct {
name string
doc string
want bool
}{
{"draft", "# T\n\n**Status:** Draft\n", false},
{"approved", "# T\n\n**Status:** Approved\n", false},
{"finalised", "# T\n\n**Status:** Finalised\n", false},
{"free text", "# T\n\n**Status:** Implemented (wiring landed)\n", true},
{"status with a changelog", "# T\n\n**Status:** Ratified (rev. 2e). Rev. 2e adds a lookup\n", true},
{"missing entirely", "# T\n\nBody.\n", true},
{"a nested document's indented status", "# T\n\n**Status:** Draft\n\n1. Item\n\n **Status:** Draft\n", true},
} {
t.Run(tc.name, func(t *testing.T) {
var got bool
for _, f := range LintDocument("x.md", tc.doc) {
if f.Rule == "status" {
got = true
}
}
if got != tc.want {
t.Fatalf("status finding = %v, want %v", got, tc.want)
}
})
}
}
// TestLintCatchesACitationSplitAcrossALineBreak: prose wraps, and a
// line-scoped rule saw "lines" and "155-159" as two innocent lines.
func TestLintCatchesACitationSplitAcrossALineBreak(t *testing.T) {
doc := "never swallowed as a log line (this document's Dedup section, lines\n155-159, the drop-and-report rule)."
var got bool
for _, f := range Lint("x.md", doc) {
if f.Rule == "line-citation" {
got = true
}
}
if !got {
t.Fatal("no line-citation finding for a citation split across a line break")
}
}
// TestLintSkipsFencedBlocks: a code listing may legitimately contain a line
// reference or a status string as the content being specified.
func TestLintSkipsFencedBlocks(t *testing.T) {
doc := "Before.\n\n```\ninternal/daemon/daemon.go:1485\n```\n\nAfter."
if findings := Lint("x.md", doc); len(findings) != 0 {
t.Fatalf("Lint = %v, want no findings inside a fence", findings)
}
}