chore: cut agent governance to a single constitution

Replace CLAUDE.md with a short decision-rule constitution; move PRDs,
architecture, development and design docs and repo skills out of the tree;
delete the docs tooling (docsgen, prdlint, docdrift, docsite, contractaudit,
reachaudit) and its gate steps; stop install.sh copying repo skills into
runtime skills.
This commit is contained in:
sam committed 2026-10-03 21:47:46 +10:00
1 parent a45300d626
commit 42988970fe
190 files changed
+151 -31692

No files matched your search

-296
View File
@@ -1,296 +0,0 @@
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
}
// 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) {
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)
}
defer f.Close()
return parseDeclarations(f)
}
// 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))
}
}
}
}
-63
View File
@@ -1,63 +0,0 @@
// 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
}
-145
View File
@@ -1,145 +0,0 @@
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
}
-292
View File
@@ -1,292 +0,0 @@
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 route registrations in internal/webui, and the consumers are
// the path literals written under ui/src.
//
// 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
}
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.
//
// Extraction is deliberately name-agnostic: it matches the path *literal*
// rather than the call that carries it. An earlier version matched `req|fetch`
// by function name, and rewriting the client's helper from `req(` to
// `request(` silently reported 16 live routes as unconsumed. The contract this
// surface audits is "the dashboard calls this path", and a literal is how the
// dashboard expresses that regardless of what the surrounding call is called.
var (
// pathLiteralPattern matches a path literal that is the first argument of a
// call, in either quoting style. Both are needed: a fixed path is written
// with double quotes and an interpolated one with backticks.
//
// Two properties are load-bearing, and they pull in opposite directions.
//
// It does not name the function, because naming it broke on rename: matching
// `req|fetch` reported 16 live routes as unconsumed the moment the
// dashboard's helper became `request(`.
//
// It requires a call, because dropping *that* requirement made the check
// vacuous: crediting any quoted `/api/...` literal meant a comment, a dead
// array, or a display label counted as proof that the route was consumed, so
// deleting every real request still read as healthy. The two directions are
// not symmetric -- a false "unconsumed" is a loud, fixable failure, while a
// false "consumed" is a silent hole in the gate, which is worse than having
// no gate at all.
//
// Known limit: the path must be the *first* argument. Accepting a comma
// before the literal would start crediting array elements, restoring the
// vacuity this pattern exists to prevent.
pathLiteralPattern = regexp.MustCompile("\\b[A-Za-z_$][A-Za-z0-9_$]*\\s*\\(\\s*[\"`](/(?:api/|events)[^\"`\\s]*)")
// fragmentPattern matches a literal that begins an API path but does not
// hold the whole route, e.g. `"/api" + "/tasks"`. Such a route cannot be
// credited, so the file is reported rather than silently contributing
// nothing -- under-reporting is how a gate stops checking unnoticed.
fragmentPattern = regexp.MustCompile("[\"`](/api)[\"`]")
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 request path in one dashboard source file.
//
// Two things must be true of a mention before it counts as a consumer: it must
// be the first argument of a call, and it must be code rather than prose. The
// first excludes bare constants, dead arrays, and object properties; the second
// excludes a commented-out call, which otherwise leaves a call-shaped path in
// the file and reads as live.
//
// The only failure it reports is a path it cannot see whole. That is a narrow
// guard rather than a heuristic: it fires when a file concatenates a bare /api
// fragment into a route, because no literal then holds the path and the
// extractor would otherwise contribute nothing for that route without saying so.
func scanFile(rel, body string) ([]string, error) {
code := stripJSComments(body)
if fragmentPattern.MatchString(code) {
return nil, fmt.Errorf(
"%s: builds an API path from a bare /api fragment; the extractor cannot see the whole route and would under-report",
rel,
)
}
var literals []string
for _, match := range pathLiteralPattern.FindAllStringSubmatch(code, -1) {
literals = append(literals, match[1])
}
return literals, nil
}
// stripJSComments removes // and /* */ comments while leaving string, template,
// and regex literals intact, so the extractor measures code rather than prose
// about code. Without it, commenting out a call still reads as a live consumer
// -- the same silent hole as crediting a bare literal.
//
// Known limit: template-literal interpolations are treated as string content, so
// a request written inside `${...}` is not seen. No such call exists in ui/src.
func stripJSComments(src string) string {
var b strings.Builder
b.Grow(len(src))
for i := 0; i < len(src); {
switch {
case opensComment(src, i, '/'):
i = skipLineComment(src, i)
case opensComment(src, i, '*'):
i = skipBlockComment(src, i)
case src[i] == '"' || src[i] == '\'' || src[i] == '`':
i = copyLiteral(&b, src, i)
default:
b.WriteByte(src[i])
i++
}
}
return b.String()
}
// opensComment reports whether a comment introduced by "/" plus second opens
// at i.
func opensComment(src string, i int, second byte) bool {
return src[i] == '/' && i+1 < len(src) && src[i+1] == second
}
// skipLineComment returns the index of the newline that ends the // comment at
// i, leaving the newline itself to be copied: dropping it would join two
// statements into one line.
func skipLineComment(src string, i int) int {
for i < len(src) && src[i] != '\n' {
i++
}
return i
}
// skipBlockComment returns the index just past the "*/" closing the comment at
// i, or the end of src when the comment is unterminated.
func skipBlockComment(src string, i int) int {
for i += 2; i < len(src); i++ {
if src[i] == '*' && i+1 < len(src) && src[i+1] == '/' {
return i + 2
}
}
return i
}
// copyLiteral copies the string, template or regex literal opening at i,
// escapes included, and returns the index just past its closing quote. An
// unterminated literal copies to the end rather than discarding the tail.
func copyLiteral(b *strings.Builder, src string, i int) int {
quote := src[i]
b.WriteByte(quote)
for i++; i < len(src); i++ {
b.WriteByte(src[i])
if src[i] == '\\' && i+1 < len(src) {
i++
b.WriteByte(src[i])
continue
}
if src[i] == quote {
return i + 1
}
}
return i
}
// 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
}
-56
View File
@@ -1,56 +0,0 @@
# docdrift baseline: citations in docs/ that no longer resolve to a
# repository path. This is a burn-down list, not a licence -- repoint the
# citation or delete the claim, then remove the line. Regenerate with:
#
# go -C tools run -mod=readonly ./docdrift list --repo-root .. > tools/docdrift/baseline.txt
internal/gate
internal/nats
internal/infrastructure/spec
internal/policy
internal/store
internal/domain/controlplane
internal/memory
internal/memory/builtin.Store
internal/app/archied/config_update.go
internal/domain/plugin
internal/curator
internal/infrastructure/forge
internal/workflow
internal/domain/eda/forgeaction
internal/app/agentworker/review.go
internal/tools/dispatch.go
internal/infrastructure/cronstore
internal/output/report.go
internal/actors/mine.go
internal/domain/research
internal/infrastructure/research/search
internal/tools/search
internal/tools/research
internal/infrastructure/research
internal/domain/workflow/wfeval/yaegi.go
internal/gate/gateeval/yaegi.go
internal/domain/workflow/skillbuild.BuildRegistry
internal/store/events.go
internal/store/captures.go
internal/domain/extensions
internal/domain/extensions/inventory.go
internal/webui/api_extensions.go
internal/app/archied/server.go
internal/infrastructure/image
internal/infrastructure/image/comfyui
internal/app/archied/telegram_setup.go
internal/tools/image/tool.go
internal/infrastructure/image/openai
internal/memory/manager.go
internal/memory/scanner.go
internal/tools/provider/memory
internal/infrastructure/legacyread
internal/gate/gateeval
internal/domain/eda/module/notify/types.go
internal/domain/eda/module/notify
internal/memory.MemoryProvider
internal/memory.Manager
internal/infrastructure/store
internal/store/interface.go
internal/storerpc
internal/store/store.go
-426
View File
@@ -1,426 +0,0 @@
// Command docdrift rejects documentation that cites a repository path which no
// longer exists.
//
// A page under docs/ states a design, a contract, or a decision, and cites the
// code that carries it. When that code moves or is deleted the sentence
// survives unchanged: it still reads as authoritative, and every session told
// to treat docs/architecture as settled design pays for it. Nothing else in the
// gate compares a prose citation against the tree. docsgen checks the contract
// schema against Go types, docsite checks generated artifacts against their
// Markdown sources, prdlint checks PRD writing style. All three verify internal
// consistency, so a page can describe a package deleted months ago and every
// check stays green -- which is how a page describing a removed system survives
// behind a hand-written "removed" banner.
//
// The baseline is a burn-down list, not a licence. A citation listed there is
// known debt: repoint it or delete the claim, then remove the line. The check
// fails when an allowlisted citation starts resolving again, so the list cannot
// quietly outlive its reasons.
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"sort"
"strings"
"syscall"
"unicode"
"unicode/utf8"
)
const (
defaultDir = "docs"
defaultBaseline = "tools/docdrift/baseline.txt"
)
// citationRE matches a repository path cited in prose. The character class
// stops at backticks, brackets, commas and whitespace, so Markdown around the
// citation does not leak into the match.
var citationRE = regexp.MustCompile(`\binternal/[A-Za-z0-9_./-]+`)
// suffixRE strips the line-number suffix some older prose carries.
var suffixRE = regexp.MustCompile(`:\d+$`)
// citation is one prose reference to a repository path.
type citation struct {
Path string // normalized, e.g. internal/config, internal/daemon/daemon.go
File string // repo-relative file it appears in
Line int // 1-based
}
func (c citation) String() string {
return fmt.Sprintf("%s:%d: %s", c.File, c.Line, c.Path)
}
// analysis is the outcome of comparing the tree against the baseline.
type analysis struct {
newDrift []citation // unresolvable and not allowlisted
stale []string // allowlisted but resolving again
unused []string // allowlisted but no longer cited anywhere
known int // unresolvable and allowlisted
scanned int // citations that do resolve
citedFile int // files containing at least one citation
}
func main() {
os.Exit(run())
}
// run holds the whole program so its deferred signal cleanup actually runs:
// os.Exit in main cannot be deferred past, and this tool's exit codes carry the
// gate's verdict, so the code is propagated rather than exited on.
func run() int {
// The one subprocess this tool runs (git ls-files) is registered against
// this context, so a cancelled gate does not leave a git process behind and
// a wedged one cannot outlive the run.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
args := os.Args[1:]
mode := "check"
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
mode = args[0]
args = args[1:]
}
flags := flag.NewFlagSet("docdrift", flag.ContinueOnError)
flags.SetOutput(io.Discard)
repoRoot := flags.String("repo-root", "..", "path to the Archie repository root")
dir := flags.String("dir", defaultDir, "directory to scan, relative to the repository root")
baselinePath := flags.String("baseline", defaultBaseline, "baseline file, relative to the repository root")
if err := flags.Parse(args); err != nil {
fmt.Fprintf(os.Stderr, "docdrift: %v\n", err)
return 2
}
if extra := flags.Args(); len(extra) > 0 {
fmt.Fprintf(os.Stderr, "docdrift: unexpected argument %q\n", extra[0])
return 2
}
root, err := filepath.Abs(*repoRoot)
if err != nil {
fmt.Fprintf(os.Stderr, "docdrift: %v\n", err)
return 2
}
tree, err := newTrackedTree(ctx, root)
if err != nil {
fmt.Fprintf(os.Stderr, "docdrift: %v\n", err)
return 2
}
switch mode {
case "check":
failed, err := runCheck(root, *dir, tree, filepath.Join(root, *baselinePath))
if err != nil {
fmt.Fprintf(os.Stderr, "docdrift: %v\n", err)
return 2
}
if failed {
return 1
}
return 0
case "list":
if err := runList(root, *dir, tree); err != nil {
fmt.Fprintf(os.Stderr, "docdrift: %v\n", err)
return 2
}
return 0
default:
fmt.Fprintf(os.Stderr, "docdrift: unknown mode %q (want check or list)\n", mode)
return 2
}
}
// runCheck reports new drift and stale baseline entries. It answers whether the
// tree fails the gate, and returns an error only when the check itself could not
// run -- a distinction the exit code carries.
func runCheck(root, dir string, tree *trackedTree, baselinePath string) (bool, error) {
baseline, err := readBaseline(baselinePath)
if err != nil {
return false, err
}
result, err := analyse(root, dir, tree, baseline)
if err != nil {
return false, err
}
for _, c := range result.newDrift {
fmt.Fprintf(os.Stderr, "new drift: %s\n", c)
}
for _, p := range result.stale {
fmt.Fprintf(os.Stderr, "stale baseline entry (now resolves, remove it): %s\n", p)
}
for _, p := range result.unused {
fmt.Fprintf(os.Stderr, "note: baseline entry no longer cited anywhere: %s\n", p)
}
if len(result.newDrift) == 0 && len(result.stale) == 0 {
fmt.Printf("docdrift: %d cited file(s), %d resolving citation(s), %d known-debt citation(s)\n",
result.citedFile, result.scanned, result.known)
return false, nil
}
fmt.Fprintf(os.Stderr,
"\ndocdrift: %d new dangling citation(s), %d stale baseline entry(ies).\n"+
"Repoint the citation at the code that carries it now, delete the claim it\n"+
"supported, or -- only for a path that is knowingly gone -- add it to %s\n"+
"with the reason in the commit message.\n",
len(result.newDrift), len(result.stale), defaultBaseline)
return true, nil
}
// runList prints the current debt in baseline format, for regeneration.
func runList(root, dir string, tree *trackedTree) error {
cites, err := scan(root, dir)
if err != nil {
return err
}
fmt.Println("# docdrift baseline: citations in docs/ that no longer resolve to a")
fmt.Println("# repository path. This is a burn-down list, not a licence -- repoint the")
fmt.Println("# citation or delete the claim, then remove the line. Regenerate with:")
fmt.Println("#")
fmt.Println("# go -C tools run -mod=readonly ./docdrift list --repo-root .. > tools/docdrift/baseline.txt")
seen := map[string]bool{}
for _, c := range cites {
if seen[c.Path] || tree.resolves(c.Path) {
continue
}
seen[c.Path] = true
fmt.Println(c.Path)
}
return nil
}
// analyse compares every citation in dir against the tree and the baseline.
func analyse(root, dir string, tree *trackedTree, baseline map[string]bool) (analysis, error) {
cites, err := scan(root, dir)
if err != nil {
return analysis{}, err
}
var out analysis
unresolved := map[string]bool{}
files := map[string]bool{}
for _, c := range cites {
files[c.File] = true
if tree.resolves(c.Path) {
out.scanned++
continue
}
unresolved[c.Path] = true
if baseline[c.Path] {
out.known++
continue
}
out.newDrift = append(out.newDrift, c)
}
out.citedFile = len(files)
for p := range baseline {
switch {
case tree.resolves(p):
out.stale = append(out.stale, p)
case !unresolved[p]:
out.unused = append(out.unused, p)
}
}
sort.Strings(out.stale)
sort.Strings(out.unused)
return out, nil
}
// scan collects every citation in the Markdown files under dir.
func scan(root, dir string) ([]citation, error) {
base := filepath.Join(root, dir)
var out []citation
err := filepath.WalkDir(base, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
// Generated artifacts embed page bodies; scanning them would
// double-count every citation they carry.
if d.Name() == "generated" || d.Name() == ".git" || d.Name() == "node_modules" {
return fs.SkipDir
}
return nil
}
if !strings.HasSuffix(d.Name(), ".md") {
return nil
}
return scanFile(root, path, &out)
})
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("scan %s: %w", dir, err)
}
return out, err
}
// scanFile appends every citation found in one file, with its line number.
func scanFile(root, path string, out *[]citation) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
rel, err := filepath.Rel(root, path)
if err != nil {
rel = path
}
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for line := 1; scanner.Scan(); line++ {
for _, raw := range citationRE.FindAllString(scanner.Text(), -1) {
p := normalize(raw)
if p == "" {
continue
}
*out = append(*out, citation{Path: p, File: rel, Line: line})
}
}
return scanner.Err()
}
// normalize strips the Markdown and Go-pattern decoration a prose citation
// carries, leaving a repository path.
func normalize(raw string) string {
s := strings.TrimRight(raw, ".,;:/")
s = strings.TrimSuffix(s, "/...")
s = suffixRE.ReplaceAllString(s, "")
return strings.TrimRight(s, ".,;:/")
}
// trackedTree is the set of paths git tracks: what "exists" means to this gate.
//
// It is deliberately not the filesystem. A directory left behind by a checkout
// that removed its files, or by a branch switch, exists on one machine and not
// another, so a filesystem check makes this gate answer differently in CI and in
// a developer's tree. That is how it first shipped a baseline that passed
// locally and failed in CI: five citations -- internal/gate, internal/gate/gateeval
// and internal/domain/workflow/skillbuild among them -- resolved against empty
// leftover directories that were never in the repository at all.
type trackedTree struct {
files map[string]bool
dirs map[string]bool
}
// newTrackedTree reads the tracked tree from git. Failing to read it is fatal
// rather than a fallback to the filesystem, because a silent fallback is the
// non-reproducibility this type exists to remove.
func newTrackedTree(ctx context.Context, root string) (*trackedTree, error) {
cmd := exec.CommandContext(ctx, "git", "-C", root, "ls-files", "-z")
out, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("git ls-files: %w (docdrift resolves against the tracked tree, so it must run in a git checkout)", err)
}
tree := &trackedTree{files: map[string]bool{}, dirs: map[string]bool{}}
for _, path := range strings.Split(string(out), "\x00") {
if path == "" {
continue
}
tree.files[path] = true
// Every ancestor of a tracked file is a directory the repository has,
// which is what makes `internal/domain/workflow` resolve without a
// file being named.
for dir := filepath.Dir(path); dir != "." && dir != "/" && dir != ""; dir = filepath.Dir(dir) {
tree.dirs[dir] = true
}
}
return tree, nil
}
// resolves reports whether a citation names something the repository holds: a
// tracked file, a directory containing tracked files, or a package directory
// cited with a symbol attached.
func (t *trackedTree) resolves(path string) bool {
for _, c := range candidates(path) {
if c == "" {
continue
}
if t.files[c] || t.files[c+".go"] || t.dirs[c] {
return true
}
if t.prefixMatch(c) {
return true
}
}
return false
}
// prefixMatch reports whether a citation names a file shape rather than a file.
// `internal/webui/api_<concern>.go` documents a naming convention: the angle
// bracket ends the path token, leaving a truncated final segment. It is
// satisfied when a tracked sibling starts with that segment.
func (t *trackedTree) prefixMatch(path string) bool {
dir, base := filepath.Split(path)
if !strings.HasSuffix(base, "_") {
return false
}
dir = strings.TrimSuffix(dir, "/")
for file := range t.files {
if filepath.Dir(file) == dir && strings.HasPrefix(filepath.Base(file), base) {
return true
}
}
return false
}
// candidates lists the paths a citation could mean: itself, itself with a
// trailing ".Symbol" dropped (a package cited together with a type or
// function), and itself with a trailing "/Symbol" dropped (a test or function
// cited with its package).
func candidates(path string) []string {
out := []string{path}
if strings.HasSuffix(path, ".go") {
return out
}
if i := strings.LastIndex(path, "."); i > strings.LastIndex(path, "/") {
out = append(out, path[:i])
}
if i := strings.LastIndex(path, "/"); i > 0 && isSymbolSegment(path[i+1:]) {
out = append(out, path[:i])
}
return out
}
// isSymbolSegment reports whether a path segment names a Go identifier rather
// than a package directory.
func isSymbolSegment(seg string) bool {
if seg == "" {
return false
}
r, _ := utf8.DecodeRuneInString(seg)
return unicode.IsUpper(r)
}
// readBaseline loads the allowlist: one citation per line, "#" comments.
func readBaseline(path string) (map[string]bool, error) {
f, err := os.Open(path)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return map[string]bool{}, nil
}
return nil, err
}
defer f.Close()
out := map[string]bool{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
out[line] = true
}
return out, scanner.Err()
}
-546
View File
@@ -1,546 +0,0 @@
// Command docsgen generates reference schemas from Archie-owned Go contracts.
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"github.com/invopop/jsonschema"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/gateway"
)
// defaultOutputPath is the committed artifact docsgen owns, relative to the
// repository root.
const defaultOutputPath = "docs/data/generated/contracts.json"
type mode int
const (
modeWrite mode = iota
modeCheck
)
// generatedArtifacts declares the directories whose contents are generated
// end-to-end, and every file name accounted for in each. Obsolete detection is
// scoped to these directories: an arbitrary --out location is not ours to judge,
// and the target layout anticipates further named artifacts here (catalog.json,
// AsyncAPI output), which must not be reported as stale merely for existing.
//
// docs/data/generated is shared. docsgen writes contracts.json from the
// Go contract types; tools/docsite writes docs.json and dev-docs.json from the
// Markdown sources, one per published set. Each tool verifies its OWN files, and
// all three are named here because this map is the directory's ownership record:
// whichever tool runs first must not report the others' artifacts as unaccounted
// files. docsgen does not verify the docsite artifacts, and tools/docsite keeps no
// registry of its own for that reason -- one fact, one home.
var generatedArtifacts = map[string][]string{
"docs/data/generated": {"contracts.json", "docs.json", "dev-docs.json"},
}
// options is a parsed command line.
type options struct {
mode mode
repoRoot string
out string
}
func main() {
parsed, err := parseOptions(os.Args[1:])
if err != nil {
log.Fatalf("docsgen: %v", err)
}
if parsed.mode == modeCheck {
err = check(parsed.repoRoot, parsed.out)
} else {
err = run(parsed.repoRoot, parsed.out)
}
if err != nil {
log.Fatalf("docsgen: %v", err)
}
}
// parseOptions resolves the optional `check` subcommand and the flags that
// follow it. A leftover positional argument is an error rather than something
// to ignore: `docsgen --repo-root .. check` would otherwise quietly fall through
// to the write path and overwrite the artifact that check promises not to
// touch, and a misspelled subcommand would do the same silently.
func parseOptions(args []string) (options, error) {
selected := modeWrite
if len(args) > 0 && args[0] == "check" {
selected = modeCheck
args = args[1:]
}
flags := flag.NewFlagSet("docsgen", flag.ContinueOnError)
flags.SetOutput(io.Discard)
repoRoot := flags.String("repo-root", "..", "path to the Archie repository root")
out := flags.String(
"out",
defaultOutputPath,
"output path relative to the repository root",
)
if err := flags.Parse(args); err != nil {
return options{}, err
}
if extra := flags.Args(); len(extra) > 0 {
return options{}, fmt.Errorf(
"unexpected argument %q; usage: docsgen [check] [--repo-root DIR] [--out PATH] "+
"(`check` must come first)",
extra[0],
)
}
return options{mode: selected, repoRoot: *repoRoot, out: *out}, nil
}
// check regenerates the artifact into a temporary directory and compares it
// with the committed output. It never writes to the working tree, so a failing
// check leaves the tree exactly as it found it -- the author, not the gate,
// applies the regenerated bytes.
func check(repoRoot, outPath string) error {
absRoot, err := filepath.Abs(repoRoot)
if err != nil {
return fmt.Errorf("resolve repository root: %w", err)
}
committedPath := outPath
if !filepath.IsAbs(committedPath) {
committedPath = filepath.Join(absRoot, committedPath)
}
relative := displayPath(absRoot, committedPath)
tmpDir, err := os.MkdirTemp("", "docsgen-check-")
if err != nil {
return fmt.Errorf("create temporary directory: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Reuse the write path so check and generate can never disagree about
// what the committed bytes should be.
generatedPath := filepath.Join(tmpDir, filepath.Base(committedPath))
if err := write(absRoot, generatedPath, true); err != nil {
return err
}
expected, err := os.ReadFile(generatedPath)
if err != nil {
return fmt.Errorf("read generated artifact: %w", err)
}
committed, err := os.ReadFile(committedPath)
if errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf(
"%s is missing; regenerate it by running `go -C tools run ./docsgen --repo-root ..` from the tools module",
relative,
)
}
if err != nil {
return fmt.Errorf("read %s: %w", relative, err)
}
problems := compareArtifacts(relative, expected, committed)
problems = append(problems, obsoleteArtifacts(absRoot, filepath.Dir(committedPath))...)
if len(problems) == 0 {
fmt.Printf("docsgen: %s is up to date\n", relative)
return nil
}
return fmt.Errorf(
"%s is stale; regenerate it with: go -C tools run ./docsgen --repo-root ..\n %s",
relative,
strings.Join(problems, "\n "),
)
}
// compareArtifacts reports every schema whose generated form differs from the
// committed form, plus a whole-file difference the schema view cannot see
// (whitespace or key ordering).
func compareArtifacts(relative string, expected, committed []byte) []string {
expectedSchemas, err := decodeSchemas(expected)
if err != nil {
return []string{fmt.Sprintf("%s: generated output is unreadable: %v", relative, err)}
}
committedSchemas, err := decodeSchemas(committed)
if err != nil {
return []string{fmt.Sprintf("%s: committed output is unreadable: %v", relative, err)}
}
provenance := schemaProvenance(expectedSchemas, contractRoots())
var problems []string
for _, name := range sortedSchemaNames(expectedSchemas) {
committedSchema, ok := committedSchemas[name]
if !ok {
problems = append(problems, fmt.Sprintf(
"schema %q is missing from the committed output (%s)",
name, describeProvenance(provenance, name),
))
continue
}
if !reflect.DeepEqual(expectedSchemas[name], committedSchema) {
problems = append(problems, fmt.Sprintf(
"schema %q changed (%s)",
name, describeProvenance(provenance, name),
))
}
}
for _, name := range sortedSchemaNames(committedSchemas) {
if _, ok := expectedSchemas[name]; !ok {
problems = append(problems, fmt.Sprintf(
"schema %q is obsolete: no Archie-owned contract defines it", name,
))
}
}
if len(problems) == 0 && !bytes.Equal(expected, committed) {
problems = append(problems, "content differs from generated form (whitespace or key ordering)")
}
return problems
}
// obsoleteArtifacts reports files present in a directory docsgen owns that the
// generator no longer produces, so a renamed or deleted artifact cannot linger
// as dead documentation. A directory docsgen does not own is never judged: its
// JSON belongs to someone else.
func obsoleteArtifacts(absRoot, dir string) []string {
owned, ours := ownedArtifacts(absRoot, dir)
if !ours {
return nil
}
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
var problems []string
for _, entry := range entries {
if entry.IsDir() || owned[entry.Name()] {
continue
}
if filepath.Ext(entry.Name()) != ".json" {
continue
}
problems = append(problems, fmt.Sprintf(
"%s is obsolete: no generator in tools/docsgen produces it",
displayPath(absRoot, filepath.Join(dir, entry.Name())),
))
}
return problems
}
// ownedArtifacts reports which file names docsgen owns in dir, and whether dir
// is one docsgen owns at all.
func ownedArtifacts(absRoot, dir string) (map[string]bool, bool) {
relative, err := filepath.Rel(absRoot, dir)
if err != nil {
return nil, false
}
names, ours := generatedArtifacts[filepath.ToSlash(relative)]
if !ours {
return nil, false
}
owned := make(map[string]bool, len(names))
for _, name := range names {
owned[name] = true
}
return owned, true
}
// schemaProvenance names the authoritative Go definition behind each published
// schema, so a drift report points at the code that must be reviewed rather
// than only at the generated file. roots maps each published contract to its
// Go definition; every other schema is attributed to the contract that pulled
// it in, transitively, because a definition reachable only through another
// definition still belongs to the contract that caused it to be published.
func schemaProvenance(schemas map[string]any, roots map[string]string) map[string]string {
// attribution maps each schema to the published contract it came in under.
attribution := make(map[string]string, len(roots))
queue := make([]string, 0, len(roots))
for _, name := range sortedStringKeys(roots) {
attribution[name] = name
queue = append(queue, name)
}
// Breadth-first, seeded with every contract before any nested definition is
// followed, so a definition reachable from several contracts is attributed
// to the alphabetically first of them rather than to whichever the walk
// happened to reach.
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
root := attribution[current]
walkSchemaRefs(schemas[current], func(target string) {
if _, known := attribution[target]; known {
return
}
attribution[target] = root
queue = append(queue, target)
})
}
provenance := make(map[string]string, len(attribution))
for name, root := range attribution {
if source, isRoot := roots[name]; isRoot {
provenance[name] = source
continue
}
provenance[name] = "reached from " + roots[root]
}
return provenance
}
func sortedStringKeys(values map[string]string) []string {
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func describeProvenance(provenance map[string]string, name string) string {
if source, ok := provenance[name]; ok {
return "authoritative definition: " + source
}
return "no authoritative definition found"
}
// contractRoots labels each published contract with the Go definition it comes
// from, which is what makes a drift report name code rather than a file.
func contractRoots() map[string]string {
types := currentContractTypes()
roots := make(map[string]string, len(types))
for name, t := range types {
roots[name] = t.PkgPath() + "." + t.Name()
}
return roots
}
func walkSchemaRefs(value any, visit func(target string)) {
switch node := value.(type) {
case map[string]any:
// Sorted so a schema reachable by more than one path is visited in the
// same order every run; provenance must not depend on map iteration.
keys := make([]string, 0, len(node))
for key := range node {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
child := node[key]
if key == "$ref" {
if ref, ok := child.(string); ok {
if target, found := strings.CutPrefix(ref, "#/schemas/"); found {
visit(target)
}
}
continue
}
walkSchemaRefs(child, visit)
}
case []any:
for _, child := range node {
walkSchemaRefs(child, visit)
}
}
}
func decodeSchemas(body []byte) (map[string]any, error) {
var data struct {
Schemas map[string]any `json:"schemas"`
}
if err := json.Unmarshal(body, &data); err != nil {
return nil, err
}
return data.Schemas, nil
}
func sortedSchemaNames(schemas map[string]any) []string {
names := make([]string, 0, len(schemas))
for name := range schemas {
names = append(names, name)
}
sort.Strings(names)
return names
}
func run(repoRoot, outPath string) error {
absRoot, err := filepath.Abs(repoRoot)
if err != nil {
return fmt.Errorf("resolve repository root: %w", err)
}
return write(absRoot, outPath, false)
}
// displayPath prefers a repository-relative path for diagnostics, falling back
// to the path as given when the target sits outside the repository (a temp
// directory under check, or an explicit --out).
func displayPath(absRoot, path string) string {
relative, err := filepath.Rel(absRoot, path)
if err != nil || strings.HasPrefix(relative, "..") {
return filepath.ToSlash(path)
}
return filepath.ToSlash(relative)
}
func write(absRoot, outPath string, quiet bool) error {
reflector := &jsonschema.Reflector{
ExpandedStruct: true,
DoNotReference: false,
}
if err := loadGoComments(reflector, absRoot); err != nil {
return fmt.Errorf("load Go comments: %w", err)
}
schemas := map[string]any{}
types := currentContractTypes()
names := make([]string, 0, len(types))
for name := range types {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if err := collectSchema(reflector, schemas, name, types[name]); err != nil {
return fmt.Errorf("reflect %s: %w", name, err)
}
}
rewriteDefRefs(schemas)
body, err := json.MarshalIndent(struct {
GeneratedBy string `json:"generatedBy"`
Schemas map[string]any `json:"schemas"`
}{
GeneratedBy: "tools/docsgen",
Schemas: schemas,
}, "", " ")
if err != nil {
return fmt.Errorf("marshal documentation data: %w", err)
}
body = append(body, '\n')
destination := outPath
if !filepath.IsAbs(destination) {
destination = filepath.Join(absRoot, destination)
}
if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil {
return fmt.Errorf("create output directory: %w", err)
}
if err := os.WriteFile(destination, body, 0o644); err != nil {
return fmt.Errorf("write %s: %w", destination, err)
}
if !quiet {
fmt.Printf("docsgen: wrote %d schemas to %s\n", len(schemas), destination)
}
return nil
}
// currentContractTypes adapts the pre-domain-registry contract set during the
// architecture migration. Delete it when agent execution and messaging expose
// domain-owned documentation registries; docsgen must then consume those
// registries directly.
func currentContractTypes() map[string]reflect.Type {
return map[string]reflect.Type{
"AgentExecutionRequest": reflect.TypeFor[agentexec.Request](),
"AgentExecutionResult": reflect.TypeFor[agentexec.Result](),
"MessageEvent": reflect.TypeFor[gateway.MessageEvent](),
}
}
func loadGoComments(reflector *jsonschema.Reflector, repoRoot string) error {
const modulePath = "github.com/samcharles93/archie-core"
if err := reflector.AddGoComments("", filepath.Join(repoRoot, "internal")); err != nil {
return err
}
rootPrefix := filepath.ToSlash(repoRoot) + "/"
comments := make(map[string]string, len(reflector.CommentMap))
for name, comment := range reflector.CommentMap {
relativeName := strings.TrimPrefix(filepath.ToSlash(name), rootPrefix)
comments[modulePath+"/"+relativeName] = comment
}
reflector.CommentMap = comments
return nil
}
func collectSchema(
reflector *jsonschema.Reflector,
schemas map[string]any,
name string,
t reflect.Type,
) error {
if _, exists := schemas[name]; exists {
return fmt.Errorf("duplicate published schema name %q", name)
}
raw, err := json.Marshal(reflector.ReflectFromType(t))
if err != nil {
return err
}
var tree map[string]any
if err := json.Unmarshal(raw, &tree); err != nil {
return err
}
defs, _ := tree["$defs"].(map[string]any)
delete(tree, "$defs")
delete(tree, "$schema")
delete(tree, "$id")
schemas[name] = tree
for defName, defSchema := range defs {
if existing, exists := schemas[defName]; exists {
if !reflect.DeepEqual(existing, defSchema) {
return fmt.Errorf("conflicting schema definition %q", defName)
}
continue
}
schemas[defName] = defSchema
}
return nil
}
func rewriteDefRefs(schemas map[string]any) {
for name, schema := range schemas {
schemas[name] = rewriteNode(schema)
}
}
func rewriteNode(value any) any {
switch node := value.(type) {
case map[string]any:
for key, child := range node {
if key == "$ref" {
if ref, ok := child.(string); ok {
node[key] = rewriteRef(ref)
continue
}
}
node[key] = rewriteNode(child)
}
return node
case []any:
for index, child := range node {
node[index] = rewriteNode(child)
}
return node
default:
return value
}
}
func rewriteRef(ref string) string {
const prefix = "#/$defs/"
if len(ref) > len(prefix) && ref[:len(prefix)] == prefix {
return "#/schemas/" + ref[len(prefix):]
}
return ref
}
-808
View File
@@ -1,808 +0,0 @@
// Command docsite derives the documentation sets into canonical, host-neutral
// artifacts.
//
// The Markdown is the source; the JSON is the fact set every renderer reads.
// The external Astro website consumes the artifacts; the JSON is the contract
// and the Markdown stays the source. tools/newsgen follows the same rule for
// release facts.
//
// One source tree yields two sets, each with its own artifact and its own url
// base: see publishRules for the split and the reasons. A renderer reads both
// files and serves each under its own base; the file a page arrives in is the set
// it belongs to, so neither carries a discriminator.
//
// Output is generated and committed:
//
// docs/data/generated/docs.json
// docs/data/generated/dev-docs.json
//
// `docsite check` regenerates both in memory and fails when a committed one
// differs, without touching the tree.
//
// This tool keeps no registry of the generated directory it writes into: that
// directory is accounted for by docsgen's generatedArtifacts, which names both
// files, so a second registry here would be a second home for one fact.
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"unicode"
)
// docsDir is the Markdown source tree, relative to the repository root.
const docsDir = "docs"
// docSet is one published set: the pages it holds, the path they are served
// under, and the committed artifact this tool writes for it.
type docSet struct {
Name string
URLPrefix string
ArtifactPath string
}
// The two sets. The public set keeps directory-style URLs stable so existing
// links keep working.
var (
publicDocs = docSet{Name: "public", URLPrefix: "/docs/", ArtifactPath: "docs/data/generated/docs.json"}
developmentDocs = docSet{Name: "development", URLPrefix: "/dev/", ArtifactPath: "docs/data/generated/dev-docs.json"}
// sets is the write and check order, so a run reports its files the same way
// every time.
sets = []docSet{publicDocs, developmentDocs}
)
type mode int
const (
modeWrite mode = iota
modeCheck
)
// options is a parsed command line.
type options struct {
mode mode
repoRoot string
}
func main() {
parsed, err := parseOptions(os.Args[1:])
if err != nil {
log.Fatalf("docsite: %v", err)
}
if parsed.mode == modeCheck {
err = check(parsed.repoRoot)
} else {
err = write(parsed.repoRoot)
}
if err != nil {
log.Fatalf("docsite: %v", err)
}
}
// parseOptions resolves the optional `check` subcommand and the flags that may
// follow it. The subcommand is peeled off before flag parsing rather than left for
// it to ignore: `docsite --repo-root .. check` would otherwise fall through to the
// write path and rewrite the artifact check promises not to touch.
func parseOptions(args []string) (options, error) {
parsed := options{repoRoot: "."}
if len(args) > 0 && args[0] == "check" {
parsed.mode = modeCheck
args = args[1:]
}
flags := flag.NewFlagSet("docsite", flag.ContinueOnError)
flags.StringVar(&parsed.repoRoot, "repo-root", ".", "repository root to read docs from")
if err := flags.Parse(args); err != nil {
return options{}, err
}
if flags.NArg() > 0 {
return options{}, fmt.Errorf("unexpected argument %q", flags.Arg(0))
}
return parsed, nil
}
// document is the artifact. Its keys are a frozen contract: a renderer is built
// against them, so a rename here breaks a consumer this repository does not
// compile.
type document struct {
Pages []page `json:"pages"`
Nav []navNode `json:"nav"`
}
// page is one published document. Body is the raw Markdown source: presentation
// belongs to the renderer, so this artifact deliberately does not carry HTML.
type page struct {
URL string `json:"url"`
Title string `json:"title"`
Section string `json:"section"`
Body string `json:"body"`
}
// navNode is one entry in the sidebar: a link when URL is set, a group when Items
// is.
type navNode struct {
Title string `json:"title"`
URL string `json:"url,omitempty"`
Items []navNode `json:"items,omitempty"`
}
// publishRules is the split, and the reasons. Everything under docs/ publishes,
// in one set or the other, except:
//
// - archive/ superseded design. Publishing it competes with the current
// architecture for a reader's attention, which is the exact failure this
// repository already fights.
// - design/ design handoff bundles (prompts, mockups, theme tokens):
// inputs to building the UI, not pages to read.
// - inspiration/ research notes that discuss other products by name.
// - news/ release notes, which tools/newsgen owns and a renderer reads
// from releases.json.
// - github-token.md setup notes about credentials.
//
// What remains divides by audience, not by sensitivity: every development page
// may be read by anyone. architecture/ and prds/ are written for contributors --
// the organisation rules, the migration register, the review procedure, the open
// design decisions -- and a reader looking for what Archie is and how to point an
// event at it is not served by meeting them in one sidebar. development/ holds
// the checklists for changing Archie, written for the same readers. They are the
// development set. Everything else is the public set.
//
// Selective PRD publication is gone with the split rather than carried into it: it
// existed only because settled architecture cites PRDs and a link to a held-back
// target fails this tool, so five PRDs published to keep citations alive. Both
// halves of those citations are now in the development set.
//
// Changing either set means editing this list. The comment is the record: a
// renderer that reads an artifact cannot see why a page is absent from it, and
// neither can the next person deciding where a new page belongs.
var (
heldBackTrees = map[string]bool{"archive": true, "design": true, "inspiration": true, "news": true}
heldBackPages = map[string]bool{"github-token.md": true}
developmentTree = map[string]bool{"architecture": true, "prds": true, "development": true}
)
// setFor is the set one published page belongs to, by its top-level directory.
func setFor(relative string) docSet {
if developmentTree[strings.Split(relative, "/")[0]] {
return developmentDocs
}
return publicDocs
}
// heldBack reports whether one path relative to docs/ is deliberately absent from
// the published set. Links and pages are judged by this one rule, so a page is
// never published while a link to it is refused, or the reverse.
func heldBack(relative string) bool {
if heldBackPages[relative] {
return true
}
return heldBackTrees[strings.Split(relative, "/")[0]]
}
// published reports whether one path relative to docs/ is a page either artifact
// carries.
func published(relative string) bool {
return strings.HasSuffix(relative, ".md") && !heldBack(relative)
}
// intraDocsLink matches a Markdown inline link or image. The target is the only
// part this tool rewrites; everything else in the match is preserved.
var intraDocsLink = regexp.MustCompile(`\]\(\s*([^)\s]+)`)
// fenceDelimiter opens or closes a fenced code block.
var fenceDelimiter = regexp.MustCompile("^\\s*(```|~~~)")
// maskCode blanks the code spans in one line, keeping its length and every other
// byte, so a link match found in the masked line indexes the real one. Code is
// prose to a Markdown renderer's link parser: `Resolve[T](i, src)` is a generic
// call, not a link to `i,`, and the difference is the backticks.
func maskCode(line string) string {
masked := []byte(line)
for index := 0; index < len(masked); {
if masked[index] != '`' {
index++
continue
}
open := index
for index < len(masked) && masked[index] == '`' {
index++
}
run := index - open
closed := -1
for scan := index; scan < len(masked); {
if masked[scan] != '`' {
scan++
continue
}
start := scan
for scan < len(masked) && masked[scan] == '`' {
scan++
}
if scan-start == run {
closed = scan
break
}
}
// An unclosed run is literal text to a Markdown renderer, so it is literal
// here too and the scan continues past it.
if closed < 0 {
continue
}
for blank := open; blank < closed; blank++ {
masked[blank] = ' '
}
index = closed
}
return string(masked)
}
// unresolvedLink names a link the artifact cannot honestly carry: its target is a
// page or asset the published set holds back. It is reported rather than rewritten
// to a hopeful URL or dropped, because such a link exists only because a site build
// used to publish the whole tree -- it is exactly what the exclusions break, and
// the reader deserves the list rather than a guess.
type unresolvedLink struct {
File string
Line int
Target string
// Why names what is wrong, because the two cases need different repairs: a
// target the set holds back is published or unlinked, and a fragment that
// matches no heading is a broken citation to fix in the prose.
Why string
}
func (u unresolvedLink) Error() string {
return fmt.Sprintf("%s:%d: %s: %s", u.File, u.Line, u.Target, u.Why)
}
// Reasons a link cannot be carried.
const (
whyTargetAbsent = "its target is not in the published set"
whyAnchorAbsent = "the target page has no such heading"
)
// headingSlugs lists the ids a page's headings produce, by the same rule a
// Markdown renderer's table of contents uses: lowercase, punctuation dropped,
// whitespace runs collapsed to one hyphen, and a repeated heading suffixed in
// order. An explicit {#id} wins, because that is what it is for.
func headingSlugs(body string) map[string]bool {
slugs := map[string]bool{}
counts := map[string]int{}
for line := range strings.Lines(body) {
trimmed := strings.TrimSpace(line)
hashes := 0
for hashes < len(trimmed) && trimmed[hashes] == '#' {
hashes++
}
if hashes == 0 || hashes == len(trimmed) || trimmed[hashes] != ' ' {
continue
}
title := strings.TrimSpace(trimmed[hashes:])
if open := strings.LastIndex(title, "{#"); open >= 0 && strings.HasSuffix(title, "}") {
slugs[strings.TrimSuffix(title[open+2:], "}")] = true
continue
}
slug := slugify(title)
if slug == "" {
continue
}
if counts[slug] > 0 {
slug = fmt.Sprintf("%s_%d", slug, counts[slug])
}
counts[strings.SplitN(slug, "_", 2)[0]]++
slugs[slug] = true
}
return slugs
}
// slugify is the table-of-contents id for one heading.
func slugify(title string) string {
var b strings.Builder
pending := false
for _, r := range strings.ToLower(title) {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_':
if pending && b.Len() > 0 {
b.WriteByte('-')
}
pending = false
b.WriteRune(r)
case unicode.IsSpace(r):
pending = true
}
}
return b.String()
}
// linkResolver rewrites one page's intra-docs links to the urls the artifact
// carries. It uses the same path-to-url rule as the pages themselves, so a link
// and the page it points at cannot disagree; only the anchor is carried over
// unchanged.
func linkResolver(relative string, urls map[string]string, slugs map[string]map[string]bool, sourceDir string) func(string) (string, string) {
dir := path.Dir(relative)
return func(target string) (string, string) {
if target == "" {
return "", whyTargetAbsent
}
// Anchors and anything with a scheme are not this tool's to resolve.
if strings.HasPrefix(target, "#") || strings.Contains(target, "://") ||
strings.HasPrefix(target, "mailto:") || strings.HasPrefix(target, "//") {
return target, ""
}
linkPath, anchor, _ := strings.Cut(target, "#")
fragment := ""
if anchor != "" {
fragment = "#" + anchor
}
resolved := path.Clean(path.Join(dir, linkPath))
if strings.HasSuffix(resolved, ".md") {
url, ok := urls[resolved]
if !ok {
return "", whyTargetAbsent
}
// A fragment that matches no heading lands the reader at the top of a
// long document with no indication why, so it is a finding rather than
// a pass: the target resolving is not the same as the citation working.
if anchor != "" && !slugs[resolved][anchor] {
return "", whyAnchorAbsent
}
return url + fragment, ""
}
// An asset is served at its own path under the public base, whichever set
// links to it: docs/public/ is one file set, and serving one file under two
// paths would invent a second location for it.
if !heldBack(resolved) {
if _, err := os.Stat(filepath.Join(sourceDir, filepath.FromSlash(resolved))); err == nil {
return publicDocs.URLPrefix + resolved + fragment, ""
}
}
return "", whyTargetAbsent
}
}
// resolveLinks rewrites every intra-docs link in body and reports the ones whose
// target neither set carries. Code is skipped, span and block alike: what a
// Markdown renderer draws as a link is the only thing this tool may rewrite, and
// the only thing it may refuse a page for.
func resolveLinks(relative, body string, urls map[string]string, slugs map[string]map[string]bool, sourceDir string) (string, []unresolvedLink) {
resolve := linkResolver(relative, urls, slugs, sourceDir)
var unresolved []unresolvedLink
lines := strings.Split(body, "\n")
inFence := false
for index, line := range lines {
if fenceDelimiter.MatchString(line) {
inFence = !inFence
continue
}
if inFence {
continue
}
var rewritten strings.Builder
end := 0
for _, match := range intraDocsLink.FindAllStringSubmatchIndex(maskCode(line), -1) {
target := line[match[2]:match[3]]
replacement, why := resolve(target)
if why != "" {
unresolved = append(unresolved, unresolvedLink{File: relative, Line: index + 1, Target: target, Why: why})
continue
}
rewritten.WriteString(line[end:match[2]])
rewritten.WriteString(replacement)
end = match[3]
}
if end == 0 {
continue
}
rewritten.WriteString(line[end:])
lines[index] = rewritten.String()
}
return strings.Join(lines, "\n"), unresolved
}
// readPages reads the source of every page either set carries, keyed by its path
// relative to docs/.
//
// The page list comes from the commit, not from the working tree: see
// sourcePages for why that distinction is the whole of this function's contract.
func readPages(repoRoot, sourceDir string) (map[string]string, error) {
relativePaths, err := sourcePages(repoRoot, sourceDir)
if err != nil {
return nil, err
}
bodies := map[string]string{}
for _, relative := range relativePaths {
if !published(relative) {
continue
}
body, err := os.ReadFile(filepath.Join(sourceDir, relative))
if err != nil {
return nil, fmt.Errorf("read %s: %w", relative, err)
}
bodies[relative] = string(body)
}
if len(bodies) == 0 {
return nil, fmt.Errorf("no published pages under %s", docsDir)
}
return bodies, nil
}
// sourcePages lists the published candidate pages, relative to docs/, choosing
// git over a directory walk whenever git can answer.
//
// The artifacts are committed beside their sources, so each one must be derived
// from the files the commit carries. A walk also sees an UNTRACKED page -- one no
// commit holds -- and then reported the artifact as stale, which sent the reader
// to regenerate an artifact that was already correct and would have committed a
// page belonging to no commit. That happened twice in one session, once to a
// migration branch and once to an unrelated writer staging a new PRD.
//
// The index counts as well as HEAD, deliberately: a page staged for this commit
// is about to be carried by it, so the artifact must include it and check must
// fail until it does. Only a file in neither tree is ignored -- and that is
// exactly the working-tree scratch this exists to exclude.
//
// Outside a git work tree there is no commit to disagree with, so the walk is
// the best answer available and is used unchanged, with a line saying so rather
// than a silence that reads as the stronger guarantee.
func sourcePages(repoRoot, sourceDir string) ([]string, error) {
pages, err := trackedPages(repoRoot, sourceDir)
if err == nil {
return pages, nil
}
fmt.Fprintf(os.Stderr, "docsite: %v; falling back to a directory walk, which cannot tell an untracked page from a committed one\n", err)
return walkedPages(sourceDir)
}
// trackedPages asks git for the .md files under docs/ that the index or HEAD
// carries.
func trackedPages(repoRoot, sourceDir string) ([]string, error) {
rel, err := filepath.Rel(repoRoot, sourceDir)
if err != nil {
return nil, fmt.Errorf("locate %s under %s: %w", docsDir, repoRoot, err)
}
rel = filepath.ToSlash(rel)
// -z because a path may contain anything but NUL; --cached so a page staged
// for this commit counts.
//
// A background context, deliberately rather than by omission: docsite is a
// short-lived CLI whose whole job is one synchronous git call, so there is no
// cancellation to propagate -- threading a context through load, write and
// check would add eight signatures to serve a rule whose subject is a request
// that can be abandoned. If docsite ever grows a long operation, the context
// becomes real and belongs in its signature.
out, err := exec.CommandContext(context.Background(), "git", "-C", repoRoot, "ls-files", "--cached", "-z", "--", rel).Output()
if err != nil {
return nil, fmt.Errorf("git ls-files %s: %w", rel, err)
}
var pages []string
for _, entry := range strings.Split(string(out), "\x00") {
if entry == "" {
continue
}
relative := strings.TrimPrefix(entry, rel+"/")
if relative == entry || !strings.HasSuffix(relative, ".md") {
continue
}
pages = append(pages, relative)
}
if len(pages) == 0 {
return nil, fmt.Errorf("git ls-files %s listed no Markdown", rel)
}
return pages, nil
}
// walkedPages is the gitless enumeration: every .md under the tree, tracked or
// not.
func walkedPages(sourceDir string) ([]string, error) {
var pages []string
err := filepath.WalkDir(sourceDir, func(filename string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
return nil
}
relative, err := filepath.Rel(sourceDir, filename)
if err != nil {
return err
}
pages = append(pages, filepath.ToSlash(relative))
return nil
})
if err != nil {
return nil, fmt.Errorf("walk %s: %w", docsDir, err)
}
return pages, nil
}
// setDocument pairs one set with the artifact generated for it.
type setDocument struct {
Set docSet
Document document
}
// load reads every published page and derives each set's sidebar from the layout,
// which keeps the directory-derived route stable: a page added under a
// directory appears without a second edit anywhere. Both sets are built in one
// pass over one url map, so a link that crosses between them resolves to the
// base its target is served under.
func load(repoRoot string) ([]setDocument, error) {
sourceDir := filepath.Join(repoRoot, docsDir)
bodies, err := readPages(repoRoot, sourceDir)
if err != nil {
return nil, err
}
// Every page's url first, so a link resolves against the whole set rather than
// against whatever the walk had reached.
urls := make(map[string]string, len(bodies))
slugs := make(map[string]map[string]bool, len(bodies))
for relative, body := range bodies {
urls[relative] = pageURL(relative)
slugs[relative] = headingSlugs(body)
}
pages := map[string][]page{}
var unresolved []unresolvedLink
for relative, body := range bodies {
resolved, missing := resolveLinks(relative, body, urls, slugs, sourceDir)
unresolved = append(unresolved, missing...)
set := setFor(relative)
pages[set.Name] = append(pages[set.Name], page{
URL: urls[relative],
Title: pageTitle(relative, body),
Section: sectionFor(relative),
Body: resolved,
})
}
if len(unresolved) > 0 {
sort.Slice(unresolved, func(i, j int) bool {
if unresolved[i].File != unresolved[j].File {
return unresolved[i].File < unresolved[j].File
}
return unresolved[i].Line < unresolved[j].Line
})
problems := make([]string, 0, len(unresolved))
for _, link := range unresolved {
problems = append(problems, link.Error())
}
return nil, fmt.Errorf(
"%d link(s) cannot be carried; see each reason:\n %s",
len(unresolved), strings.Join(problems, "\n "))
}
generated := make([]setDocument, 0, len(sets))
for _, set := range sets {
entries := pages[set.Name]
if len(entries) == 0 {
return nil, fmt.Errorf("no pages in the %s set", set.Name)
}
sort.Slice(entries, func(i, j int) bool { return entries[i].URL < entries[j].URL })
generated = append(generated, setDocument{
Set: set,
Document: document{Pages: entries, Nav: navFor(entries, set.URLPrefix)},
})
}
return generated, nil
}
// pageURL is the directory-style path a static site produces for one source file,
// under the base of the set the file belongs to: docs/index.md is the public
// root, docs/a/index.md is a section's own landing page, and docs/a/b.md is a page
// inside it.
func pageURL(relative string) string {
prefix := setFor(relative).URLPrefix
if relative == "index.md" {
return prefix
}
dir, file := path.Split(relative)
if file == "index.md" {
return prefix + dir // path.Split keeps the trailing slash
}
return prefix + dir + strings.TrimSuffix(file, ".md") + "/"
}
// pageTitle is the page's own first heading, which is the title its author chose,
// falling back to its file name so a page without one is never nameless.
func pageTitle(relative, body string) string {
for line := range strings.Lines(body) {
if heading, ok := strings.CutPrefix(strings.TrimSpace(line), "# "); ok {
if title := strings.TrimSpace(heading); title != "" {
return title
}
}
}
return readableName(strings.TrimSuffix(path.Base(relative), ".md"))
}
// sectionFor is the group a page belongs to: its first directory, titled. A page
// directly under docs/ has no section, because it is not in one.
func sectionFor(relative string) string {
segments := strings.Split(relative, "/")
if len(segments) < 2 {
return ""
}
return readableName(segments[0])
}
// acronyms are directory names whose natural label is not title case, so a
// sidebar does not read "Prds".
var acronyms = map[string]string{"prds": "PRDs"}
// readableName turns a directory or file name into a label.
func readableName(name string) string {
if label, ok := acronyms[name]; ok {
return label
}
words := strings.FieldsFunc(name, func(r rune) bool { return r == '-' || r == '_' })
for i, word := range words {
words[i] = strings.ToUpper(word[:1]) + word[1:]
}
return strings.Join(words, " ")
}
// navFor derives the sidebar tree from the pages. At each level the landing page
// comes first and the rest follow alphabetically, so a reader meets the section's
// own page before its children -- the order a static site's navigation uses.
func navFor(pages []page, urlPrefix string) []navNode {
type node struct {
title string
url string
children map[string]*node
}
root := &node{children: map[string]*node{}}
for _, entry := range pages {
segments := strings.Split(strings.Trim(strings.TrimPrefix(entry.URL, urlPrefix), "/"), "/")
current := root
for _, segment := range segments {
if segment == "" {
continue
}
child, ok := current.children[segment]
if !ok {
child = &node{title: readableName(segment), children: map[string]*node{}}
current.children[segment] = child
}
current = child
}
if current == root {
// The root index: the site's home, listed at the top of the sidebar.
root.title, root.url = entry.Title, entry.URL
continue
}
current.url, current.title = entry.URL, entry.Title
}
var render func(*node) []navNode
render = func(parent *node) []navNode {
names := make([]string, 0, len(parent.children))
for name := range parent.children {
names = append(names, name)
}
sort.Strings(names)
// A directory whose own index is published: the section's landing page
// leads with its link, then its children.
var nodes []navNode
for _, name := range names {
child := parent.children[name]
entry := navNode{Title: child.title}
if child.url != "" {
entry.URL = child.url
}
entry.Items = render(child)
// A directory is a group whether it holds one page or twenty: the tree
// mirrors the layout a reader sees, and collapsing a one-page directory
// into a bare link would be a shape this artifact invented rather than
// one it reports.
nodes = append(nodes, entry)
}
return nodes
}
var nav []navNode
if root.url != "" {
nav = append(nav, navNode{Title: root.title, URL: root.url})
}
return append(nav, render(root)...)
}
// marshal renders the artifact. Indented and newline-terminated so a diff reads
// as a change to a page rather than a change to one line.
func marshal(doc document) ([]byte, error) {
encoded, err := json.MarshalIndent(doc, "", " ")
if err != nil {
return nil, fmt.Errorf("encode artifact: %w", err)
}
return append(encoded, '\n'), nil
}
// write regenerates every artifact, leaving a file untouched when its bytes
// already match so a no-op run does not churn the tree.
func write(repoRoot string) error {
generated, err := load(repoRoot)
if err != nil {
return err
}
for _, entry := range generated {
if err := writeSet(repoRoot, entry); err != nil {
return err
}
}
return nil
}
func writeSet(repoRoot string, entry setDocument) error {
artifactPath := entry.Set.ArtifactPath
encoded, err := marshal(entry.Document)
if err != nil {
return err
}
target := filepath.Join(repoRoot, artifactPath)
existing, err := os.ReadFile(target)
if err == nil && bytes.Equal(existing, encoded) {
fmt.Printf("docsite: %s is up to date\n", artifactPath)
return nil
}
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("read %s: %w", artifactPath, err)
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return fmt.Errorf("create %s: %w", filepath.Dir(artifactPath), err)
}
if err := os.WriteFile(target, encoded, 0o644); err != nil {
return fmt.Errorf("write %s: %w", artifactPath, err)
}
fmt.Printf("docsite: wrote %s (%d pages)\n", artifactPath, len(entry.Document.Pages))
return nil
}
// check regenerates in memory and compares, so a source edit that has not been
// reflected in a committed artifact fails without the tree being touched.
func check(repoRoot string) error {
generated, err := load(repoRoot)
if err != nil {
return err
}
for _, entry := range generated {
if err := checkSet(repoRoot, entry); err != nil {
return err
}
}
return nil
}
const regenerate = "regenerate it by running `go -C tools run ./docsite --repo-root ..` from the tools module"
func checkSet(repoRoot string, entry setDocument) error {
artifactPath := entry.Set.ArtifactPath
expected, err := marshal(entry.Document)
if err != nil {
return err
}
committed, err := os.ReadFile(filepath.Join(repoRoot, artifactPath))
if errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("%s is missing; %s", artifactPath, regenerate)
}
if err != nil {
return fmt.Errorf("read %s: %w", artifactPath, err)
}
if !bytes.Equal(expected, committed) {
return fmt.Errorf("%s is stale; %s", artifactPath, regenerate)
}
fmt.Printf("docsite: %s is up to date (%d pages)\n", artifactPath, len(entry.Document.Pages))
return nil
}
+2 -32
View File
@@ -2,77 +2,47 @@ module github.com/samcharles93/archie-core/tools
go 1.27.0
require (
github.com/invopop/jsonschema v0.14.0
github.com/samcharles93/archie-core v0.0.0-20260922071806-cd2ab7f2cbfe
)
require (
cel.dev/expr v0.25.3 // indirect
filippo.io/edwards25519 v1.1.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.5.1 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.6.1 // indirect
github.com/cloudflare/circl v1.6.5 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/cubicdaiya/gonp v1.0.4 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/go-git/gcfg/v2 v2.0.2 // indirect
github.com/go-git/go-billy/v6 v6.0.0-alpha.2 // indirect
github.com/go-git/go-git/v6 v6.0.0-alpha.5 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/google/cel-go v0.28.0 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.11.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/kevinburke/ssh_config v1.6.0 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/modelcontextprotocol/go-sdk v1.8.0 // indirect
github.com/ncruces/go-sqlite3 v0.32.0 // indirect
github.com/ncruces/julianday v1.0.0 // indirect
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
github.com/pingcap/log v1.1.0 // indirect
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/riza-io/grpc-go v0.2.0 // indirect
github.com/samcharles93/ai-sdk v0.1.39 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/sqlc-dev/doubleclick v1.0.0 // indirect
github.com/sqlc-dev/sqlc v1.31.1 // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/tetratelabs/wazero v1.11.0 // indirect
github.com/traefik/yaegi v0.16.1 // indirect
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect
golang.org/x/crypto v0.57.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
golang.org/x/net v0.59.0 // indirect
golang.org/x/oauth2 v0.37.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
golang.org/x/time v0.16.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect
google.golang.org/grpc v1.85.0-dev.0.20260825072537-93e31b48545e // indirect
-171
View File
@@ -1,103 +1,31 @@
cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw=
filippo.io/edwards25519 v1.1.1/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Azure/go-ansiterm v0.0.0-20260917205352-e937bb47801a h1:4hxax9ktNjSDoFn1tZSeL6gXMTRMpO0FzjdKfT01jgY=
github.com/Azure/go-ansiterm v0.0.0-20260917205352-e937bb47801a/go.mod h1:3EWSSOZ50kb+arhww0qIaEXHToib/3FjBj9Jj5lcP5g=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.5.1 h1:pTrLDQHyOT8y3DFYIpijgPBTw/7E2GLMimutvOlceuE=
github.com/ProtonMail/go-crypto v1.5.1/go.mod h1:/RaSu30DaKO4RY+XdV/ACcCcZkGr7AhUIduq5sjzzCo=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/log v0.2.0 h1:BewD/umNgVnoczglOpX8eRMyEy5t5iPlu5AIpnWDONc=
github.com/containerd/log v0.2.0/go.mod h1:/M7L7CXKcPTfNC74XzaK+5H5KbO5+4lJVpuVI6vRLoM=
github.com/containerd/platforms v1.0.0-rc.5 h1:vXd569rDrz8LeMXzAnBsy6LADV5YtsD8oyaRarxdmSU=
github.com/containerd/platforms v1.0.0-rc.5/go.mod h1:lKlMXyLybmBedS/JJm11uDofzI8L2v0J2ZbYvNsbq1A=
github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cubicdaiya/gonp v1.0.4 h1:ky2uIAJh81WiLcGKBVD5R7KsM/36W6IqqTy6Bo6rGws=
github.com/cubicdaiya/gonp v1.0.4/go.mod h1:iWGuP/7+JVTn02OWhRemVbMmG1DOUnmrGTYYACpOI0I=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M=
github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs=
github.com/go-git/go-billy/v6 v6.0.0-alpha.2 h1:1Sv5WemXL8CxKrAx1gioJ+uHNb2bZJhiQLfwSZ4Et8c=
github.com/go-git/go-billy/v6 v6.0.0-alpha.2/go.mod h1:r/bsv9i/iDyyEU8/Z6mjC+YraOVwie1ddfUqBCElKXQ=
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4sbjHwwlhktMw0DUg3mA=
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE=
github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/cel-go v0.28.0 h1:KjSWstCpz/MN5t4a8gnGJNIYUsJRpdi/r97xWDphIQc=
github.com/google/cel-go v0.28.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -108,12 +36,6 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY=
github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
@@ -121,42 +43,10 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 h1:eveIIGn4BGM3qknO74omf6HYr30/exH+eVUTuAgwjZ0=
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/magiconair/properties v1.18.12 h1:sT9zQpvTB3B4gzrX0tmZNTEaGyg8Zw55MFYRE32Mr9I=
github.com/magiconair/properties v1.18.12/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.3.3 h1:OxxR9paxsluYi+zDUEXTTaIxtkK3viymW+Ka7vRhhME=
github.com/moby/go-archive v0.3.3/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE=
github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ=
github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs=
github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ=
github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0=
github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y=
github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8=
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-sqlite3 v0.32.0 h1:hNBUXp88LrfQCsuyXLqWTbTUG35sUuktDsqhhgHvU20=
github.com/ncruces/go-sqlite3 v0.32.0/go.mod h1:MIWTK60ONDl0oVY073zYvJP21C3Dly6P9bxVpgkLwdQ=
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ=
github.com/pganalyze/pg_query_go/v6 v6.2.2 h1:O0L6zMC226R82RF3X5n0Ki6HjytDsoAzuzp4ATVAHNo=
github.com/pganalyze/pg_query_go/v6 v6.2.2/go.mod h1:Cn6+j4870kJz3iYNsb0VsNG04vpSWgEvBwc590J4qD0=
github.com/pingcap/errors v0.11.0/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
@@ -168,35 +58,13 @@ github.com/pingcap/log v1.1.0 h1:ELiPxACz7vdo1qAvvaWJg1NrYFoY6gqAh/+Uo6aXdD8=
github.com/pingcap/log v1.1.0/go.mod h1:DWQW5jICDR7UJh4HtxXSM20Churx4CQL0fwL/SoOSA4=
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 h1:zYmP5fBH+i2yhhU6f5uOol6zxHtR2/sD47BsJLfy0oU=
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124/go.mod h1:zDLDsfNBU5+L6T4J9/OgWAHc/WZvMUjbpgHqQ/t3yKo=
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 h1:XA01Vk/wv9YikCi1V51yRzIHPMT5of9+cMpZoZvDn/M=
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/pressly/goose/v3 v3.28.0 h1:D2M+iL31GmpZxSHOhX8mqyqAT3CXnokUmm0eKoSP+Vc=
github.com/pressly/goose/v3 v3.28.0/go.mod h1:v26MOuB8bL3kzzrt3Vqhb3R0PRVsl8hFQKdrht/L6Rk=
github.com/riza-io/grpc-go v0.2.0 h1:2HxQKFVE7VuYstcJ8zqpN84VnAoJ4dCL6YFhJewNcHQ=
github.com/riza-io/grpc-go v0.2.0/go.mod h1:2bDvR9KkKC3KhtlSHfR3dAXjUMT86kg4UfWFyVGWqi8=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/samcharles93/ai-sdk v0.1.39 h1:gbNPYeA27MifReCruBiqMgb4fFSjCDi1Zv57a9bo0Vo=
github.com/samcharles93/ai-sdk v0.1.39/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/shirou/gopsutil/v4 v4.26.8 h1:YQMTF/1J50B5+Y0vlo1eDRf5DoR7Gk69hY+8wjYkQeo=
github.com/shirou/gopsutil/v4 v4.26.8/go.mod h1:5O9FjBiXoTDFatIWjZZosqj4pV0DRtLx598xGbBehzM=
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
@@ -212,36 +80,12 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 h1:8fdv/9y3JMxjQ+ULAcOG8RtgeNu5t9XF9LolSXDuTwM=
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0/go.mod h1:CFr2LncGYokw+OKjXcr8ARCKG1SaC2UEnGxFBovE86g=
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 h1:mJdDDPblDfPe7z7go8Dvv1AJQDI3eQ/5xith3q2mFlo=
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07/go.mod h1:Ak17IJ037caFp4jpCw/iQQ7/W74Sqpb1YuKJU6HTKfM=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 h1:OvLBa8SqJnZ6P+mjlzc2K7PM22rRUPE1x32G9DTPrC4=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52/go.mod h1:jMeV4Vpbi8osrE/pKUxRZkVaA0EX7NZN0A9/oRzgpgY=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
@@ -260,11 +104,7 @@ go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=
go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU=
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
@@ -272,27 +112,18 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
@@ -306,7 +137,6 @@ google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fw
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
@@ -314,7 +144,6 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-160
View File
@@ -1,160 +0,0 @@
package main
import (
"fmt"
"regexp"
"strings"
)
// Finding is one rule violation, addressed the way an editor reads it.
type Finding struct {
File string
Line int
Rule string
Text string
}
func (f Finding) String() string {
return fmt.Sprintf("%s:%d: %s: %s", f.File, f.Line, f.Rule, strings.TrimSpace(f.Text))
}
// rule is one forbidden shape. Each rejects writing whose truth expires while
// the sentence around it still reads as current.
type rule struct {
name string
pattern *regexp.Regexp
remedy string
}
// datedVerbs are the words that turn a date into a status claim. A date on
// its own is provenance; a date next to one of these is a progress report.
const datedVerbs = `(status|resolved|settled|decided|agreed|approved|supersedes|superseded|withdrawn|shipped|landed|complete|completed|done|wired|verified|corrected|confirmed)`
// rules is the closed set. Each pattern targets a shape that decays, never a
// topic: a PRD may discuss phases, dates and shipped work, and says so without
// asserting the state of the tree on the day it was written.
var rules = []rule{
{
name: "line-citation",
pattern: regexp.MustCompile(`\.(go|md|ya?ml|toml|proto|ts|js|sql):\d+|\blines? \d+(-\d+)?\b`),
remedy: "cite the file and the symbol, not the line. Line numbers move on the next edit above them and the stale citation still reads as authoritative. This covers a document citing its own line numbers.",
},
{
name: "dated-status",
pattern: regexp.MustCompile(`(?i)\b` + datedVerbs + `\b[^.\n]{0,30}\b20\d\d-\d\d-\d\d\b|\b20\d\d-\d\d-\d\d\b[^.\n]{0,30}\b` + datedVerbs + `\b|\b(surveyed|queried|measured|checked|reviewed|correction|per [A-Z]\w+)\b[^.\n]{0,20}\b20\d\d-\d\d-\d\d\b`),
remedy: "drop the date and the state. A PRD says what the design is; the tracker and git history say when it happened.",
},
{
name: "progress-claim",
pattern: regexp.MustCompile(`(?i)\b(not yet|already|now|currently|today)\s+(wired|built|implemented|shipped|landed|complete)\b|\bis (now|already) \w+ed\b|\bready to (implement|design|build)\b|\bas of (today|this writing)\b`),
remedy: "state the design, not its build state. \"X is not yet wired\" is true for one week and misleading afterwards. Naming a dependency that exists is evidence and stays; reporting progress on the work this document designs does not.",
},
{
name: "phase-progress",
pattern: regexp.MustCompile(`(?i)\bphases?\s+\d[^.\n]{0,40}\b(complete|completed|done|shipped|landed|in progress|underway|remaining)\b|\b(complete|completed|done|shipped|landed|in progress)\b[^.\n]{0,20}\bphases?\s+\d`),
remedy: "a phased plan is durable design; which phase is finished is not. Name the phases, not their state.",
},
{
name: "temporal-hedge",
pattern: regexp.MustCompile(`(?i)\b(today|currently|right now|at present|at the moment|as things stand|for now)\b`),
remedy: "\"today\" dates the sentence to the day it was written, so the claim it qualifies is false the moment the design lands. Describe the shape being replaced without asserting it is the present.",
},
{
name: "stale-cross-reference",
pattern: regexp.MustCompile(`(?i)\bthis (bullet|section|document|doc|paragraph|note) (previously|originally|earlier)\b|\b(an?|the) earlier (draft|note|version|section) of this\b|\bthe earlier (draft|note|version)\b|\bpreviously said\b|\bused to say\b`),
remedy: "a reader cannot see what the document used to say, so the reference resolves to nothing. State the current decision; git history holds the rest. A supersede marker is fine when it names a file, a section or a symbol the reader can find.",
},
{
name: "session-artefact",
pattern: regexp.MustCompile(`(?i)\b(crew investigation|investigation pass|not committed|caught in review|this session|at time of writing|in this session)\b`),
remedy: "how the finding was produced is not design. State what is true and the evidence for it.",
},
}
// codeFence tracks fenced blocks so a rule never fires on quoted sample output
// or a code listing, where a line number or a status string may be the literal
// content being specified.
var codeFence = regexp.MustCompile("^\\s*```")
// exemptHeader matches the two metadata fields that carry a status and a date
// by design (RULES.md gives three statuses). The match is deliberately narrow:
// a Date field holding only a date, and a Status field holding only one of the
// three. A wider exemption let "**Date:** 2026-09-03, Channel resolved
// 2026-09-22" smuggle a dated status into the one line the rules did not read.
var exemptHeader = regexp.MustCompile(`^\*\*Date:\*\*\s*20\d\d-\d\d-\d\d\s*$|^\*\*Status:\*\*\s*(Draft|Approved|Finalised)\s*$`)
// statusField matches a status line anywhere in the document, indented or
// not. The indent matters: a whole second PRD nested inside a list item
// carried its own indented status, and an anchored pattern never saw it.
var statusField = regexp.MustCompile(`^\s*\*\*Status:\*\*\s*(.*)$`)
// statuses is the closed set from RULES.md. A status outside it is how a
// progress report gets into the one field the rules cannot read: "Implemented
// (wiring landed)" and "Ratified (rev. 2e). Rev. 2e adds..." were both really
// changelogs.
var statuses = map[string]bool{"Draft": true, "Approved": true, "Finalised": true}
// statusRemedy is the status rule's fix. It is not in rules because the check
// is document-level: a missing field has no line to point at.
const statusRemedy = "every PRD carries exactly one of Draft, Approved or Finalised. Anything else is a progress report in the one field the other rules exempt."
// LintDocument reports every violation in a whole document: the status the
// document must declare, then each line.
func LintDocument(name, content string) []Finding {
return append(lintStatus(name, content), Lint(name, content)...)
}
// Lint reports every line-level rule violation in one document.
func Lint(name, content string) []Finding {
var findings []Finding
inFence := false
lines := strings.Split(content, "\n")
for i, line := range lines {
if codeFence.MatchString(line) {
inFence = !inFence
continue
}
if inFence || exemptHeader.MatchString(line) {
continue
}
for _, r := range rules {
if r.pattern.MatchString(line) {
findings = append(findings, Finding{File: name, Line: i + 1, Rule: r.name, Text: line})
continue
}
// Prose wraps, so a citation can straddle a line break ("...lines"
// / "155-159, ..."). Re-test the pair, reporting the line the
// match starts on.
if i+1 < len(lines) && !inFence && r.pattern.MatchString(line+" "+strings.TrimSpace(lines[i+1])) {
findings = append(findings, Finding{File: name, Line: i + 1, Rule: r.name, Text: line + " " + strings.TrimSpace(lines[i+1])})
}
}
}
return findings
}
// lintStatus checks the one status line RULES.md requires, since a missing or
// free-text status is not a line-level violation any pattern above would see.
func lintStatus(name, content string) []Finding {
var findings []Finding
var seen int
for i, line := range strings.Split(content, "\n") {
m := statusField.FindStringSubmatch(line)
if m == nil {
continue
}
seen++
switch {
case seen > 1:
// One document, one status. A second one means a second document
// has been pasted inside this one, which is the real defect.
findings = append(findings, Finding{File: name, Line: i + 1, Rule: "status", Text: "second **Status:** field; a nested document belongs in its own file"})
case !statuses[strings.TrimSpace(m[1])]:
findings = append(findings, Finding{File: name, Line: i + 1, Rule: "status", Text: line})
}
}
if seen == 0 {
return []Finding{{File: name, Line: 1, Rule: "status", Text: "no **Status:** field"}}
}
return findings
}
-107
View File
@@ -1,107 +0,0 @@
// Command prdlint rejects session-bound writing in docs/prds.
//
// A PRD states a decision, a requirement, a constraint, or evidence
// (docs/prds/RULES.md). Those survive the code moving underneath them. A line
// number, a progress report, or a dated status claim does not: it is true on
// the day it is written and silently wrong a month later, while still reading
// as authoritative. The tracker records progress; the PRD records the design.
package main
import (
"errors"
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// defaultDir is the directory prdlint governs, relative to the repository root.
const defaultDir = "docs/prds"
func main() {
flags := flag.NewFlagSet("prdlint", flag.ContinueOnError)
flags.SetOutput(io.Discard)
repoRoot := flags.String("repo-root", "..", "path to the Archie repository root")
dir := flags.String("dir", defaultDir, "directory to lint, relative to the repository root")
if err := flags.Parse(os.Args[1:]); err != nil {
fmt.Fprintf(os.Stderr, "prdlint: %v\n", err)
os.Exit(2)
}
if extra := flags.Args(); len(extra) > 0 {
fmt.Fprintf(os.Stderr, "prdlint: unexpected argument %q\n", extra[0])
os.Exit(2)
}
findings, err := lintDir(filepath.Join(*repoRoot, *dir))
if err != nil {
fmt.Fprintf(os.Stderr, "prdlint: %v\n", err)
os.Exit(2)
}
if len(findings) == 0 {
fmt.Printf("prdlint: %s carries no session-bound writing\n", *dir)
return
}
for _, f := range findings {
fmt.Fprintln(os.Stderr, f.String())
}
fmt.Fprintf(os.Stderr, "\nprdlint: %d finding(s). A PRD outlives the code it describes:\n%s\n",
len(findings), strings.Join(remedies(findings), "\n"))
os.Exit(1)
}
// lintDir lints every Markdown file in dir, skipping RULES.md: it is the rule
// text itself and quotes the shapes the rules forbid.
func lintDir(dir string) ([]Finding, error) {
entries, err := os.ReadDir(dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("%s does not exist", dir)
}
if err != nil {
return nil, err
}
var findings []Finding
names := make([]string, 0, len(entries))
for _, e := range entries {
if e.IsDir() || filepath.Ext(e.Name()) != ".md" || e.Name() == "RULES.md" {
continue
}
names = append(names, e.Name())
}
sort.Strings(names)
for _, name := range names {
data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
return nil, err
}
findings = append(findings, LintDocument(name, string(data))...)
}
return findings, nil
}
// remedies renders each triggered rule's fix once, in rule order, so the
// output ends with instructions rather than repeating them per finding.
func remedies(findings []Finding) []string {
seen := map[string]bool{}
var out []string
for _, f := range findings {
if f.Rule == "status" && !seen["status"] {
seen["status"] = true
out = append(out, " status: "+statusRemedy)
}
}
for _, r := range rules {
for _, f := range findings {
if f.Rule == r.name && !seen[r.name] {
seen[r.name] = true
out = append(out, " "+r.name+": "+r.remedy)
}
}
}
return out
}
-262
View File
@@ -1,262 +0,0 @@
#!/usr/bin/env python3
"""reachaudit -- report completion state, not just intent.
Trackers record intention ("build a cron job store"). Nothing records whether
that intention is already written but executing nowhere. This walks the tree,
finds code that no shipped binary can reach, and attributes each finding to its
package with provenance and tracker status, so "is it implemented?" and "is it
reachable?" are separate answerable questions.
Categories, deliberately distinct because their actions differ:
unreachable-tracked planned and partially built -- a status, not a bug
unreachable-untracked genuinely dead, and invisible to every tracker
unreachable-dynamic invisible to static analysis by design (yaegi or
reflection), do not delete
reachable in a shipped binary
Usage:
python3 reachaudit.py [--repo PATH] [--json OUT] [--md OUT]
Advisory only. It never proposes deletion; it reports state.
"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
# Modules that load code at RUNTIME, so static reachability cannot see them.
# Findings inside these are labelled, never presented as dead.
DYNAMIC_MARKERS = ("yaegi", "go:linkname", "reflect.ValueOf")
# Tracker terms that mean "this subsystem is planned". Matched case-insensitively
# against open issue titles. Coverage is an INPUT to classification, not a
# conclusion -- tracked-and-unreachable is a legitimate status.
TRACKER_HINTS = {
"cronstore": ["cron"],
"domain/scheduling": ["cron", "schedul"],
"servicediscovery": ["service discovery", "servicediscovery"],
"memory/scrubber": ["scrub", "replay", "transcript"],
"pairing": ["pairing", "device auth"],
"domain/sampling": ["sampling", "embedding"],
"configuration/tomlwrite": ["setup", "toml", "config"],
"configuration/setup": ["setup", "first-run", "config generation"],
"terminalprompt": ["setup", "prompt"],
"domain/image": ["image"],
"ratelimit": ["rate limit", "ratelimit", "throttl"],
}
def run(cmd: list[str], cwd: Path) -> str:
return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True).stdout.strip()
def cmd_closure(repo: Path) -> set[str]:
"""Packages compiled into a shipped binary. A package absent from this set
cannot execute in production, whatever deadcode says about its functions."""
out = run(["go", "list", "-deps", "./cmd/..."], repo)
prefix = "github.com/samcharles93/archie-core/"
return {l[len(prefix):] for l in out.splitlines() if l.startswith(prefix)}
def deadcode_findings(repo: Path) -> list[str]:
"""Run deadcode, or reuse a cached run. Falls back to an empty list with a
loud warning rather than silently reporting zero findings."""
head = run(["git", "rev-parse", "HEAD"], repo) or "unknown"
dirty = "-dirty" if run(["git", "status", "--porcelain"], repo) else ""
cache = Path(f"/tmp/reachaudit-deadcode-{head[:12]}{dirty}.txt")
if cache.exists() and not dirty:
return cache.read_text().splitlines()
print("running deadcode (this compiles the module, may take a minute)...", file=sys.stderr)
out = subprocess.run(
["go", "run", "golang.org/x/tools/cmd/deadcode@latest", "./..."],
cwd=repo, capture_output=True, text=True,
).stdout
if not out.strip():
print("WARNING: deadcode returned nothing; report will be empty", file=sys.stderr)
cache.write_text(out)
return out.splitlines()
def open_tracker_titles(repo: Path) -> list[str]:
titles = []
gh = run(["gh", "issue", "list", "--state", "open", "--limit", "400",
"--json", "title", "--jq", ".[].title"], repo)
titles += [t for t in gh.splitlines() if t]
bd = run(["bd", "list", "--status", "open"], repo)
titles += [t for t in bd.splitlines() if t]
return titles
def dynamic_packages(repo: Path) -> set[str]:
"""Packages that reference runtime-loaded code."""
out = run(["grep", "-rl", "-E", "|".join(DYNAMIC_MARKERS),
"--include=*.go", "internal/", "cmd/"], repo)
return {f.rsplit("/", 1)[0] if "/" in f else f for f in out.splitlines()}
def tracked_terms(short_pkg: str) -> list[str]:
for key, terms in TRACKER_HINTS.items():
if key in short_pkg:
return terms
tail = short_pkg.split("/")[-1]
return [tail]
def provenance(repo: Path, pkg: str) -> dict:
added = run(["git", "log", "--diff-filter=A", "--format=%ad", "--date=short", "--", pkg], repo)
first = added.splitlines()[-1] if added else "?"
last = run(["git", "log", "-1", "--format=%ad|%h|%s", "--date=short", "--", pkg], repo)
parts = last.split("|") if last else ["?", "?", "?"]
return {"added": first, "last_date": parts[0], "last_sha": parts[1],
"last_subject": parts[2][:70] if len(parts) > 2 else ""}
def loc(repo: Path, pkg: str) -> int:
out = run(["bash", "-c", f"find {pkg} -maxdepth 1 -name '*.go' -exec cat {{}} + 2>/dev/null | wc -l"], repo)
try:
return int(out)
except ValueError:
return 0
def consumers(repo: Path, pkg: str) -> tuple[int, int]:
"""(non-test importers, test importers) outside the package itself."""
out = run(["grep", "-rl", f"archie-core/{pkg}\"", "--include=*.go", "."], repo)
files = [f for f in out.splitlines() if f and f.lstrip("./").rstrip("/") != pkg]
files = [f for f in files if not f.startswith(f"./{pkg}/")]
nt = [f for f in files if not f.endswith("_test.go")]
return len(nt), len(files) - len(nt)
def classify(repo: Path, pkg: str, titles: list[str], dyn: set[str]) -> tuple[str, list[str]]:
"""Shared classification: tracked / untracked / dynamic, plus the tracker
titles that matched. Used for both whole-package and in-package findings
so a symbol inside a live package is judged by the same evidence as a
whole dead one."""
terms = tracked_terms(pkg)
hits = [t for t in titles if any(term.lower() in t.lower() for term in terms)]
is_dynamic = any(pkg.startswith(d) or d.startswith(pkg) for d in dyn)
if is_dynamic:
return "dynamic", hits
if hits:
return "tracked", hits
return "untracked", hits
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--repo", default=str(Path(__file__).resolve().parents[2]))
ap.add_argument("--json")
ap.add_argument("--md")
ap.add_argument("--refresh", action="store_true", help="re-run deadcode instead of using the cache")
args = ap.parse_args()
repo = Path(args.repo)
if args.refresh:
Path("/tmp/reachaudit-deadcode.txt").unlink(missing_ok=True)
closure = cmd_closure(repo)
if not closure:
print("ERROR: go list returned no packages; is this a Go module?", file=sys.stderr)
return 1
findings = deadcode_findings(repo)
titles = open_tracker_titles(repo)
dyn = dynamic_packages(repo)
by_pkg_syms: dict[str, list[str]] = defaultdict(list)
for line in findings:
m = re.match(r"^(.+?):\d+:\d+: unreachable func: (.+)$", line)
if m:
by_pkg_syms[str(Path(m.group(1)).parent)].append(m.group(2))
if not by_pkg_syms:
print("WARNING: no findings parsed; deadcode output format may have changed", file=sys.stderr)
# Whole packages absent from the cmd closure: the package cannot execute
# at all, whatever deadcode says about individual functions inside it.
rows = []
for pkg, syms in sorted(by_pkg_syms.items(), key=lambda kv: -len(kv[1])):
if pkg in closure:
continue
category, hits = classify(repo, pkg, titles, dyn)
nt, tt = consumers(repo, pkg)
rows.append({
"package": pkg, "findings": len(syms), "loc": loc(repo, pkg),
"category": f"unreachable-{category}",
"non_test_importers": nt, "test_importers": tt,
"tracker_hits": hits[:3],
**provenance(repo, pkg),
})
# Functions unreachable INSIDE a package that IS in the closure: the
# package ships, but this symbol is the unwired tail of a feature --
# the ChatCourier/Dispatch shape, not a dead whole package. This is the
# half-built-feature case the whole-package report structurally cannot
# see, since the package itself looks perfectly live.
in_pkg_rows = []
for pkg, syms in sorted(by_pkg_syms.items(), key=lambda kv: -len(kv[1])):
if pkg not in closure:
continue
category, hits = classify(repo, pkg, titles, dyn)
in_pkg_rows.append({
"package": pkg, "symbols": sorted(syms),
"category": f"in-package-{category}",
"tracker_hits": hits[:3],
})
order = {"unreachable-untracked": 0, "unreachable-dynamic": 1, "unreachable-tracked": 2}
rows.sort(key=lambda r: (order.get(r["category"], 9), -r["loc"]))
in_pkg_order = {"in-package-untracked": 0, "in-package-dynamic": 1, "in-package-tracked": 2}
in_pkg_rows.sort(key=lambda r: (in_pkg_order.get(r["category"], 9), -len(r["symbols"])))
total = sum(r["loc"] for r in rows)
lines = []
lines.append(f"packages reachable from shipped binaries: {len(closure)}")
lines.append(f"deadcode findings total: {len(findings)}")
lines.append(f"unreachable packages: {len(rows)}")
lines.append(f"unreachable LOC: {total}")
lines.append("")
for cat in ("unreachable-untracked", "unreachable-dynamic", "unreachable-tracked"):
group = [r for r in rows if r["category"] == cat]
if not group:
continue
lines.append(f"== {cat} ({len(group)}) ==")
for r in group:
lines.append(f" {r['loc']:>6} LOC {r['package']}")
for hit in r["tracker_hits"] or ["NONE"]:
lines.append(f" {hit}")
lines.append("")
for cat in ("in-package-untracked", "in-package-dynamic", "in-package-tracked"):
group = [r for r in in_pkg_rows if r["category"] == cat]
if not group:
continue
lines.append(f"== {cat} ({len(group)}) -- package ships, these symbols do not ==")
for r in group:
tr = "; ".join(r["tracker_hits"]) or "NONE"
lines.append(f" {r['package']} ({tr})")
for sym in r["symbols"]:
lines.append(f" {sym}")
lines.append("")
print("\n".join(lines))
if args.json:
Path(args.json).write_text(json.dumps({
"rows": rows, "in_package_rows": in_pkg_rows,
"total_loc": total, "closure_size": len(closure),
}, indent=2))
print(f"wrote {args.json}")
if args.md:
md = ["# reachaudit", "", "```", *lines, "```", ""]
Path(args.md).write_text("\n".join(md))
print(f"wrote {args.md}")
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -2
View File
@@ -7,8 +7,7 @@
# exactly that, silently -- and with more than one agent working in its own
# worktree, each could "pass" while producing a different bundle.
#
# So this builds somewhere temporary and compares, the rule docs:check already
# follows for docs/data/generated/contracts.json. A mismatch means ui/src
# So this builds somewhere temporary and compares. A mismatch means ui/src
# changed without `task ui`, or the bundle was hand-edited; the fix is the same
# either way.
set -euo pipefail