fix(tools): stop testing on the text of other files, and ungate contractaudit

Six tests asserted on the wording and formatting of source and config files
rather than on behaviour: four injected text into fixtures and checked that a
regex noticed, and two asserted on api.jsx's contents. They break on an extra
space, a newline, a rename, or a comment that merely mentions the token -- the
single-fetch check had already false-positived on a comment, and I patched it
with a comment-stripper instead of deleting it. A test that cannot tell "the
code is wrong" from "the file is formatted differently" tests the wrong thing,
and the maintenance cost is permanent.

Deleted: tools/contractaudit/negative_test.go in full, and the source-scanning
"api.jsx holds exactly one fetch call" check with its stripComments helper. The
dashboard suite still asserts the browser mutation contract behaviourally, per
method, by inspecting the request each one makes -- which is where the real
defect was found. 142 UI tests pass; the 45 methods remain fully covered by the
two inventories and the completeness check.

The tool's own decoding is now testable without a file: parseDeclarations takes
an io.Reader, so its rules are exercised with in-memory input, and only the
absent-file branch still touches a path (which is never created).

contractaudit is no longer part of task check. Its surfaces are discovered by
scanning source text, so a rename or reformat elsewhere can change its output
with nothing actually wrong -- it reported 16 live routes as unconsumed once,
when the dashboard's request helper was renamed. A check that can fail for
reasons unrelated to what it measures must not be able to break a build. It now
matches tools/reachaudit: advisory, run by hand, --strict available on request.

Also removes five unused indirect requires from tools/go.mod (go mod tidy).
They were residue from the reflection-based first implementation of the RPC
scan, which was replaced by text scanning without tidying. -mod=readonly cannot
catch a superfluous require, so nothing would ever have found them.

Rewrites docs/prds/contract-conformance-audit.md, which claimed RPC coverage was
derived by reflection over the exported client type -- it never was -- listed
surface sizes of 43/12/52 against real counts of 45/21/49, described three
classification classes where the code has four, invented a five-surface Shape
with files that were never written, and blamed raw fetch calls for a 401 defect
that did not exist. Each false claim is now recorded in an errata section rather
than quietly dropped, and the document states plainly that the audit has found
nothing actionable: the 415 refusals and the duplicated client plumbing were
both found by reading the handler and reproducing the request.

Testing rule added to the document, since this is the second time: assert on the
observable effect, never on the content or formatting of generated or
hand-authored text and config files.
This commit is contained in:
sam committed 2026-09-15 14:17:53 +10:00
1 parent cb69cf1979
commit 6fd76ae550
10 files changed
+217 -592

No files matched your search

+16 -9
View File
@@ -127,25 +127,32 @@ func New(root, declPath string) (*Audit, error) {
}, nil
}
// parseDeclarations decodes the allowlist from r. Decoding is separate from
// reading the file so its rules can be exercised without authoring a file.
func parseDeclarations(r io.Reader) (Declarations, error) {
var declarations Declarations
if err := json.NewDecoder(r).Decode(&declarations); err != nil {
return Declarations{}, fmt.Errorf("parse declarations: %w", err)
}
if declarations.Surfaces == nil {
declarations.Surfaces = map[string]map[string]Declaration{}
}
return declarations, nil
}
// loadDeclarations reads the allowlist. A missing file is not an error: an
// empty allowlist is the correct starting state and makes every unconsumed
// subject an undeclared finding, which is the honest first report.
func loadDeclarations(path string) (Declarations, error) {
raw, err := os.ReadFile(path)
f, err := os.Open(path)
if os.IsNotExist(err) {
return Declarations{Surfaces: map[string]map[string]Declaration{}}, nil
}
if err != nil {
return Declarations{}, fmt.Errorf("read declarations: %w", err)
}
var declarations Declarations
if err := json.Unmarshal(raw, &declarations); err != nil {
return Declarations{}, fmt.Errorf("parse %s: %w", path, err)
}
if declarations.Surfaces == nil {
declarations.Surfaces = map[string]map[string]Declaration{}
}
return declarations, nil
defer f.Close()
return parseDeclarations(f)
}
// Run walks every surface and returns findings sorted by surface then subject.
+37 -13
View File
@@ -1,8 +1,8 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
@@ -84,7 +84,8 @@ func TestUndeclaredCountCountsOnlyFindings(t *testing.T) {
// 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.
// 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 {
@@ -95,15 +96,38 @@ func TestLoadDeclarationsMissingFileIsEmpty(t *testing.T) {
}
}
// TestLoadDeclarationsRejectsMalformed asserts a broken allowlist fails loudly
// rather than degrading to "no declarations", which would silently turn every
// declared entry into a finding nobody could clear.
func TestLoadDeclarationsRejectsMalformed(t *testing.T) {
path := filepath.Join(t.TempDir(), "bad.json")
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := loadDeclarations(path); err == nil {
t.Error("loadDeclarations(malformed) error = nil, want a parse failure")
}
// 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")
}
})
}
-336
View File
@@ -1,336 +0,0 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// fixture copies the repository subtrees the audit reads into a temporary
// directory, so a test can inject a violation without touching the working
// tree. The audit reads only these paths -- if a surface starts reading
// something else, a test here fails rather than silently auditing a fixture
// that no longer matches the real layout.
func fixture(t *testing.T) string {
t.Helper()
root := t.TempDir()
for _, dir := range []string{
"proto/state/v1",
"proto/gateway/v1",
"internal/infrastructure/staterpc",
"internal/infrastructure/gatewayrpc",
"internal/webui",
"ui/src",
} {
copyTree(t, filepath.Join("../..", dir), filepath.Join(root, dir))
}
return root
}
// copyTree copies a directory recursively. It must recurse: the dashboard's
// call sites live in nested feature folders (ui/src/base, ui/src/chat), so a
// flat copy yields a fixture with zero consumers and every negative test then
// passes for the wrong reason.
func copyTree(t *testing.T, src, dst string) {
t.Helper()
if err := os.MkdirAll(dst, 0o755); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(src)
if err != nil {
t.Fatalf("fixture: read %s: %v", src, err)
}
for _, entry := range entries {
from := filepath.Join(src, entry.Name())
to := filepath.Join(dst, entry.Name())
if entry.IsDir() {
copyTree(t, from, to)
continue
}
body, err := os.ReadFile(from)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(to, body, 0o644); err != nil {
t.Fatal(err)
}
}
}
func auditOf(t *testing.T, root string) []Finding {
t.Helper()
audit, err := New(root, "docs/contract-declarations.json")
if err != nil {
t.Fatalf("New: %v", err)
}
findings, err := audit.Run()
if err != nil {
t.Fatalf("Run: %v", err)
}
return findings
}
func find(findings []Finding, subject string) (Finding, bool) {
for _, f := range findings {
if f.Subject == subject {
return f, true
}
}
return Finding{}, false
}
// TestNegativeInjectedRouteIsReported proves the webui check catches a route
// nobody consumes. Without this the check is decoration: a gate that has never
// failed is a gate nobody can trust.
func TestNegativeInjectedRouteIsReported(t *testing.T) {
root := fixture(t)
// A new route with no consumer anywhere in ui/src.
serverPath := filepath.Join(root, "internal/webui/server.go")
body, err := os.ReadFile(serverPath)
if err != nil {
t.Fatal(err)
}
injected := strings.Replace(
string(body),
`mux.HandleFunc("GET /api/summary"`,
`mux.HandleFunc("GET /api/injected-orphan", s.handleSummary)
mux.HandleFunc("GET /api/summary"`,
1,
)
if injected == string(body) {
t.Fatal("could not inject the route; the registration shape changed")
}
if err := os.WriteFile(serverPath, []byte(injected), 0o644); err != nil {
t.Fatal(err)
}
finding, ok := find(auditOf(t, root), "GET /api/injected-orphan")
if !ok {
t.Fatal("injected unconsumed route was not reported")
}
if finding.Class != Undeclared {
t.Errorf("class = %q, want %q", finding.Class, Undeclared)
}
}
// TestNegativeRemovedConsumerIsReported proves the same check fails in the
// other direction: remove the dashboard's only call to a route and the route
// becomes an undeclared finding.
func TestNegativeRemovedConsumerIsReported(t *testing.T) {
root := fixture(t)
apiPath := filepath.Join(root, "ui/src/base/api.jsx")
body, err := os.ReadFile(apiPath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), "/api/summary") {
t.Fatal("fixture does not contain the expected consumer")
}
trimmed := strings.ReplaceAll(string(body), "/api/summary", "/api/renamed-by-test")
if err := os.WriteFile(apiPath, []byte(trimmed), 0o644); err != nil {
t.Fatal(err)
}
finding, ok := find(auditOf(t, root), "GET /api/summary")
if !ok {
t.Fatal("route whose consumer was removed was not reported")
}
if finding.Class != Undeclared {
t.Errorf("class = %q, want %q", finding.Class, Undeclared)
}
}
// TestNegativeInjectedRPCIsReported proves the proto check catches an RPC no
// adapter reaches.
func TestNegativeInjectedRPCIsReported(t *testing.T) {
root := fixture(t)
protoPath := filepath.Join(root, "proto/state/v1/state.proto")
body, err := os.ReadFile(protoPath)
if err != nil {
t.Fatal(err)
}
injected := strings.Replace(
string(body),
" rpc RegisterTaskGrant(",
" rpc InjectedOrphanRPC(InjectedOrphanRPCRequest) returns (InjectedOrphanRPCResponse);\n rpc RegisterTaskGrant(",
1,
)
if injected == string(body) {
t.Fatal("could not inject the rpc; the declaration shape changed")
}
if err := os.WriteFile(protoPath, []byte(injected), 0o644); err != nil {
t.Fatal(err)
}
finding, ok := find(auditOf(t, root), "StateStoreService/InjectedOrphanRPC")
if !ok {
t.Fatal("injected unconsumed RPC was not reported")
}
if finding.Class != Undeclared {
t.Errorf("class = %q, want %q", finding.Class, Undeclared)
}
}
// TestNegativeStaleDeclarationIsReported proves a declaration that outlived its
// subject fails. This is the direction people forget, and it is what stops an
// allowlist from quietly permitting something nobody checks.
func TestNegativeStaleDeclarationIsReported(t *testing.T) {
findings := classify("s", []Subject{
{Name: "Svc/NowConsumed", Consumed: true, Consumer: "internal/x/y.go:1"},
}, Declarations{Surfaces: map[string]map[string]Declaration{
"s": {"Svc/NowConsumed": {Reason: "was unconsumed", Tracker: "t"}},
}})
finding, ok := find(findings, "Svc/NowConsumed")
if !ok {
t.Fatal("stale declaration was not reported")
}
if finding.Class != Stale {
t.Errorf("class = %q, want %q", finding.Class, Stale)
}
}
// TestNegativeUnparsableCallShapeFailsLoudly proves the extractor refuses to
// under-report. A path built from a bare /api fragment must be an error, never
// a silently smaller consumer set.
func TestNegativeUnparsableCallShapeFailsLoudly(t *testing.T) {
body := `
const base = "/api";
const url = base + "/things";
`
_, err := scanFile("ui/src/base/exotic.jsx", body)
if err == nil {
t.Fatal("a path built from a bare /api fragment was accepted; the extractor would under-report")
}
if !strings.Contains(err.Error(), "would under-report") {
t.Errorf("error = %v, want the under-report explanation", err)
}
}
// TestNegativeCommentedOutCallIsStillReported is the anti-vacuity test at the
// surface level. Commenting out a real call leaves the path text in the file,
// so an extractor that credits any quoted path reports the route as healthy
// while nothing calls it -- a silent hole rather than a loud failure. The route
// must become an undeclared finding.
func TestNegativeCommentedOutCallIsStillReported(t *testing.T) {
root := fixture(t)
apiPath := filepath.Join(root, "ui/src/base/api.jsx")
body, err := os.ReadFile(apiPath)
if err != nil {
t.Fatal(err)
}
live := `summary: () => request("/api/summary"),`
if !strings.Contains(string(body), live) {
t.Fatal("fixture does not contain the expected live call; the client changed shape")
}
commented := strings.Replace(string(body), live, `// retired: () => request("/api/summary"),`, 1)
if err := os.WriteFile(apiPath, []byte(commented), 0o644); err != nil {
t.Fatal(err)
}
finding, ok := find(auditOf(t, root), "GET /api/summary")
if !ok {
t.Fatal("a route whose only remaining mention is a comment was not reported")
}
if finding.Class != Undeclared {
t.Errorf("class = %q, want %q: a comment cannot prove a route is reachable", finding.Class, Undeclared)
}
}
// TestScanFileCreditsAnyCallSignature pins the lesson from a real regression:
// the first version of this extractor matched the call by name (`req|fetch`),
// and rewriting the dashboard's helper from `req(` to `request(` silently
// reported 16 live routes as unconsumed. Extraction must key on the path
// literal as a call argument, not on the name of the function carrying it.
func TestScanFileCreditsAnyCallSignature(t *testing.T) {
cases := []struct {
name string
body string
want []string
}{
{
name: "the original helper name",
body: `const a = req("/api/summary");`,
want: []string{"/api/summary"},
},
{
name: "a renamed helper",
body: `const a = request("/api/summary");`,
want: []string{"/api/summary"},
},
{
name: "a name the extractor has never heard of",
body: `const a = someOtherTransport("/api/summary");`,
want: []string{"/api/summary"},
},
{
name: "an interpolated path in backticks",
body: "const a = request(`/api/tasks/${id}`);",
want: []string{"/api/tasks/${id}"},
},
{
name: "an EventSource subscription",
body: `const s = new EventSource("/events");`,
want: []string{"/events"},
},
{
name: "a path with a query string",
body: `const a = request("/api/logs" + qs(params));`,
want: []string{"/api/logs"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := scanFile("ui/src/base/client.jsx", tc.body)
if err != nil {
t.Fatalf("scanFile: %v", err)
}
if len(got) != len(tc.want) {
t.Fatalf("scanFile(%q) = %v, want %v", tc.body, got, tc.want)
}
for i := range tc.want {
if got[i] != tc.want[i] {
t.Errorf("scanFile(%q)[%d] = %q, want %q", tc.body, i, got[i], tc.want[i])
}
}
})
}
}
// TestScanFileIgnoresNonCallLiterals is the anti-vacuity half, and the more
// important one. Crediting any quoted path -- rather than a path passed to a
// call -- makes the whole surface pass on a file that issues no requests at
// all: a comment, a retired-route array, or a display label would each count as
// proof of consumption. That failure is silent, which makes it worse than a
// false finding.
func TestScanFileIgnoresNonCallLiterals(t *testing.T) {
cases := []struct {
name string
body string
}{
{"a constant that is never passed to anything", `const p = "/api/summary";`},
{"a comment quoting a path", `// the route "/api/summary" is dead`},
{"an array of retired paths", `const RETIRED = ["/api/summary", "/api/tasks"];`},
{"an object property", `const cfg = { path: "/api/summary" };`},
{"a template constant", "const p = `/api/summary`;"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := scanFile("ui/src/base/client.jsx", tc.body)
if err != nil {
t.Fatalf("scanFile: %v", err)
}
if len(got) != 0 {
t.Errorf(
"scanFile(%q) = %v, want no consumers: a literal that is not a call argument cannot prove a route is reachable",
tc.body, got,
)
}
})
}
}
+7 -8
View File
@@ -10,15 +10,14 @@ import (
)
// webUISurface reports HTTP route coverage for the dashboard API. The contract
// of record is the `registerXRoutes` call sites in internal/webui, and the
// consumers are the path literals the dashboard's client actually calls.
// of record is the route registrations in internal/webui, and the consumers are
// the path literals written under ui/src.
//
// This is the one surface with no schema at all: 52 routes and their response
// shapes are hand-matched against ui/src, so it is also the one that needs the
// check the most. The extractor fails loudly rather than under-reporting -- see
// scanFile -- because a call shape it cannot parse would otherwise make every
// route it feeds look unconsumed, and a false finding in a gate is worse than
// no gate.
// This surface has no schema at all, so the two lists are hand-matched and the
// matching is textual. It is advisory for that reason: a rename or a reformat
// elsewhere can change the result with nothing wrong, and it has already
// reported a batch of false "unconsumed" routes once when the dashboard's
// request helper was renamed. Do not gate a build on this.
type webUISurface struct {
root string
}
-5
View File
@@ -20,12 +20,7 @@ require (
github.com/samcharles93/ai-sdk v0.1.32 // indirect
github.com/traefik/yaegi v0.16.1 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.75.7 // indirect
modernc.org/mathutil v1.7.1 // indirect
-10
View File
@@ -38,23 +38,13 @@ go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=
go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 h1:5t+ZydAFj5kGVLrgCvLmpmCf9ylGRd64hpEronfRaws=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=