diff --git a/cmd/bd/schema.go b/cmd/bd/schema.go new file mode 100644 index 000000000..1826e7a04 --- /dev/null +++ b/cmd/bd/schema.go @@ -0,0 +1,94 @@ +package main + +import ( + "reflect" + + "github.com/invopop/jsonschema" + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/types" +) + +// schemaCmd emits the JSON Schema for bd's canonical --json / export output +// record types. +// +// The schema is generated by reflection from the same internal/types structs +// that bd serializes, so by construction it cannot drift from the actual output +// the way a hand-maintained doc (docs/JSON_SCHEMA.md) or a downstream consumer +// model (e.g. beads-mcp's Pydantic models) can. The named string enums (status, +// issue_type, dependency type) are enriched with their allowed values, sourced +// from the same internal/types lists that validation uses. The emitted +// schema_version matches JSONSchemaVersion and bumps with it. +// +// Consumers can codegen typed models from this output (datamodel-code-generator +// for Python/Pydantic, quicktype, etc.) instead of hand-mirroring the format. +var schemaCmd = &cobra.Command{ + Use: "schema", + Short: "Print the JSON Schema for bd's --json / export output", + // The schema is reflected from static Go types; no store is needed, and + // opening one would make this fail outside a workspace (or on a CGO-less + // build) for no reason. + Annotations: map[string]string{skipStoreAnnotation: "1"}, + Long: `Print the JSON Schema for bd's canonical output record types. + +The schema is reflected from the same Go structs bd serializes, so it stays in +lockstep with the actual --json / export output. Use it to generate typed +consumer models (datamodel-code-generator, quicktype, ...) rather than +hand-maintaining them. + + bd schema | jq '.types.issue' # the issue record schema + bd schema | jq '.types.dependency' # the dependency record schema`, + RunE: func(cmd *cobra.Command, args []string) error { + // Raw: the document carries its own schema_version; do not double-wrap + // it in the --json envelope. + return outputJSONRaw(schemaDocument()) + }, +} + +// schemaDocument builds the JSON Schema document for bd's canonical output +// record types. Split out from the command so it can be unit-tested without a +// workspace or database. +func schemaDocument() map[string]interface{} { + reflector := &jsonschema.Reflector{ + // Inline referenced types so each record schema is self-contained and + // directly consumable by codegen tools. + DoNotReference: true, + // Enrich bd's named string enums with their allowed values. + Mapper: enumMapper, + } + return map[string]interface{}{ + "schema_version": JSONSchemaVersion, + "types": map[string]*jsonschema.Schema{ + "issue": reflector.Reflect(&types.Issue{}), + "dependency": reflector.Reflect(&types.Dependency{}), + }, + } +} + +// enumMapper maps bd's named string enum types to a string schema enumerating +// their allowed values, so the published schema constrains them instead of +// emitting a bare "string". Values come from the canonical internal/types lists +// that validation also consults, so the schema cannot drift from them. +func enumMapper(t reflect.Type) *jsonschema.Schema { + switch t { + case reflect.TypeOf(types.Status("")): + return stringEnum(types.AllStatuses) + case reflect.TypeOf(types.IssueType("")): + return stringEnum(types.AllIssueTypes) + case reflect.TypeOf(types.DependencyType("")): + return stringEnum(types.AllDependencyTypes) + } + return nil +} + +func stringEnum[T ~string](values []T) *jsonschema.Schema { + enum := make([]any, len(values)) + for i, v := range values { + enum[i] = string(v) + } + return &jsonschema.Schema{Type: "string", Enum: enum} +} + +func init() { + rootCmd.AddCommand(schemaCmd) +} diff --git a/cmd/bd/schema_test.go b/cmd/bd/schema_test.go new file mode 100644 index 000000000..839a6f01f --- /dev/null +++ b/cmd/bd/schema_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "encoding/json" + "testing" +) + +// TestSchemaDocument verifies `bd schema` emits a valid JSON Schema document +// pinned to JSONSchemaVersion, with the issue/dependency record schemas and the +// enriched string enums sourced from internal/types. It exercises the pure +// schemaDocument() builder, so it needs no workspace or database. +func TestSchemaDocument(t *testing.T) { + raw, err := json.Marshal(schemaDocument()) + if err != nil { + t.Fatalf("marshal schema document: %v", err) + } + var doc map[string]any + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatalf("schema document is not valid JSON: %v", err) + } + + if got, ok := doc["schema_version"].(float64); !ok || int(got) != JSONSchemaVersion { + t.Errorf("schema_version = %v, want %d", doc["schema_version"], JSONSchemaVersion) + } + + recordTypes, ok := doc["types"].(map[string]any) + if !ok { + t.Fatalf("types missing or wrong shape: %T", doc["types"]) + } + + // --- issue record --- + issue := objectField(t, recordTypes, "issue") + mustContain(t, "issue.required", strSlice(issue["required"]), "id", "title") + issueProps := objectField(t, issue, "properties") + for _, p := range []string{"id", "title", "status", "priority", "issue_type"} { + if _, ok := issueProps[p]; !ok { + t.Errorf("issue schema missing property %q", p) + } + } + mustContain(t, "issue.status.enum", propEnum(t, issueProps, "status"), "open", "closed") + mustContain(t, "issue.issue_type.enum", propEnum(t, issueProps, "issue_type"), "bug", "task", "epic") + + // --- dependency record --- + dep := objectField(t, recordTypes, "dependency") + depProps := objectField(t, dep, "properties") + for _, p := range []string{"issue_id", "depends_on_id", "type"} { + if _, ok := depProps[p]; !ok { + t.Errorf("dependency schema missing property %q", p) + } + } + mustContain(t, "dependency.type.enum", propEnum(t, depProps, "type"), "blocks", "parent-child") +} + +func objectField(t *testing.T, m map[string]any, key string) map[string]any { + t.Helper() + obj, ok := m[key].(map[string]any) + if !ok { + t.Fatalf("%q missing or not an object: %T", key, m[key]) + } + return obj +} + +func propEnum(t *testing.T, props map[string]any, name string) []string { + t.Helper() + return strSlice(objectField(t, props, name)["enum"]) +} + +func strSlice(v any) []string { + arr, _ := v.([]any) + out := make([]string, 0, len(arr)) + for _, x := range arr { + if s, ok := x.(string); ok { + out = append(out, s) + } + } + return out +} + +func mustContain(t *testing.T, label string, got []string, want ...string) { + t.Helper() + set := make(map[string]bool, len(got)) + for _, g := range got { + set[g] = true + } + for _, w := range want { + if !set[w] { + t.Errorf("%s = %v, missing %q", label, got, w) + } + } +} diff --git a/go.mod b/go.mod index 89d1fd051..3d98e318e 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,7 @@ require ( github.com/dolthub/driver/v2 v2.2.0 github.com/dolthub/eventkit v0.0.0-20260611184414-99f5693e696a github.com/go-sql-driver/mysql v1.10.0 + github.com/invopop/jsonschema v0.14.0 github.com/olebedev/when v1.1.0 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 @@ -42,7 +43,6 @@ require ( github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cockroachdb/apd/v3 v3.2.3 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/invopop/jsonschema v0.14.0 // indirect github.com/moby/moby/api v1.54.2 // indirect github.com/moby/moby/client v0.4.0 // indirect github.com/pb33f/ordered-map/v2 v2.3.1 // indirect diff --git a/internal/types/types.go b/internal/types/types.go index 557bdae39..d6bb3d86b 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -420,13 +420,17 @@ const ( StatusHooked Status = "hooked" // Work actively claimed by a worker ) +// AllStatuses lists the built-in issue statuses (excludes custom statuses). It +// is the single source consulted by Status.IsValid and the `bd schema` enum, so +// adding a status here surfaces it in both validation and the published schema. +var AllStatuses = []Status{ + StatusOpen, StatusInProgress, StatusBlocked, StatusDeferred, + StatusClosed, StatusPinned, StatusHooked, +} + // IsValid checks if the status value is valid (built-in statuses only) func (s Status) IsValid() bool { - switch s { - case StatusOpen, StatusInProgress, StatusBlocked, StatusDeferred, StatusClosed, StatusPinned, StatusHooked: - return true - } - return false + return slices.Contains(AllStatuses, s) } // IsValidWithCustom checks if the status is valid, including custom statuses. @@ -637,16 +641,19 @@ const TypeEvent IssueType = "event" // - event: set-state audit trail beads (GH#1356) // (message was re-promoted to built-in for inter-agent communication — GH#1347.) +// AllIssueTypes lists the built-in issue types (excludes TypeEvent and custom +// types, matching IssueType.IsValid). Single source for IsValid and the +// `bd schema` enum. +var AllIssueTypes = []IssueType{ + TypeBug, TypeFeature, TypeTask, TypeEpic, TypeChore, TypeDecision, + TypeMessage, TypeMolecule, TypeGate, TypeSpike, TypeStory, TypeMilestone, +} + // IsValid checks if the issue type is a core work type. // Core work types (bug, feature, task, epic, chore, decision, message, spike, story, milestone) // and internal types (molecule, gate) are built-in. Other types require types.custom configuration. func (t IssueType) IsValid() bool { - switch t { - case TypeBug, TypeFeature, TypeTask, TypeEpic, TypeChore, TypeDecision, TypeMessage, TypeMolecule, - TypeGate, TypeSpike, TypeStory, TypeMilestone: - return true - } - return false + return slices.Contains(AllIssueTypes, t) } // IsBuiltIn returns true for core work types and system-internal types @@ -942,6 +949,19 @@ const ( DepDelegatedFrom DependencyType = "delegated-from" // Work delegated from parent; completion cascades up ) +// AllDependencyTypes lists the built-in dependency types, in declaration order. +// Single source for the `bd schema` enum so the published schema enumerates +// exactly the types bd recognizes. +var AllDependencyTypes = []DependencyType{ + DepBlocks, DepParentChild, DepConditionalBlocks, DepWaitsFor, + DepRelated, DepDiscoveredFrom, + DepRepliesTo, DepRelatesTo, DepDuplicates, DepSupersedes, + DepAuthoredBy, DepAssignedTo, DepApprovedBy, DepAttests, + DepTracks, + DepUntil, DepCausedBy, DepValidates, + DepDelegatedFrom, +} + // IsValid checks if the dependency type value is valid. // Accepts any non-empty string up to 50 characters. // Use IsWellKnown() to check if it's a built-in type.