beads/cmd/bd/config_nodb_embedded_test.go
Kevin Glynn 0d4b979354
feat: JSON schema contract, bd ping, structured errors, import enhancements (#3368)
* feat: add schema_version to all --json output (beads-5uh)

All bd commands that emit --json output now include a schema_version
field so consumers (Jawnt MCP, BeadsX, gt mail, sync scripts) can
detect format changes without silently breaking.

- Object output: schema_version injected as top-level field
- Array output: wrapped as {"schema_version": 1, "items": [...]}
- Error output: schema_version added to stderr JSON

Central implementation in outputJSON() via wrapWithSchemaVersion()
means all 272 call sites get the field automatically.

Includes:
- Unit tests for wrapping logic (object, struct, slice, nil, roundtrip)
- Updated protocol contract tests for new envelope format
- New schema_version presence test across list/ready/show
- docs/JSON_SCHEMA.md documenting the field contract per command

* feat: add ready/blocked JSON contract tests (beads-clt)

bd ready --json and bd blocked --json already return full issue objects
with dependency counts and blocked_by fields. Add protocol contract
tests to pin this behavior:

- TestJSONContract_ReadyOutputHasFullObjects: verifies dependency_count,
  dependent_count fields on ready items
- TestJSONContract_BlockedOutputHasBlockedBy: verifies blocked_by and
  blocked_by_count fields on blocked items

Update docs/JSON_SCHEMA.md with blocked output contract.

* feat: add bd ping lightweight health-check command (beads-8cc)

New minimal command that confirms bd can reach its database:
1. Resolves the .beads workspace
2. Opens the store (embedded or server)
3. Runs a trivial query (SearchIssues with Limit=1)
4. Reports timing breakdown

Supports --json for structured output with resolve_ms, store_ms,
query_ms, and total_ms fields. Exit 0 on success, 1 on failure.

Registered as read-only command (no auto-push, no file writes).
Includes protocol contract test for JSON output.

* feat: structured JSON errors on stderr when --json active (beads-06n)

All fatal error functions (FatalError, FatalErrorWithHint,
FatalErrorRespectJSON, FatalErrorWithHintRespectJSON) now emit
structured JSON with schema_version when --json is active:

  {"schema_version": 1, "error": "message", "hint": "optional"}

Centralized via jsonStderrError() and jsonStdoutError() helpers.
Replaces ad-hoc json.MarshalIndent calls scattered across error
functions with a consistent, schema-versioned format.

Includes unit tests and updated protocol contract test verifying
schema_version presence in error JSON output.

* feat: enhance bd import with stdin, --dedup, --json (beads-c6i)

Enhance the existing bd import command for bulk JSONL ingest:

- Stdin support: bd import - reads JSONL from stdin for piped workflows
- --dedup flag: skips lines whose title matches an existing open issue
  (case-insensitive) to prevent duplicate creation
- --json flag: structured output with created/skipped counts and IDs

Refactored import to use runImportFromReader() for unified file/stdin
handling. Added filterDuplicatesByTitle() for dedup logic. Updated
docs/JSON_SCHEMA.md with import output contract.

Backward compatible: existing bd import [file] and --dry-run work
exactly as before.

* fix: update tests for schema_version envelope in JSON output

Three test files expected raw JSON arrays or map[string]string, which
broke when schema_version (a number) was added to the output envelope:

- ado_test.go: parse envelope with items array instead of raw []json.RawMessage
- bootstrap_embedded_test.go: use map[string]interface{} for mixed types
- where_embedded_test.go: same map[string]interface{} fix

* fix: drop array envelope wrapping to fix 200+ test failures

The schema_version envelope was wrapping arrays as
{"schema_version": N, "items": [...]} which broke every integration
test that parses --json array output. Objects (show, create, ping)
still get schema_version injected. Arrays (list, ready, blocked)
now pass through unchanged for backwards compatibility.

Also fixes: gofmt on import.go, doc-flags reference to bd import,
uses importIssuesCore result to satisfy unparam lint.

* fix: update remaining tests for schema_version number field

config_embedded_test.go, kv_embedded_test.go, config_nodb_embedded_test.go,
and show_test.go all parsed JSON output into map[string]string but
schema_version is a number. Parse to map[string]interface{} and
skip/assert schema_version appropriately.

---------

Co-authored-by: kev <kglynn@pryoninc.com>
2026-04-20 21:09:48 -07:00

165 lines
5.3 KiB
Go

//go:build cgo
package main
import (
"bytes"
"encoding/json"
"os"
"os/exec"
"strings"
"testing"
)
func runConfigCommandWithStreams(t *testing.T, bd, dir string, args ...string) (stdout string, stderr string, err error) {
t.Helper()
fullArgs := append([]string{"config"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
err = cmd.Run()
return stdoutBuf.String(), stderrBuf.String(), err
}
func assertNoStoreInitLeak(t *testing.T, stderr string) {
t.Helper()
for _, needle := range []string{
"database name may default incorrectly",
"failed to open database",
"no database selected",
} {
if strings.Contains(stderr, needle) {
t.Fatalf("unexpected low-level store init output %q in stderr:\n%s", needle, stderr)
}
}
}
func TestEmbeddedConfigNoWorkspaceStoreFreeCommands(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
t.Run("get_yaml_only", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "get", "no-db")
if err != nil {
t.Fatalf("config get no-db failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config get no-db, got:\n%s", stderr)
}
got := strings.TrimSpace(stdout)
if got != "false" && !strings.Contains(got, "not set in config.yaml") {
t.Fatalf("expected yaml-only config lookup result, got stdout:\n%s", stdout)
}
})
t.Run("set_yaml_only_reports_config_yaml_error", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "set", "no-db", "true")
if err == nil {
t.Fatalf("expected config set no-db to fail without a workspace config, stdout:\n%s\nstderr:\n%s", stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if !strings.Contains(stderr, "no .beads/config.yaml found") {
t.Fatalf("expected config.yaml error, got stderr:\n%s", stderr)
}
})
t.Run("show_json", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "show", "--json")
if err != nil {
t.Fatalf("config show --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config show --json, got:\n%s", stderr)
}
var payload []map[string]any
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config show --json output: %v\nstdout:\n%s", err, stdout)
}
if len(payload) == 0 {
t.Fatalf("expected config show --json to return entries, got empty payload")
}
})
t.Run("drift_json", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "drift", "--json")
if err != nil {
t.Fatalf("config drift --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config drift --json, got:\n%s", stderr)
}
var payload []map[string]any
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config drift --json output: %v\nstdout:\n%s", err, stdout)
}
if len(payload) == 0 {
t.Fatalf("expected config drift --json to return checks, got empty payload")
}
})
t.Run("apply_json", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "apply", "--json")
if err != nil {
t.Fatalf("config apply --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config apply --json, got:\n%s", stderr)
}
var payload []map[string]any
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config apply --json output: %v\nstdout:\n%s", err, stdout)
}
if len(payload) == 0 {
t.Fatalf("expected config apply --json to return results, got empty payload")
}
})
}
func TestEmbeddedConfigValidateJSONNoWorkspaceWritesStdout(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "validate", "--json")
if err == nil {
t.Fatalf("expected config validate --json to fail without a workspace, stdout:\n%s\nstderr:\n%s", stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected JSON error on stdout only, got stderr:\n%s", stderr)
}
var payload map[string]interface{}
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config validate --json output: %v\nstdout:\n%s", err, stdout)
}
if errField, _ := payload["error"].(string); errField != activeWorkspaceNotFoundError() {
t.Fatalf("error = %q, want %q", errField, activeWorkspaceNotFoundError())
}
if hint, _ := payload["hint"].(string); !strings.Contains(hint, "bd where") {
t.Fatalf("expected hint to mention bd where, got %q", hint)
}
}