chore: cleanup

This commit is contained in:
sam committed 2026-07-29 02:10:44 +10:00
1 parent 65aa5b462d
commit d1bbd37d95
56 files changed
+8781 -78

No files matched your search

+32 -14
View File
@@ -13,16 +13,16 @@ import (
"strings"
"github.com/invopop/jsonschema"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/gateway"
"gopkg.in/yaml.v3"
)
func main() {
repoRoot := flag.String("repo-root", "..", "path to the Archie repository root")
out := flag.String(
"out",
"docs-2/reference/generated/agent-contracts.yaml",
"docs-2/data/generated/contracts.json",
"output path relative to the repository root",
)
flag.Parse()
@@ -47,11 +47,7 @@ func run(repoRoot, outPath string) error {
}
schemas := map[string]any{}
types := map[string]reflect.Type{
"AgentExecutionRequest": reflect.TypeFor[agentexec.Request](),
"AgentExecutionResult": reflect.TypeFor[agentexec.Result](),
"MessageEvent": reflect.TypeFor[gateway.MessageEvent](),
}
types := currentContractTypes()
names := make([]string, 0, len(types))
for name := range types {
names = append(names, name)
@@ -64,10 +60,17 @@ func run(repoRoot, outPath string) error {
}
rewriteDefRefs(schemas)
body, err := yaml.Marshal(map[string]any{"schemas": 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 schemas: %w", err)
return fmt.Errorf("marshal documentation data: %w", err)
}
body = append(body, '\n')
destination := outPath
if !filepath.IsAbs(destination) {
@@ -76,8 +79,7 @@ func run(repoRoot, outPath string) error {
if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil {
return fmt.Errorf("create output directory: %w", err)
}
header := []byte("# Code generated by tools/docsgen. DO NOT EDIT.\n")
if err := os.WriteFile(destination, append(header, body...), 0o644); err != nil {
if err := os.WriteFile(destination, body, 0o644); err != nil {
return fmt.Errorf("write %s: %w", destination, err)
}
@@ -85,6 +87,18 @@ func run(repoRoot, outPath string) error {
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 {
@@ -108,7 +122,7 @@ func collectSchema(
t reflect.Type,
) error {
if _, exists := schemas[name]; exists {
return nil
return fmt.Errorf("duplicate published schema name %q", name)
}
raw, err := json.Marshal(reflector.ReflectFromType(t))
if err != nil {
@@ -124,9 +138,13 @@ func collectSchema(
delete(tree, "$id")
schemas[name] = tree
for defName, defSchema := range defs {
if _, exists := schemas[defName]; !exists {
schemas[defName] = defSchema
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
}
+215
View File
@@ -1,11 +1,75 @@
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/invopop/jsonschema"
)
type contractWithConflictingDefinition struct {
Value conflictingDefinition `json:"value"`
}
type conflictingDefinition struct {
Value string `json:"value"`
}
func TestRunWritesDeterministicContractData(t *testing.T) {
repoRoot := filepath.Clean("../..")
outputDir := t.TempDir()
outputs := []string{
filepath.Join(outputDir, "first.json"),
filepath.Join(outputDir, "second.json"),
}
for _, output := range outputs {
if err := run(repoRoot, output); err != nil {
t.Fatalf("run(%q) error = %v", output, err)
}
}
first, err := os.ReadFile(outputs[0])
if err != nil {
t.Fatalf("read first output: %v", err)
}
second, err := os.ReadFile(outputs[1])
if err != nil {
t.Fatalf("read second output: %v", err)
}
if !bytes.Equal(first, second) {
t.Fatal("repeated generation produced different bytes")
}
var data struct {
GeneratedBy string `json:"generatedBy"`
Schemas map[string]json.RawMessage `json:"schemas"`
}
if err := json.Unmarshal(first, &data); err != nil {
t.Fatalf("decode generated data: %v", err)
}
if data.GeneratedBy != "tools/docsgen" {
t.Fatalf("generatedBy = %q, want %q", data.GeneratedBy, "tools/docsgen")
}
for _, name := range []string{
"AgentExecutionRequest",
"AgentExecutionResult",
"MessageEvent",
} {
if _, ok := data.Schemas[name]; !ok {
t.Errorf("schemas[%q] is missing", name)
}
}
for name, schema := range data.Schemas {
assertSchemaRefsResolve(t, name, schema, data.Schemas)
}
}
func TestRunHonoursAbsoluteOutputPath(t *testing.T) {
repoRoot := filepath.Clean("../..")
outputDir := t.TempDir()
@@ -31,3 +95,154 @@ func TestRunHonoursAbsoluteOutputPath(t *testing.T) {
t.Fatalf("working directory = %q, want %q", currentDir, originalDir)
}
}
func TestCollectSchemaRejectsDuplicatePublishedName(t *testing.T) {
reflector := &jsonschema.Reflector{ExpandedStruct: true}
schemas := map[string]any{}
const name = "PublishedContract"
if err := collectSchema(reflector, schemas, name, reflect.TypeFor[struct {
First string `json:"first"`
}]()); err != nil {
t.Fatalf("collect first schema: %v", err)
}
err := collectSchema(reflector, schemas, name, reflect.TypeFor[struct {
Second int `json:"second"`
}]())
if err == nil {
t.Fatal("collect duplicate schema returned nil error")
}
}
func TestCollectSchemaRejectsConflictingDefinition(t *testing.T) {
reflector := &jsonschema.Reflector{ExpandedStruct: true}
schemas := map[string]any{
"conflictingDefinition": map[string]any{"type": "integer"},
}
err := collectSchema(
reflector,
schemas,
"PublishedContract",
reflect.TypeFor[contractWithConflictingDefinition](),
)
if err == nil {
t.Fatal("collect conflicting definition returned nil error")
}
if !strings.Contains(err.Error(), `conflicting schema definition "conflictingDefinition"`) {
t.Fatalf("collect conflicting definition error = %q", err)
}
}
func TestRunReportsFilesystemAndSourceErrors(t *testing.T) {
repoRoot := filepath.Clean("../..")
blocker := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(blocker, []byte("occupied"), 0o600); err != nil {
t.Fatalf("create blocker: %v", err)
}
tests := []struct {
name string
root string
output string
contains string
}{
{
name: "missing source tree",
root: t.TempDir(),
output: filepath.Join(t.TempDir(), "contracts.json"),
contains: "load Go comments",
},
{
name: "output parent is a file",
root: repoRoot,
output: filepath.Join(blocker, "contracts.json"),
contains: "create output directory",
},
{
name: "output is a directory",
root: repoRoot,
output: t.TempDir(),
contains: "write ",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := run(test.root, test.output)
if err == nil {
t.Fatal("run() returned nil error")
}
if !bytes.Contains([]byte(err.Error()), []byte(test.contains)) {
t.Fatalf("run() error = %q, want substring %q", err, test.contains)
}
})
}
}
func TestRewriteRef(t *testing.T) {
tests := map[string]string{
"definition": "#/schemas/Contract",
"external": "https://example.com/schema.json",
"empty name": "#/$defs/",
}
for name, want := range tests {
t.Run(name, func(t *testing.T) {
input := want
if name == "definition" {
input = "#/$defs/Contract"
}
if got := rewriteRef(input); got != want {
t.Fatalf("rewriteRef(%q) = %q, want %q", input, got, want)
}
})
}
}
func assertSchemaRefsResolve(
t *testing.T,
name string,
raw json.RawMessage,
schemas map[string]json.RawMessage,
) {
t.Helper()
var value any
if err := json.Unmarshal(raw, &value); err != nil {
t.Fatalf("decode schema %q: %v", name, err)
}
walkJSON(value, func(ref string) {
const prefix = "#/schemas/"
if !strings.HasPrefix(ref, "#") {
return
}
if !strings.HasPrefix(ref, prefix) {
t.Errorf("schema %q contains unresolved local reference %q", name, ref)
return
}
target := ref[len(prefix):]
if _, ok := schemas[target]; !ok {
t.Errorf("schema %q references missing schema %q", name, target)
}
})
}
func walkJSON(value any, visitRef func(string)) {
switch node := value.(type) {
case map[string]any:
for key, child := range node {
if key == "$ref" {
if ref, ok := child.(string); ok {
visitRef(ref)
}
continue
}
walkJSON(child, visitRef)
}
case []any:
for _, child := range node {
walkJSON(child, visitRef)
}
}
}
+1 -1
View File
@@ -5,7 +5,6 @@ go 1.26.4
require (
github.com/invopop/jsonschema v0.14.0
github.com/samcharles93/archie-core v0.0.0-00010101000000-000000000000
gopkg.in/yaml.v3 v3.0.1
)
require (
@@ -25,6 +24,7 @@ require (
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/sys v0.46.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace github.com/samcharles93/archie-core => ../