From e537447333c5dba10530c39b4316a6c55da29351 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 15 Sep 2026 09:41:20 +1000 Subject: [PATCH] feat(tools): add contractaudit for standing contract-conformance reporting Reachability (tools/reachaudit, epic archie-core-06ag) answers "is this code in a shipped binary?". It cannot answer the complementary question: "does every declared contract surface have a consumer, or a declaration that it has none?". ratelimit was in the binary closure and called by nothing, which reachability could not see. tools/contractaudit classifies each subject of each declared surface as CONSUMED, DECLARED-UNCONSUMED, UNDECLARED-UNCONSUMED, or STALE-DECLARATION, and only the last two are findings. The declaration allowlist must match reality exactly: a missing entry fails and so does an entry that outlived its subject, because a stale allowlist is how a gate quietly stops checking anything. Surfaces: the two gRPC services, whose consumption is derived by scanning adapter bodies for calls through the generated client, and the dashboard HTTP API, matched between the registerXRoutes call sites and the path literals the bundled client calls. Findings on the current tree, all deliberate and now declared: ListCaptures and ListUndispatchedCaptures are superseded by their streaming variants -- staterpc's client calls StreamCaptures -- so no production client reaches the unary RPCs. Three bugs this tool found in itself, each recorded because each is the class of error that makes a conformance check worse than none: - Joining RPCs to adapter methods by name silently reported live RPCs as unconsumed, because adapters do not map one-to-one: StoreClient.Get calls GetSession, List calls ListSessions. - Reflecting over the client value rather than the pointer reported zero methods, hence the whole surface unconsumed. - Treating the asset mount and the health probes as dashboard API routes reported four healthy routes as undeclared; they have different consumers and are out of scope for this surface. The consumer extractor fails loudly on a call shape it cannot parse rather than under-reporting, and every check is negative-tested: a route, an RPC, and a removed consumer are each injected, confirmed to fail for the right reason, and reverted. The declaration staleness rule is tested too. Advisory when run directly; task check runs it -strict. See docs/prds/contract-conformance-audit.md. --- Taskfile.yml | 24 +- docs/contract-declarations.json | 38 ++++ docs/prds/contract-conformance-audit.md | 158 +++++++++++++ tools/contractaudit/audit.go | 288 ++++++++++++++++++++++++ tools/contractaudit/audit_test.go | 109 +++++++++ tools/contractaudit/main.go | 63 ++++++ tools/contractaudit/negative_test.go | 214 ++++++++++++++++++ tools/contractaudit/proto.go | 145 ++++++++++++ tools/contractaudit/webui.go | 235 +++++++++++++++++++ tools/go.mod | 5 + tools/go.sum | 10 + 11 files changed, 1288 insertions(+), 1 deletion(-) create mode 100644 docs/contract-declarations.json create mode 100644 docs/prds/contract-conformance-audit.md create mode 100644 tools/contractaudit/audit.go create mode 100644 tools/contractaudit/audit_test.go create mode 100644 tools/contractaudit/main.go create mode 100644 tools/contractaudit/negative_test.go create mode 100644 tools/contractaudit/proto.go create mode 100644 tools/contractaudit/webui.go diff --git a/Taskfile.yml b/Taskfile.yml index 6a929cf8a..e609b035a 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -221,7 +221,7 @@ tasks: - go -C tools test -mod=readonly ./... -count=1 check: - desc: "Full quality gate: fmt, go fix, proto, vet, lint, build, test, tools tests, ui tests" + desc: "Full quality gate: fmt, go fix, proto, vet, lint, build, test, tools tests, ui tests, contract" cmds: - task: fmt - go fix ./... @@ -238,6 +238,28 @@ tasks: # The dashboard's suite runs here too. Left out of the gate it rots # silently: nothing else executes it, so a broken DOM primitive ships. - task: test:ui + # Contract conformance. Static and dependency-light, so it belongs with + # the per-edit checks rather than next to the end-to-end suite. It runs + # -strict here: every unconsumed surface must be declared in + # docs/contract-declarations.json with a reason and a tracker, and a + # stale declaration fails the same way an undeclared one does. + - task: contract + + contract: + desc: "Report contract conformance: declared surfaces, their consumers, and the drift between them" + summary: | + Walks every declared contract surface -- the two gRPC services, the + dashboard HTTP API -- and classifies each subject as consumed, + declared-unconsumed, undeclared, or a stale declaration. + + Advisory when run directly; `task check` runs it with -strict so an + undeclared or stale entry fails the gate. Declare an intentionally + unconsumed surface in docs/contract-declarations.json with a reason + that states the consequence and the tracker that owns the work. + + See docs/prds/contract-conformance-audit.md. + cmds: + - go -C tools run ./contractaudit --repo-root .. --strict release:preview: desc: "Show the release notes that would be generated (VERSION=1.2.0, or GATEWAY=/RUNTIME= to version the two components separately)" diff --git a/docs/contract-declarations.json b/docs/contract-declarations.json new file mode 100644 index 000000000..f5596bec5 --- /dev/null +++ b/docs/contract-declarations.json @@ -0,0 +1,38 @@ +{ + "$comment": [ + "Contract-conformance declarations. Every entry here is a declared-unconsumed", + "surface: a capability that exists, that no client reaches, and that is", + "deliberately left that way. It must match reality exactly -- a missing entry", + "is an undeclared finding and an entry that is no longer true is a stale one,", + "and both fail a -strict run. See docs/prds/contract-conformance-audit.md.", + "", + "Managed by tools/contractaudit. Reasons state the consequence, not 'TODO':", + "this file is the only place the debt is legible." + ], + "surfaces": { + "proto/state/v1/state.proto": { + "StateStoreService/ListCaptures": { + "reason": "Superseded by StreamCaptures. The remote adapter's ListCaptures method (staterpc/client.go) calls StreamCaptures, not this unary RPC, so no production client reaches it. The server keeps it implemented as a compatibility surface for callers of the raw proto.", + "tracker": "archie-core-8cda.4" + }, + "StateStoreService/ListUndispatchedCaptures": { + "reason": "Superseded by StreamUndispatchedCaptures, on the same terms as ListCaptures: the remote adapter's ListUndispatchedCaptures calls the streaming variant, leaving this unary RPC reachable only through the raw proto.", + "tracker": "archie-core-8cda.4" + } + } + }, + "blindSpots": [ + { + "surface": "internal/webui", + "reason": "Consumer extraction is textual over ui/src. A path assembled by string concatenation rather than written as a literal is invisible; scanFile fails loudly when a call shape it cannot parse appears, but it cannot see a path that is never a literal. Routes whose consumer is outside the dashboard (the asset mount, the health probes, the capture-intake webhook) are excluded from this surface by design: they have different consumers and are not part of the dashboard API contract." + }, + { + "surface": "proto/state/v1/state.proto", + "reason": "Consumption is derived by scanning adapter bodies for calls through the generated client. An RPC reached only through runtime-loaded code (Yaegi) or reflection would read as unconsumed. No such path exists today." + }, + { + "surface": "proto/gateway/v1/chat.proto", + "reason": "As above. Note that gatewayrpc is served by archie-gateway and consumed by archied and archie-ui; a consumer living outside this repository would be invisible here." + } + ] +} diff --git a/docs/prds/contract-conformance-audit.md b/docs/prds/contract-conformance-audit.md new file mode 100644 index 000000000..de9e08c52 --- /dev/null +++ b/docs/prds/contract-conformance-audit.md @@ -0,0 +1,158 @@ +# Contract conformance audit — decision + +**Status:** Decided, implementing +**Date:** 2026-09-15 +**Authority:** sibling to `archie-core-06ag` (standing reachability audit) and +`docs/architecture/dependencies-and-contracts.md`. Does not replace either. +**Extends:** `docs/architecture/generated-documentation.md` (the `docsgen check` +gap it admits at line 331), `docs/prds/config-example-drift.md` (step 3). + +## Question + +Archie has strong contract enforcement at exactly one boundary and none at the +rest. `proto/*.proto` is generated, linted against `main`, and regenerated in +`task check`; `proto:check` fails on any drift. The **application** boundary — +where the dashboard, the generated documentation, and the shipped asset bundle +meet their consumers — has no equivalent, and three separate documents already +admit drift there in writing. + +Should contract conformance be a standing, runnable audit like `reachaudit`? + +## Decision + +**Yes, and it is a sibling of reachability, not a replacement.** Reachability asks +*"is this code in a shipped binary?"*. Conformance asks the complementary +question: *"does every declared contract surface have a consumer, or an explicit +declaration that it has none?"* A capability can be reachable and unconsumed — +`ratelimit` was in the binary closure and called by nothing +(`archie-core-6wxb`). Reachability would not have found that; this would. + +The audit reports three classifications, and **the third is the only finding**: + +| Classification | Meaning | Action | +| --- | --- | --- | +| `CONSUMED` | a non-test client call site exercises it | none | +| `DECLARED-UNCONSUMED` | named in the declaration file with a reason and a tracker id | none — it is tracked work | +| `UNDECLARED-UNCONSUMED` | nobody reaches it and nobody declared it | **the finding** | + +`DECLARED-UNCONSUMED` is a status, not a defect — the same posture `reachaudit` +takes with `unreachable-tracked`. The declaration file is an allowlist that +**must match reality exactly**: an entry naming a surface that is now consumed is +itself a failure (stale declaration), because a stale allowlist is how a gate +quietly stops checking anything. + +### Surfaces, and what proves each is consumed + +| Surface | Contract of record | Consumed means | +| --- | --- | --- | +| `proto/state/v1` `StateStoreService` (43 RPCs) | the `.proto` | an exported method on `staterpc.Client` whose body calls that RPC | +| `proto/gateway/v1` `ChatService` (12 RPCs) | the `.proto` | an exported method on `gatewayrpc.Client` calling that RPC | +| `internal/webui` HTTP routes (52) | the `registerX` call sites | a path literal in `ui/src/base/api.jsx` or an `EventSource` subscriber | +| `docs/data/generated/contracts.json` | `tools/docsgen` | a committed-artifact comparison (`docsgen check`) | +| `ui/dist` | `ui/src` | a rebuild that produces no diff | + +RPC coverage is derived by **reflection over the exported client type**, not by +parsing call sites. If a method exists, the generated `grpc` interface already +forced it to make a real RPC call, so presence of the method *is* the proof of +consumption. This keeps the check exact without a call-graph. + +## The two gaps this closes immediately + +Both are already admitted in writing; neither is implemented. + +**1. `docsgen check` is documented and does not exist.** +`generated-documentation.md:118-121` advertises `docsgen data|asyncapi|all|check` +and line 336 gives the invocation `go -C tools run ./docsgen check --repo-root ..`. +`tools/docsgen/main.go` defines exactly two flags, `--repo-root` and `--out`, and +`run()` unconditionally writes. Line 331 admits "`task check` does not run +`docs:check`, so generated drift is currently ungated" — and it cannot, because +there is no `check` mode and no `docs:*` task to run. + +**2. The dashboard's client is not centralised, and its own comments say it is.** +`ui/src/base/api.jsx` opens with "Single place that knows how to talk to archied. +Every feature folder goes through this, so auth handling and error shape live in +one file." **22 of its 39 calls use a raw `fetch()` that bypasses its own `req()` +wrapper**, and `ui/src/chat/chat.jsx:406` calls `fetch("/api/chat/stream")` from +outside `api.jsx` entirely. The consequence is concrete, not stylistic: `req()` +is the only place that maps `401` to `ApiError("unauthorised", 401)`, which +`classifyActionError` turns into `session-expired`. Every raw-`fetch` path +therefore reports an expired session as a generic `refused`/`broken` failure — +which is the exact defect `archie-core-1786637490536-29-f1dab2c4` ("Make dashboard +authentication and connectivity failures actionable") exists to fix. + +This is the check the audit's own harness must survive: it asserts the +centralisation claim, and today it fails. + +## Shape + +```text +tools/contractaudit/ + main.go # flag parsing, report rendering (advisory by default) + surface.go # Surface interface: Name() + Findings() []Finding + proto.go # RPC coverage by reflection over the exported client types + webui.go # route registration vs ui/src call sites + generated.go # docsgen check-mode comparison + declarations.go # the allowlist, with exact-match staleness + testdata/ # negative-test fixtures +docs/contract-declarations.json # DECLARED-UNCONSUMED allowlist +``` + +Finding shape, stable because tests and the report both consume it: + +```go +type Finding struct { + Surface string // "proto/state/v1" + Subject string // "StateStoreService/TokensByDay" + Class string // CONSUMED | DECLARED-UNCONSUMED | UNDECLARED-UNCONSUMED + Evidence string // file:line, or the reason string + Tracker string // bead id for DECLARED entries, empty otherwise +} +``` + +Advisory is the default: findings print, exit status is 0. `--strict` (and +`task contract` in the gate, once the initial findings are triaged) fails on any +`UNDECLARED-UNCONSUMED` or stale declaration. + +## Blind spots, labelled rather than omitted + +Following `reachaudit`'s rule that Yaegi/reflection packages are "labelled, never +presented as dead": + +- **Runtime-loaded code** (Yaegi, reflection) — a route or RPC reached only + through dynamic dispatch reads as unconsumed. Labelled with the package list. +- **JSX call-site extraction is textual.** It matches path literals in + `ui/src/**`, so a path built by string concatenation is invisible. The + extractor must **fail loudly on an unexpected call shape** rather than + under-report — under-reporting is the failure mode that makes a gate worse than + no gate. +- **An `EventSource` subscription is a consumer.** `/events` and + `/api/logs/stream` are consumed via `EventSource`, not `fetch`; an extractor + that only looks for `fetch` reports them unconsumed and is simply wrong. + +## Acceptance + +1. `go -C tools run ./contractaudit` runs on demand and prints a report; exit 0. +2. Every unconsumed surface appears with a classification and, where declared, a + reason and tracker id. +3. The declaration file fails on a **new** undeclared entry *and* on a **stale** + entry that is no longer true. +4. Blind spots are labelled in the report, never silently counted as findings. +5. Findings are advisory; nothing is deleted or rewritten by this tool. +6. `docsgen check` exists and `task check` runs it, so committed generated data + cannot drift. +7. **Each check is negative-tested**: a violation is injected, the check is + confirmed to fail for the right reason, and the injection is reverted. A check + that has never failed is not a check. + +## Non-goals + +- No runtime schema validation of HTTP responses. The webui handlers already + return non-nil slices on every empty path (`[]SkillView{}`, `[]CuratorView{}`, + `make([]taskView, len(tasks))`), so the nil-slice class does not currently + apply; adding a live-stack validator before it has a defect to find is + scaffolding, not a gate. Recorded as deferred, not rejected. +- No re-parse of the proto as a second source of truth. The generated Go types + are the contract; `buf lint`/`buf breaking` already own the `.proto`. +- No generation of `config.example.toml` or `deployments/*.toml` — settled + against in `config-example-drift.md`. +- No change to `tools/reachaudit`'s scope or report shape. diff --git a/tools/contractaudit/audit.go b/tools/contractaudit/audit.go new file mode 100644 index 000000000..6785a6188 --- /dev/null +++ b/tools/contractaudit/audit.go @@ -0,0 +1,288 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" +) + +// Class is a finding's conformance classification. Only Undeclared and Stale +// are findings; the other two are healthy states that are still reported so a +// reader can see the surface was actually walked rather than skipped. +type Class string + +const ( + // Consumed: a non-test client call site exercises the subject. + Consumed Class = "CONSUMED" + // DeclaredUnconsumed: named in the declaration allowlist with a reason and + // a tracker id. This is a status, not a defect -- tracked work whose only + // property is that its completion state was not visible anywhere. + DeclaredUnconsumed Class = "DECLARED-UNCONSUMED" + // Undeclared: nobody reaches the subject and nobody declared it. The finding. + Undeclared Class = "UNDECLARED-UNCONSUMED" + // Stale: a declaration naming a subject that is now consumed, or that no + // longer exists on the surface. A stale allowlist is how a gate quietly + // stops checking anything, so it fails like an undeclared entry. + Stale Class = "STALE-DECLARATION" +) + +// Finding is one surface subject's conformance state. The shape is consumed by +// the text and JSON renderers and by the tests, so it is stable. +type Finding struct { + Surface string `json:"surface"` + Subject string `json:"subject"` + Class Class `json:"class"` + Evidence string `json:"evidence,omitempty"` + Tracker string `json:"tracker,omitempty"` +} + +// Declaration is one allowlisted unconsumed subject. +type Declaration struct { + // Reason states the consequence, not "TODO". This file is the only place + // the debt is legible. + Reason string `json:"reason"` + // Tracker is the bead id or issue URL that owns the work. + Tracker string `json:"tracker,omitempty"` +} + +// Declarations is the allowlist, keyed by surface name then subject. It must +// match reality exactly: a missing entry is an undeclared finding and an entry +// that is no longer true is a stale one. +type Declarations struct { + // Surfaces maps a surface name (e.g. "proto/state/v1") to its declared + // unconsumed subjects. + Surfaces map[string]map[string]Declaration `json:"surfaces"` + // BlindSpots names the checks that cannot be exact, with the reason. These + // are printed as-is and are never counted as findings -- the reachaudit + // rule that a static-analysis blind spot is labelled, not presented as dead. + BlindSpots []BlindSpot `json:"blindSpots,omitempty"` +} + +// BlindSpot is a check limitation reported rather than silently applied. +type BlindSpot struct { + Surface string `json:"surface"` + Reason string `json:"reason"` +} + +// Subject is one addressable element of a surface: an RPC, an HTTP route, a +// generated artifact. +type Subject struct { + // Name is the stable identity, e.g. "StateStoreService/TokensByDay" or + // "GET /api/summary". + Name string + // Evidence is where the subject is declared, as file:line where known. + Evidence string + // Consumed reports whether a client reaches it. + Consumed bool + // Consumer is the consuming call site, for the report. + Consumer string +} + +// Surface is one declared contract surface and the subjects it exposes. +type Surface interface { + // Name is the surface's stable identifier, matching the declaration file. + Name() string + // Subjects enumerates the surface's declared subjects and their + // consumption state. + Subjects() ([]Subject, error) +} + +// Audit walks every surface and classifies each subject against the +// declaration allowlist. +type Audit struct { + root string + declPath string + declarations Declarations + surfaces []Surface +} + +// New builds an audit over the repository at root, reading the declaration +// allowlist from declPath (relative to root). +func New(root, declPath string) (*Audit, error) { + absRoot, err := filepath.Abs(root) + if err != nil { + return nil, fmt.Errorf("resolve repository root: %w", err) + } + absDecl := declPath + if !filepath.IsAbs(absDecl) { + absDecl = filepath.Join(absRoot, declPath) + } + declarations, err := loadDeclarations(absDecl) + if err != nil { + return nil, err + } + return &Audit{ + root: absRoot, + declPath: absDecl, + declarations: declarations, + surfaces: []Surface{ + newStateStoreSurface(absRoot), + newGatewayChatSurface(absRoot), + newWebUISurface(absRoot), + }, + }, 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) + 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 +} + +// Run walks every surface and returns findings sorted by surface then subject. +func (a *Audit) Run() ([]Finding, error) { + var findings []Finding + for _, surface := range a.surfaces { + subjects, err := surface.Subjects() + if err != nil { + return nil, fmt.Errorf("surface %s: %w", surface.Name(), err) + } + findings = append(findings, classify(surface.Name(), subjects, a.declarations)...) + } + sort.Slice(findings, func(i, j int) bool { + if findings[i].Surface != findings[j].Surface { + return findings[i].Surface < findings[j].Surface + } + return findings[i].Subject < findings[j].Subject + }) + return findings, nil +} + +// classify applies the three-state rule, then the staleness rule in the +// opposite direction: every declaration must name a subject that still exists +// and is still unconsumed. +func classify(surface string, subjects []Subject, declarations Declarations) []Finding { + declared := declarations.Surfaces[surface] + findings := make([]Finding, 0, len(subjects)+len(declared)) + seen := make(map[string]bool, len(subjects)) + + for _, subject := range subjects { + seen[subject.Name] = true + declaration, isDeclared := declared[subject.Name] + switch { + case subject.Consumed && isDeclared: + // The declaration outlived its subject's unconsumed state. + findings = append(findings, Finding{ + Surface: surface, + Subject: subject.Name, + Class: Stale, + Evidence: fmt.Sprintf("declared unconsumed but consumed by %s", subject.Consumer), + Tracker: declaration.Tracker, + }) + case subject.Consumed: + findings = append(findings, Finding{ + Surface: surface, + Subject: subject.Name, + Class: Consumed, + Evidence: subject.Consumer, + }) + case isDeclared: + findings = append(findings, Finding{ + Surface: surface, + Subject: subject.Name, + Class: DeclaredUnconsumed, + Evidence: declaration.Reason, + Tracker: declaration.Tracker, + }) + default: + findings = append(findings, Finding{ + Surface: surface, + Subject: subject.Name, + Class: Undeclared, + Evidence: subject.Evidence, + }) + } + } + + // A declaration for a subject the surface no longer exposes is stale too: + // the allowlist is now permitting something that does not exist, which is + // indistinguishable from permitting something nobody checked. + for name, declaration := range declared { + if seen[name] { + continue + } + findings = append(findings, Finding{ + Surface: surface, + Subject: name, + Class: Stale, + Evidence: "declared, but the surface no longer exposes this subject", + Tracker: declaration.Tracker, + }) + } + return findings +} + +// UndeclaredCount is the number of findings that should fail a strict run. +func UndeclaredCount(findings []Finding) int { + n := 0 + for _, finding := range findings { + if finding.Class == Undeclared || finding.Class == Stale { + n++ + } + } + return n +} + +func writeJSON(out io.Writer, findings []Finding) error { + encoder := json.NewEncoder(out) + encoder.SetIndent("", " ") + return encoder.Encode(findings) +} + +func writeText(out io.Writer, findings []Finding) { + bySurface := map[string][]Finding{} + var order []string + for _, finding := range findings { + if _, ok := bySurface[finding.Surface]; !ok { + order = append(order, finding.Surface) + } + bySurface[finding.Surface] = append(bySurface[finding.Surface], finding) + } + sort.Strings(order) + for _, surface := range order { + group := bySurface[surface] + counts := map[Class]int{} + for _, finding := range group { + counts[finding.Class]++ + } + fmt.Fprintf(out, "\n%s (%s %d, %s %d, %s %d, %s %d)\n", + surface, + Consumed, counts[Consumed], + DeclaredUnconsumed, counts[DeclaredUnconsumed], + Undeclared, counts[Undeclared], + Stale, counts[Stale], + ) + for _, finding := range group { + if finding.Class == Consumed { + continue + } + line := fmt.Sprintf(" %-22s %s", finding.Class, finding.Subject) + if finding.Tracker != "" { + line += " [" + finding.Tracker + "]" + } + fmt.Fprintln(out, line) + if finding.Evidence != "" { + fmt.Fprintf(out, " %s\n", strings.TrimSpace(finding.Evidence)) + } + } + } +} diff --git a/tools/contractaudit/audit_test.go b/tools/contractaudit/audit_test.go new file mode 100644 index 000000000..fc8d04e07 --- /dev/null +++ b/tools/contractaudit/audit_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "os" + "path/filepath" + "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. +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) + } +} + +// 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") + } +} diff --git a/tools/contractaudit/main.go b/tools/contractaudit/main.go new file mode 100644 index 000000000..6e85ec069 --- /dev/null +++ b/tools/contractaudit/main.go @@ -0,0 +1,63 @@ +// Command contractaudit reports contract-conformance state across Archie's +// declared surfaces: which capabilities have a consumer, which have an +// explicit declaration that they do not, and which have neither. +// +// It is the sibling of tools/reachaudit. Reachability asks "is this code in a +// shipped binary?"; conformance asks "does every declared surface have a +// consumer, or a declaration that it has none?". A capability can be reachable +// and unconsumed -- ratelimit was in the binary closure and called by nothing +// (archie-core-6wxb) -- which reachability cannot see and this can. +// +// Advisory by default: it prints, it never deletes or rewrites anything. Pass +// -strict to fail on an undeclared or stale entry. +// +// See docs/prds/contract-conformance-audit.md. +package main + +import ( + "flag" + "fmt" + "log" + "os" +) + +func main() { + repoRoot := flag.String("repo-root", "..", "path to the Archie repository root") + declPath := flag.String( + "declarations", + "docs/contract-declarations.json", + "declaration allowlist, relative to the repository root", + ) + strict := flag.Bool("strict", false, "fail on undeclared or stale entries") + jsonOut := flag.Bool("json", false, "emit the report as JSON instead of text") + flag.Parse() + + if err := run(*repoRoot, *declPath, *strict, *jsonOut, os.Stdout); err != nil { + log.Fatalf("contractaudit: %v", err) + } +} + +func run(repoRoot, declPath string, strict, jsonOut bool, out *os.File) error { + audit, err := New(repoRoot, declPath) + if err != nil { + return err + } + findings, err := audit.Run() + if err != nil { + return err + } + if jsonOut { + if err := writeJSON(out, findings); err != nil { + return err + } + } else { + writeText(out, findings) + } + if strict && UndeclaredCount(findings) > 0 { + return fmt.Errorf( + "%d undeclared or stale contract entries; declare them in %s or consume them", + UndeclaredCount(findings), declPath, + ) + } + return nil +} diff --git a/tools/contractaudit/negative_test.go b/tools/contractaudit/negative_test.go new file mode 100644 index 000000000..a9d6c9c86 --- /dev/null +++ b/tools/contractaudit/negative_test.go @@ -0,0 +1,214 @@ +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 call shape it cannot parse must be an error, never a +// silently smaller consumer set -- under-reporting is how a gate stops +// checking without anyone noticing. +func TestNegativeUnparsableCallShapeFailsLoudly(t *testing.T) { + body := ` +export const api = { + exotic: (p) => fetch(buildPath("/api/things"), { method: "GET" }), +}; +` + _, err := scanFile("ui/src/base/exotic.jsx", body) + if err == nil { + t.Fatal("unparsable call shape 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) + } +} diff --git a/tools/contractaudit/proto.go b/tools/contractaudit/proto.go new file mode 100644 index 000000000..83c84466f --- /dev/null +++ b/tools/contractaudit/proto.go @@ -0,0 +1,145 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" +) + +// protoSurface reports RPC coverage for one gRPC service. +// +// Consumption is established by scanning the adapter package for calls through +// the generated client, e.g. `c.client.ListSessions(...)`. The method-name +// lookup an earlier version used was wrong in a way worth recording: the +// adapters do not rename RPCs one-to-one. `StoreClient.Get` calls GetSession, +// `StoreClient.List` calls ListSessions, `StoreClient.GetByChannel` calls +// GetSessionsByChannel -- so a name-based join silently reports live RPCs as +// unconsumed, which is exactly the false finding a gate must never produce. +// +// Scanning bodies also catches every adapter in the package rather than only +// the one type the caller passes, so a second adapter added later is covered +// without changing this file. +type protoSurface struct { + root string + protoPath string + adapter string +} + +func newStateStoreSurface(root string) Surface { + return &protoSurface{ + root: root, + protoPath: "proto/state/v1/state.proto", + adapter: "internal/infrastructure/staterpc", + } +} + +func newGatewayChatSurface(root string) Surface { + return &protoSurface{ + root: root, + protoPath: "proto/gateway/v1/chat.proto", + adapter: "internal/infrastructure/gatewayrpc", + } +} + +// Name is the proto path itself, so a declaration entry names the exact file +// whose RPCs it is talking about and cannot be confused with another surface. +func (s *protoSurface) Name() string { return s.protoPath } + +var ( + rpcPattern = regexp.MustCompile(`(?m)^\s*rpc\s+([A-Za-z0-9_]+)\s*\(`) + servicePattern = regexp.MustCompile(`(?m)^\s*service\s+([A-Za-z0-9_]+)\s*\{`) + // A call through the generated client: `c.client.ListSessions(`. The + // receiver is whatever the adapter names its field, so match any selector + // that ends in a generated-client call rather than a fixed receiver name. + clientCallPattern = regexp.MustCompile(`\bclient\.([A-Z][A-Za-z0-9_]*)\(`) + // The enclosing method, used to attribute the call in the report. + methodPattern = regexp.MustCompile(`(?m)^func \([^)]*\)\s+([A-Z][A-Za-z0-9_]*)\s*\(`) +) + +func (s *protoSurface) Subjects() ([]Subject, error) { + raw, err := os.ReadFile(filepath.Join(s.root, s.protoPath)) + if err != nil { + return nil, fmt.Errorf("read proto: %w", err) + } + service := servicePattern.FindSubmatch(raw) + if service == nil { + return nil, fmt.Errorf("%s declares no service; the parser is stale", s.protoPath) + } + serviceName := string(service[1]) + + rpcs := rpcPattern.FindAllSubmatch(raw, -1) + if len(rpcs) == 0 { + return nil, fmt.Errorf("%s declares no rpc; refusing to report an empty surface", s.protoPath) + } + + consumers, err := s.adapterCallSites() + if err != nil { + return nil, err + } + + subjects := make([]Subject, 0, len(rpcs)) + for _, match := range rpcs { + name := string(match[1]) + subject := Subject{ + Name: serviceName + "/" + name, + Evidence: s.protoPath, + } + if site, ok := consumers[name]; ok { + subject.Consumed = true + subject.Consumer = site + } + subjects = append(subjects, subject) + } + return subjects, nil +} + +// adapterCallSites maps an RPC name to the adapter method that calls it. The +// generated request/response build helpers are counted too, because a stream +// RPC is reached through one. +func (s *protoSurface) adapterCallSites() (map[string]string, error) { + adapterDir := filepath.Join(s.root, s.adapter) + entries, err := os.ReadDir(adapterDir) + if err != nil { + return nil, fmt.Errorf("read adapter package: %w", err) + } + sites := map[string]string{} + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") { + continue + } + // _test.go files prove an adapter works, not that production reaches + // it. server.go is the serving side, which is the surface being + // consumed, not a consumer of it. + if strings.HasSuffix(name, "_test.go") || name == "server.go" { + continue + } + body, err := os.ReadFile(filepath.Join(adapterDir, name)) + if err != nil { + return nil, fmt.Errorf("read adapter file: %w", err) + } + rel := filepath.Join(s.adapter, name) + + // Walk the file linearly so each client call is attributed to the + // method that encloses it. methods is position-ordered, so the last + // entry starting before the call is the enclosing one. + methods := methodPattern.FindAllStringSubmatchIndex(string(body), -1) + for _, call := range clientCallPattern.FindAllStringSubmatchIndex(string(body), -1) { + rpcName := string(body[call[2]:call[3]]) + enclosing := "" + for _, method := range methods { + if method[0] < call[0] { + enclosing = string(body[method[2]:method[3]]) + continue + } + break + } + if _, exists := sites[rpcName]; !exists { + sites[rpcName] = fmt.Sprintf("%s (%s.%s)", rel, filepath.Base(s.adapter), enclosing) + } + } + } + return sites, nil +} diff --git a/tools/contractaudit/webui.go b/tools/contractaudit/webui.go new file mode 100644 index 000000000..998a9cdda --- /dev/null +++ b/tools/contractaudit/webui.go @@ -0,0 +1,235 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" +) + +// 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. +// +// 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. +type webUISurface struct { + root string +} + +func newWebUISurface(root string) Surface { return &webUISurface{root: root} } + +func (s *webUISurface) Name() string { return "internal/webui" } + +// routePattern matches a route registration in internal/webui. Every route is +// registered as HandleFunc("METHOD /path", handler). +var routePattern = regexp.MustCompile(`(?:HandleFunc|Handle)\(\s*"([A-Z]+)\s+(/[^"]*)"`) + +// routeLiteralPattern finds a const holding a non-literal route, so a route +// built from a constant is still seen. Without this, captureIntakeRoute would +// read as an unconsumed route when it is in fact a mounted one. +var routeLiteralPattern = regexp.MustCompile(`(?m)^\s*(?:const\s+)?([A-Za-z0-9_]+)\s*=\s*"([A-Z]+)\s+(/[^"]*)"`) + +// Consumer call shapes. Go's regexp has no backreferences, so each quoting +// style gets its own alternative rather than a backreference pair. +// +// EventSource counts as a consumer: /events and /api/logs/stream are +// subscribed to, not fetched, and an extractor that only looks for fetch +// reports them unconsumed and is simply wrong. +var ( + fetchPathPatterns = []*regexp.Regexp{ + regexp.MustCompile(`(?:req|fetch)\(\s*"([^"]+)"`), + regexp.MustCompile("(?:req|fetch)\\(\\s*`([^`]+)`"), + } + eventPathPatterns = []*regexp.Regexp{ + regexp.MustCompile(`new\s+EventSource\(\s*"([^"]+)"`), + regexp.MustCompile("new\\s+EventSource\\(\\s*`([^`]+)`"), + } + // A bare path literal, so a call routed through a helper this extractor + // does not know about is still credited. + pathLiteralPattern = regexp.MustCompile(`"(/[a-zA-Z0-9_./{}:-]*)"`) + + // Every fetch/req/EventSource call's opening, captured with its first + // argument, so the extractor can require that argument to be a literal + // rather than hoping a shape it does not recognise never appears. + callOpenPattern = regexp.MustCompile(`\b(?:req|fetch|new\s+EventSource)\s*\(\s*([^\s)\n]{0,80})`) + // A declaration, not a call: `async function req(path) {`. + declPattern = regexp.MustCompile(`\bfunction\s+(?:req|fetch)\s*\(`) + // The wrapper delegating on a variable: `fetch(path, {`. This carries no + // path by construction, so it is not an under-report. + delegatePattern = regexp.MustCompile(`\b(?:req|fetch)\s*\(\s*[a-z][A-Za-z0-9_]*\s*[,)]`) + // The first argument opening with a quote, which is what makes it a + // literal path this extractor must have extracted. + literalArgOnly = regexp.MustCompile("^[\"`]") + // An EventSource subscription built from a variable is skipped for the + // same reason as the wrapper delegation above. + + tmpPattern = regexp.MustCompile(`\$\{[^}]*\}`) + routeParamPat = regexp.MustCompile(`\{[^}]+\}`) + apiPathPrefix = "/api/" + eventStreamRoute = "/events" +) + +func (s *webUISurface) Subjects() ([]Subject, error) { + serverPath := filepath.Join(s.root, "internal/webui/server.go") + raw, err := os.ReadFile(serverPath) + if err != nil { + return nil, fmt.Errorf("read webui routes: %w", err) + } + serverSource := string(raw) + + // Resolve route constants before scanning registrations. + for _, match := range routeLiteralPattern.FindAllStringSubmatch(serverSource, -1) { + serverSource = strings.ReplaceAll(serverSource, match[1], `"`+match[2]+`"`) + } + + var routes []Subject + seen := map[string]bool{} + for _, match := range routePattern.FindAllStringSubmatch(serverSource, -1) { + method, path := match[1], normalizeRoute(match[2]) + // The surface is the dashboard API contract: the routes the bundled + // client consumes. The asset mount and the health probes have + // different consumers -- a browser and a load balancer or the update + // watchdog -- so they are out of scope here rather than reported as + // undeclared. Reporting them would be a false finding, and a false + // finding in a gate is worse than no gate. + if !strings.HasPrefix(path, apiPathPrefix) && path != eventStreamRoute { + continue + } + name := method + " " + path + if seen[name] { + continue + } + seen[name] = true + routes = append(routes, Subject{Name: name, Evidence: "internal/webui/server.go"}) + } + if len(routes) == 0 { + return nil, fmt.Errorf("parsed 0 routes from internal/webui/server.go; the parser is stale, refusing to report an empty surface") + } + + consumed, err := s.consumerPaths() + if err != nil { + return nil, err + } + for i := range routes { + if consumer, ok := consumed[routes[i].Name]; ok { + routes[i].Consumed = true + routes[i].Consumer = consumer + } + } + sort.Slice(routes, func(i, j int) bool { return routes[i].Name < routes[j].Name }) + return routes, nil +} + +// consumerPaths walks the dashboard source for path literals and maps each to +// a normalized "METHOD /path" route name. A path is credited to both GET and +// POST, because a bare literal cannot tell one verb from the other and +// reporting a route unconsumed on a verb mismatch would be a false finding. +func (s *webUISurface) consumerPaths() (map[string]string, error) { + srcDir := filepath.Join(s.root, "ui/src") + consumed := map[string]string{} + + err := filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() || (filepath.Ext(path) != ".jsx" && filepath.Ext(path) != ".js") { + return nil + } + body, err := os.ReadFile(path) + if err != nil { + return err + } + rel, err := filepath.Rel(s.root, path) + if err != nil { + return err + } + literals, err := scanFile(rel, string(body)) + if err != nil { + return err + } + for _, literal := range literals { + if !strings.HasPrefix(literal, apiPathPrefix) && literal != eventStreamRoute { + continue + } + route := normalizeRoute(literal) + for _, method := range []string{"GET", "POST", "PATCH", "DELETE"} { + key := method + " " + route + if _, exists := consumed[key]; !exists { + consumed[key] = rel + } + } + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("walk dashboard source: %w", err) + } + if len(consumed) == 0 { + return nil, fmt.Errorf("found 0 dashboard API call sites; refusing to report every route as unconsumed") + } + return consumed, nil +} + +// scanFile returns every API path literal in one dashboard source file. +// +// It fails loudly on a call it cannot parse. Under-reporting is how a gate +// silently stops checking, so a `fetch`/`req`/`EventSource` whose first +// argument is neither a literal nor one of the two shapes that legitimately +// carries no path -- a declaration, or the wrapper delegating on a variable -- +// is an error naming the file rather than a quietly smaller consumer set. +func scanFile(rel, body string) ([]string, error) { + var literals []string + for _, pattern := range append(append([]*regexp.Regexp{}, fetchPathPatterns...), eventPathPatterns...) { + for _, match := range pattern.FindAllStringSubmatch(body, -1) { + literals = append(literals, match[1]) + } + } + for _, match := range pathLiteralPattern.FindAllStringSubmatch(body, -1) { + literals = append(literals, match[1]) + } + + // Every call whose first argument is not a literal, minus the declarations + // and variable delegations that legitimately produce no path. + // + // The guard is deliberately one-directional. There is no matching "found no + // calls" condition: a file may legitimately carry a path literal with no + // call of its own (a router table, a link), and the aggregate check in + // consumerPaths already fails when the whole surface yields nothing. + declarations := len(declPattern.FindAllString(body, -1)) + delegations := len(delegatePattern.FindAllString(body, -1)) + for _, match := range callOpenPattern.FindAllStringSubmatch(body, -1) { + first := match[1] + if first == "" || literalArgOnly.MatchString(first) { + continue + } + // A non-literal first argument. Accounted for by a declaration or a + // delegation, or an under-report. + if declarations+delegations > 0 { + declarations-- + continue + } + return nil, fmt.Errorf( + "%s: fetch/req/EventSource call with non-literal first argument %q; the extractor cannot see the path it builds and would under-report", + rel, first, + ) + } + return literals, nil +} + +// normalizeRoute strips query strings and replaces both `${...}` template +// interpolations and `{param}` wildcards with a single placeholder, so a +// parameter's *name* never causes a false mismatch. `{id}` in the server and +// `{taskId}` in the client are the same route. +func normalizeRoute(route string) string { + route = strings.SplitN(route, "?", 2)[0] + route = tmpPattern.ReplaceAllString(route, "{}") + route = routeParamPat.ReplaceAllString(route, "{}") + return route +} diff --git a/tools/go.mod b/tools/go.mod index 95e670446..6bc530d70 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -20,7 +20,12 @@ 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 diff --git a/tools/go.sum b/tools/go.sum index c9e364e44..6f9029411 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -38,13 +38,23 @@ 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=