beads/cmd/bd/errors.go

181 lines
5.2 KiB
Go
Raw Permalink Normal View History

package main
import (
"encoding/json"
"fmt"
"os"
)
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183) * fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-11 13:23:14 +09:00
func activeWorkspaceNotFoundError() string {
return "no active beads workspace found"
}
func activeWorkspaceNotFoundMessage() string {
return "No active beads workspace found."
}
// diagHint returns the appropriate diagnostic hint when the active beads
// workspace cannot be resolved. In embedded mode, 'bd doctor' is not
// available so the hint omits it.
func diagHint() string {
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183) * fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-11 13:23:14 +09:00
return workspaceDiagHint(true)
}
func whereDiagHint() string {
return workspaceDiagHint(false)
}
func workspaceDiagHint(includeWhere bool) string {
if includeWhere {
if isEmbeddedMode() {
return "run 'bd where' to inspect the resolved workspace, or 'bd init' to create a new database"
}
return "run 'bd where' to inspect the resolved workspace, run 'bd doctor' to diagnose, or 'bd init' to create a new database"
}
if isEmbeddedMode() {
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183) * fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-11 13:23:14 +09:00
return "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database"
}
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183) * fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-11 13:23:14 +09:00
return "check BEADS_DIR/worktree setup, run 'bd doctor' to diagnose, or run 'bd init' to create a new database"
}
feat: BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping (#3393) * feat: add BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping Follow-up to #3368 as discussed with @maphew. Adds the envelope format that wraps all --json output as {"schema_version": N, "data": <payload>}, gated behind BD_JSON_ENVELOPE=1 to avoid breaking existing consumers. Legacy mode (default): unchanged behavior from #3368 — objects get schema_version injected inline, arrays pass through raw. Envelope mode (BD_JSON_ENVELOPE=1): uniform wrapping for all types. The original payload is untouched inside .data — no type corruption, no field injection. A one-time deprecation notice is emitted to stderr when --json is used without the env var. Timeline: envelope becomes default in v2.0, with BD_JSON_ENVELOPE=0 as a temporary escape hatch for one release cycle. Includes: - wrapWithSchemaVersion dual-mode logic - outputJSONError and buildJSONError envelope support - Deprecation notice on stderr (once per process) - Tests for both legacy and envelope modes - Migration guide in docs/JSON_SCHEMA.md * fix: suppress deprecation notice when stderr is not a TTY Gate emitEnvelopeDeprecation() on ui.IsStderrTerminal() so the "NOTE: bd --json output format will change in v2.0" message only appears in interactive terminals. Test harnesses and pipelines capture stderr via CombinedOutput(), and the trailing notice after the JSON closing brace caused json.Unmarshal to fail with "invalid character 'N' after top-level value" in 15 CI tests. Follows the same TTY-gating pattern used by ShouldUseColor and ShouldUseEmoji. * fix: suppress gosec G304 false positive in hookWorkTreeRoot The path is filepath.Join(os.Getenv("GIT_DIR"), "gitdir") — reading a well-known git internal file from a trusted environment variable set by git itself during hook execution. Not a user-controlled file inclusion. This false positive causes the Lint CI check to fail on every PR in the repo, masking real lint issues.
2026-04-21 16:24:17 -04:00
// buildJSONError constructs a JSON error object respecting envelope mode.
func buildJSONError(message, hint string) interface{} {
inner := map[string]interface{}{
"error": message,
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-21 00:09:48 -04:00
}
if hint != "" {
feat: BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping (#3393) * feat: add BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping Follow-up to #3368 as discussed with @maphew. Adds the envelope format that wraps all --json output as {"schema_version": N, "data": <payload>}, gated behind BD_JSON_ENVELOPE=1 to avoid breaking existing consumers. Legacy mode (default): unchanged behavior from #3368 — objects get schema_version injected inline, arrays pass through raw. Envelope mode (BD_JSON_ENVELOPE=1): uniform wrapping for all types. The original payload is untouched inside .data — no type corruption, no field injection. A one-time deprecation notice is emitted to stderr when --json is used without the env var. Timeline: envelope becomes default in v2.0, with BD_JSON_ENVELOPE=0 as a temporary escape hatch for one release cycle. Includes: - wrapWithSchemaVersion dual-mode logic - outputJSONError and buildJSONError envelope support - Deprecation notice on stderr (once per process) - Tests for both legacy and envelope modes - Migration guide in docs/JSON_SCHEMA.md * fix: suppress deprecation notice when stderr is not a TTY Gate emitEnvelopeDeprecation() on ui.IsStderrTerminal() so the "NOTE: bd --json output format will change in v2.0" message only appears in interactive terminals. Test harnesses and pipelines capture stderr via CombinedOutput(), and the trailing notice after the JSON closing brace caused json.Unmarshal to fail with "invalid character 'N' after top-level value" in 15 CI tests. Follows the same TTY-gating pattern used by ShouldUseColor and ShouldUseEmoji. * fix: suppress gosec G304 false positive in hookWorkTreeRoot The path is filepath.Join(os.Getenv("GIT_DIR"), "gitdir") — reading a well-known git internal file from a trusted environment variable set by git itself during hook execution. Not a user-controlled file inclusion. This false positive causes the Lint CI check to fail on every PR in the repo, masking real lint issues.
2026-04-21 16:24:17 -04:00
inner["hint"] = hint
}
if jsonEnvelopeEnabled() {
return map[string]interface{}{
"schema_version": JSONSchemaVersion,
"data": inner,
}
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-21 00:09:48 -04:00
}
feat: BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping (#3393) * feat: add BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping Follow-up to #3368 as discussed with @maphew. Adds the envelope format that wraps all --json output as {"schema_version": N, "data": <payload>}, gated behind BD_JSON_ENVELOPE=1 to avoid breaking existing consumers. Legacy mode (default): unchanged behavior from #3368 — objects get schema_version injected inline, arrays pass through raw. Envelope mode (BD_JSON_ENVELOPE=1): uniform wrapping for all types. The original payload is untouched inside .data — no type corruption, no field injection. A one-time deprecation notice is emitted to stderr when --json is used without the env var. Timeline: envelope becomes default in v2.0, with BD_JSON_ENVELOPE=0 as a temporary escape hatch for one release cycle. Includes: - wrapWithSchemaVersion dual-mode logic - outputJSONError and buildJSONError envelope support - Deprecation notice on stderr (once per process) - Tests for both legacy and envelope modes - Migration guide in docs/JSON_SCHEMA.md * fix: suppress deprecation notice when stderr is not a TTY Gate emitEnvelopeDeprecation() on ui.IsStderrTerminal() so the "NOTE: bd --json output format will change in v2.0" message only appears in interactive terminals. Test harnesses and pipelines capture stderr via CombinedOutput(), and the trailing notice after the JSON closing brace caused json.Unmarshal to fail with "invalid character 'N' after top-level value" in 15 CI tests. Follows the same TTY-gating pattern used by ShouldUseColor and ShouldUseEmoji. * fix: suppress gosec G304 false positive in hookWorkTreeRoot The path is filepath.Join(os.Getenv("GIT_DIR"), "gitdir") — reading a well-known git internal file from a trusted environment variable set by git itself during hook execution. Not a user-controlled file inclusion. This false positive causes the Lint CI check to fail on every PR in the repo, masking real lint issues.
2026-04-21 16:24:17 -04:00
inner["schema_version"] = JSONSchemaVersion
return inner
}
// jsonStderrError writes a structured JSON error to stderr when --json is active.
func jsonStderrError(message, hint string) {
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-21 00:09:48 -04:00
encoder := json.NewEncoder(os.Stderr)
encoder.SetIndent("", " ")
feat: BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping (#3393) * feat: add BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping Follow-up to #3368 as discussed with @maphew. Adds the envelope format that wraps all --json output as {"schema_version": N, "data": <payload>}, gated behind BD_JSON_ENVELOPE=1 to avoid breaking existing consumers. Legacy mode (default): unchanged behavior from #3368 — objects get schema_version injected inline, arrays pass through raw. Envelope mode (BD_JSON_ENVELOPE=1): uniform wrapping for all types. The original payload is untouched inside .data — no type corruption, no field injection. A one-time deprecation notice is emitted to stderr when --json is used without the env var. Timeline: envelope becomes default in v2.0, with BD_JSON_ENVELOPE=0 as a temporary escape hatch for one release cycle. Includes: - wrapWithSchemaVersion dual-mode logic - outputJSONError and buildJSONError envelope support - Deprecation notice on stderr (once per process) - Tests for both legacy and envelope modes - Migration guide in docs/JSON_SCHEMA.md * fix: suppress deprecation notice when stderr is not a TTY Gate emitEnvelopeDeprecation() on ui.IsStderrTerminal() so the "NOTE: bd --json output format will change in v2.0" message only appears in interactive terminals. Test harnesses and pipelines capture stderr via CombinedOutput(), and the trailing notice after the JSON closing brace caused json.Unmarshal to fail with "invalid character 'N' after top-level value" in 15 CI tests. Follows the same TTY-gating pattern used by ShouldUseColor and ShouldUseEmoji. * fix: suppress gosec G304 false positive in hookWorkTreeRoot The path is filepath.Join(os.Getenv("GIT_DIR"), "gitdir") — reading a well-known git internal file from a trusted environment variable set by git itself during hook execution. Not a user-controlled file inclusion. This false positive causes the Lint CI check to fail on every PR in the repo, masking real lint issues.
2026-04-21 16:24:17 -04:00
_ = encoder.Encode(buildJSONError(message, hint))
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-21 00:09:48 -04:00
}
// jsonStdoutError writes a structured JSON error to stdout when --json is active.
// Used by FatalErrorRespectJSON and FatalErrorWithHintRespectJSON where
// callers expect errors on stdout (e.g., bd show nonexistent-id --json).
func jsonStdoutError(message, hint string) {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
feat: BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping (#3393) * feat: add BD_JSON_ENVELOPE=1 opt-in for uniform JSON wrapping Follow-up to #3368 as discussed with @maphew. Adds the envelope format that wraps all --json output as {"schema_version": N, "data": <payload>}, gated behind BD_JSON_ENVELOPE=1 to avoid breaking existing consumers. Legacy mode (default): unchanged behavior from #3368 — objects get schema_version injected inline, arrays pass through raw. Envelope mode (BD_JSON_ENVELOPE=1): uniform wrapping for all types. The original payload is untouched inside .data — no type corruption, no field injection. A one-time deprecation notice is emitted to stderr when --json is used without the env var. Timeline: envelope becomes default in v2.0, with BD_JSON_ENVELOPE=0 as a temporary escape hatch for one release cycle. Includes: - wrapWithSchemaVersion dual-mode logic - outputJSONError and buildJSONError envelope support - Deprecation notice on stderr (once per process) - Tests for both legacy and envelope modes - Migration guide in docs/JSON_SCHEMA.md * fix: suppress deprecation notice when stderr is not a TTY Gate emitEnvelopeDeprecation() on ui.IsStderrTerminal() so the "NOTE: bd --json output format will change in v2.0" message only appears in interactive terminals. Test harnesses and pipelines capture stderr via CombinedOutput(), and the trailing notice after the JSON closing brace caused json.Unmarshal to fail with "invalid character 'N' after top-level value" in 15 CI tests. Follows the same TTY-gating pattern used by ShouldUseColor and ShouldUseEmoji. * fix: suppress gosec G304 false positive in hookWorkTreeRoot The path is filepath.Join(os.Getenv("GIT_DIR"), "gitdir") — reading a well-known git internal file from a trusted environment variable set by git itself during hook execution. Not a user-controlled file inclusion. This false positive causes the Lint CI check to fail on every PR in the repo, masking real lint issues.
2026-04-21 16:24:17 -04:00
_ = encoder.Encode(buildJSONError(message, hint))
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-21 00:09:48 -04:00
}
// FatalError writes an error message to stderr and exits with code 1.
// Use this for fatal errors that prevent the command from completing.
//
// Pattern A from ERROR_HANDLING.md:
// - User input validation failures
// - Critical preconditions not met
// - Unrecoverable system errors
//
// Example:
//
// if err := store.CreateIssue(ctx, issue, actor); err != nil {
// FatalError("%v", err)
// }
func FatalError(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
if jsonOutput {
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-21 00:09:48 -04:00
jsonStderrError(msg, "")
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
}
os.Exit(1)
}
// FatalErrorRespectJSON writes an error message and exits with code 1.
// If --json flag is set, outputs structured JSON to stdout.
// Otherwise, outputs plain text to stderr.
//
// Use this for errors in commands that support --json output.
//
// Example:
//
// if err := store.GetIssue(ctx, id); err != nil {
// FatalErrorRespectJSON("%v", err)
// }
func FatalErrorRespectJSON(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
if jsonOutput {
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-21 00:09:48 -04:00
jsonStdoutError(msg, "")
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
}
os.Exit(1)
}
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183) * fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-11 13:23:14 +09:00
// FatalErrorWithHintRespectJSON writes an error message with a hint and exits.
// If --json is set, emits structured JSON to stdout so callers can parse it.
func FatalErrorWithHintRespectJSON(message, hint string) {
if jsonOutput {
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-21 00:09:48 -04:00
jsonStdoutError(message, hint)
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183) * fix(workspace): align resolved workspace messaging and config lookup intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths * fix(bootstrap): align no-workspace JSON wording intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test * fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1) intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead * fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3) intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release * fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1) intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree * fix(config): skip no-workspace store init for store-free commands intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers * fix(ci): restore init prefix normalization and formatting intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-11 13:23:14 +09:00
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
}
os.Exit(1)
}
// FatalErrorWithHint writes an error message with a hint to stderr and exits.
// Use this when you can provide an actionable suggestion to fix the error.
//
// Example:
//
// FatalErrorWithHint("database not found", "Run 'bd init' to create a database")
func FatalErrorWithHint(message, hint string) {
if jsonOutput {
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-21 00:09:48 -04:00
jsonStderrError(message, hint)
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
}
os.Exit(1)
}
// WarnError writes a warning message to stderr and returns.
// Use this for optional operations that enhance functionality but aren't required.
//
// Pattern B from ERROR_HANDLING.md:
// - Metadata operations
// - Cleanup operations
// - Auxiliary features (git hooks, merge drivers)
//
// Example:
//
// if err := createConfigYaml(beadsDir, false); err != nil {
// WarnError("failed to create config.yaml: %v", err)
// }
func WarnError(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
}
// CheckReadonly exits with an error if readonly mode is enabled.
// Call this at the start of write commands (create, update, close, delete, sync, etc.).
// Used by worker sandboxes that should only read beads, not modify them.
//
// Example:
//
// var createCmd = &cobra.Command{
// Run: func(cmd *cobra.Command, args []string) {
// CheckReadonly("create")
// // ... rest of command
// },
// }
func CheckReadonly(operation string) {
if readonlyMode {
FatalError("operation '%s' is not allowed in read-only mode", operation)
}
}