feat(cli): bd schema — JSON Schema for --json/export output (carries #4413, griels) (#5098)

* Add `bd schema` command emitting JSON Schema for output records

`bd schema` reflects the canonical issue/dependency output structs
(internal/types) into a JSON Schema via invopop/jsonschema, so consumers can
codegen typed models (datamodel-code-generator, quicktype, ...) instead of
hand-mirroring the --json / export format. Because the schema is generated from
the same structs bd serializes, it cannot drift from the actual output the way
docs/JSON_SCHEMA.md or a downstream consumer model (e.g. beads-mcp's Pydantic
models) can. Output carries schema_version (== JSONSchemaVersion).

Promotes invopop/jsonschema from an indirect to a direct dependency.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 2bb8d2c305)

* Enumerate status/type/dependency values in `bd schema` + add tests

- Add canonical AllStatuses / AllIssueTypes / AllDependencyTypes lists to
  internal/types and derive Status.IsValid / IssueType.IsValid from them, so
  validation and the schema enums share one source (behaviour-preserving;
  internal/types tests pass).
- `bd schema` now enriches the status, issue_type, and dependency `type`
  fields with their allowed values via a jsonschema Mapper sourced from those
  lists, so the published schema constrains them instead of emitting a bare
  "string" — exactly the constraint hand-mirrored consumers can't track.
- Extract schemaDocument() so the command is unit-testable without a workspace
  or DB; add cmd/bd/schema_test.go asserting valid JSON, schema_version, the
  issue/dependency records, required fields, and the populated enums.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 9beb73d023)

* Fix misspell + regenerate CLI docs for `bd schema`

- internal/types: "recognises" -> "recognizes" (misspell lint).
- Regenerate docs/CLI_REFERENCE.md, the website CLI reference pages, and
  llms-full.txt to cover the new `bd schema` command (via
  scripts/generate-cli-docs.sh + generate-llms-full.sh from a canonical
  pure-go build). The CLI-docs freshness gate now passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 1cd9be76c6)

* fixup: errcheck on outputJSONRaw, godoc placement, go.mod tidy for bd schema

- cmd/bd/schema.go: switch schemaCmd.Run to RunE and return the
  outputJSONRaw error instead of discarding it, matching the
  return-outputJSON(...) pattern used elsewhere in cmd/bd (e.g.
  branch.go, audit.go, comment.go).
- internal/types/types.go: reorder the AllIssueTypes var and its
  godoc so each comment sits directly above its own declaration; the
  cherry-picked var block had split IsValid's godoc comment across
  the inserted var.
- go.mod: go mod tidy after the cherry-picked invopop/jsonschema
  v0.14.0 direct-require resolution; drops the now-unneeded
  mailru/easyjson indirect entry.

Agent-Signature: claude-code-sonnet-medium on behalf of matt wilkie

* fix(schema): skip store init — the command reflects static types only

Without skipStoreAnnotation, bd schema ran the PersistentPreRunE store open
and failed outside a workspace or on a CGO-less build, defeating the
command's storage-free design.

Agent-Signature: claude-fable-5-medium on behalf of matt wilkie

---------

Co-authored-by: Ellis Breen <1263585+griels@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
matt wilkie 2026-07-27 14:16:56 -07:00 • committed by GitHub
commit ecb9e92735
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 216 additions and 12 deletions

94
cmd/bd/schema.go Normal file
View file

@ -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)
}

90
cmd/bd/schema_test.go Normal file
View file

@ -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)
}
}
}

2
go.mod
View file

@ -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

View file

@ -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.