beads/cmd/bd/errors.go
Kevin Glynn 8518e71d66
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 13:24:17 -07:00

180 lines
5.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
)
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 {
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() {
return "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database"
}
return "check BEADS_DIR/worktree setup, run 'bd doctor' to diagnose, or run 'bd init' to create a new database"
}
// buildJSONError constructs a JSON error object respecting envelope mode.
func buildJSONError(message, hint string) interface{} {
inner := map[string]interface{}{
"error": message,
}
if hint != "" {
inner["hint"] = hint
}
if jsonEnvelopeEnabled() {
return map[string]interface{}{
"schema_version": JSONSchemaVersion,
"data": inner,
}
}
inner["schema_version"] = JSONSchemaVersion
return inner
}
// jsonStderrError writes a structured JSON error to stderr when --json is active.
func jsonStderrError(message, hint string) {
encoder := json.NewEncoder(os.Stderr)
encoder.SetIndent("", " ")
_ = encoder.Encode(buildJSONError(message, hint))
}
// 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("", " ")
_ = encoder.Encode(buildJSONError(message, hint))
}
// 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 {
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 {
jsonStdoutError(msg, "")
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
}
os.Exit(1)
}
// 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 {
jsonStdoutError(message, hint)
} 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 {
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)
}
}