diff --git a/cmd/bd/protocol/errors_contract_test.go b/cmd/bd/protocol/errors_contract_test.go index f28ca9341..ea8a7f242 100644 --- a/cmd/bd/protocol/errors_contract_test.go +++ b/cmd/bd/protocol/errors_contract_test.go @@ -115,25 +115,16 @@ func TestProtocol_ErrorClass_NotClaimableNamesState(t *testing.T) { } // TestProtocol_ErrorClass_ClaimFailures_StructuredJSON is the §E5 half of the -// claim error classes — and it is SKIPPED because bd-go does not satisfy it -// today (wy-kxgf4). -// -// bd routes not-found through the JSON-respecting error helper, so -// `bd show --json` emits {error, schema_version:1} (pinned above). -// The claim path does not: `bd update --claim --json` prints -// -// Error claiming t04…-qqr: issue already claimed by alice -// -// as plain text, so an agent driving bd with --json gets an unparseable stderr -// line for the single most common contended-write failure it must branch on. -// The message contract (§E4) holds; the structured contract (§E5) does not. -// -// Per proposal §14, where bd's behavior deviates from a clause the clause wins -// and the deviation is a bug — so this test asserts the clause and stays -// skipped until wy-kxgf4 lands, at which point it becomes the guardrail. +// claim error classes: a lost claim is the most common contended-write failure +// an agent driving bd with --json has to branch on, so its class must be +// readable from a JSON document and not only from a stderr line to scrape. bd +// update reports per-id refusals in one batch document, so the class and the +// holder/state live in the refused id's "failed" entry; the top-level "error" +// is the batch summary. The document count is pinned as well: a second, +// per-claim object beside the batch report would hand a consumer two +// concatenated documents (wy-kxgf4). The stream (stdout vs stderr) is +// deliberately not pinned — that split is proposal OQ-5. func TestProtocol_ErrorClass_ClaimFailures_StructuredJSON(t *testing.T) { - t.Skip("bd emits claim failures as plain text even with --json; violates §E5 (wy-kxgf4)") - t.Parallel() w := newWorkspace(t) @@ -145,18 +136,16 @@ func TestProtocol_ErrorClass_ClaimFailures_StructuredJSON(t *testing.T) { // already-claimed: structured, and still naming the holder. out, _ := w.runEnvExpectError([]string{actorBob}, "update", claimed, "--claim", "--json") - obj := requireJSONError(t, out, "already-claimed --json") - msg := errorMessage(obj) + msg := requireFailedEntry(t, out, claimed, "already-claimed --json") if !strings.Contains(strings.ToLower(msg), "already claimed") || !strings.Contains(msg, "alice") { - t.Errorf("--json error does not name class + holder (§E4/§E5): %q", msg) + t.Errorf("--json failed entry does not name class + holder (§E4/§E5): %q", msg) } // not-claimable: structured, and still naming the state. out, _ = w.runEnvExpectError([]string{actorBob}, "update", closed, "--claim", "--json") - obj = requireJSONError(t, out, "not-claimable --json") - msg = strings.ToLower(errorMessage(obj)) - if !strings.Contains(msg, "not claimable") || !strings.Contains(msg, "closed") { - t.Errorf("--json error does not name class + state (§E4/§E5): %q", errorMessage(obj)) + msg = requireFailedEntry(t, out, closed, "not-claimable --json") + if lower := strings.ToLower(msg); !strings.Contains(lower, "not claimable") || !strings.Contains(lower, "closed") { + t.Errorf("--json failed entry does not name class + state (§E4/§E5): %q", msg) } } diff --git a/cmd/bd/protocol/wp4_helpers_test.go b/cmd/bd/protocol/wp4_helpers_test.go index 6c4ba40a0..b777150bf 100644 --- a/cmd/bd/protocol/wp4_helpers_test.go +++ b/cmd/bd/protocol/wp4_helpers_test.go @@ -100,24 +100,57 @@ func jsonErrorFrom(t *testing.T, out string) (map[string]any, bool) { if err := dec.Decode(&obj); err != nil { continue } - if _, ok := obj["error"]; ok { - return obj, true - } - // BD_JSON_ENVELOPE=1 nests the error under "data". - if data, ok := obj["data"].(map[string]any); ok { - if _, ok := data["error"]; ok { - // Lift schema_version from the envelope so the caller can - // assert one shape. - if sv, ok := obj["schema_version"]; ok { - data["schema_version"] = sv - } - return data, true - } + if errObj, ok := asJSONError(obj); ok { + return errObj, true } } return nil, false } +// asJSONError returns obj as a structured error object if it carries an +// "error" key, unwrapping the BD_JSON_ENVELOPE form ({schema_version, +// data:{...}}) so callers see one shape either way. +func asJSONError(obj map[string]any) (map[string]any, bool) { + if _, ok := obj["error"]; ok { + return obj, true + } + // BD_JSON_ENVELOPE=1 nests the error under "data". + if data, ok := obj["data"].(map[string]any); ok { + if _, ok := data["error"]; ok { + // Lift schema_version from the envelope so the caller can + // assert one shape. + if sv, ok := obj["schema_version"]; ok { + data["schema_version"] = sv + } + return data, true + } + } + return nil, false +} + +// jsonErrorDocs returns every top-level JSON error object in the output, in +// order. Unlike jsonErrorFrom it steps over each object it decodes, so an +// object nested inside a document is not counted as a document of its own — +// the entries of a batch report's "failed" list carry "error" keys too. +func jsonErrorDocs(out string) []map[string]any { + var docs []map[string]any + for i := 0; i < len(out); i++ { + if out[i] != '{' { + continue + } + dec := json.NewDecoder(strings.NewReader(out[i:])) + var obj map[string]any + if err := dec.Decode(&obj); err != nil { + continue + } + i += int(dec.InputOffset()) - 1 + if errObj, ok := asJSONError(obj); ok { + docs = append(docs, errObj) + } + } + return docs +} + // requireJSONError asserts the output carries a structured error object with a // non-empty message and schema_version == 1 (§E5), and returns it. func requireJSONError(t *testing.T, out, context string) map[string]any { @@ -126,6 +159,14 @@ func requireJSONError(t *testing.T, out, context string) map[string]any { if !ok { t.Fatalf("%s: no JSON error object in output:\n%s", context, out) } + checkJSONError(t, obj, out, context) + return obj +} + +// checkJSONError asserts a structured error object has a non-empty message +// and schema_version == 1 (§E5). +func checkJSONError(t *testing.T, obj map[string]any, out, context string) { + t.Helper() msg, _ := obj["error"].(string) if strings.TrimSpace(msg) == "" { t.Errorf("%s: JSON error has empty %q field:\n%s", context, "error", out) @@ -134,7 +175,6 @@ func requireJSONError(t *testing.T, out, context string) map[string]any { if !ok || int(sv) != 1 { t.Errorf("%s: schema_version = %v, want 1 (§E5):\n%s", context, obj["schema_version"], out) } - return obj } // errorMessage returns the "error" field of a structured error object. @@ -143,6 +183,35 @@ func errorMessage(obj map[string]any) string { return msg } +// requireFailedEntry asserts the output of a refused single-id write carries +// exactly one structured error document (§E5) and returns the "error" of that +// document's "failed" entry for id. bd reports per-id refusals in one batch +// document, {error: "N of M issues failed to update", failed: [{id, error}]}, +// so the entry, not the top-level summary, is where the class lives (§E4). +func requireFailedEntry(t *testing.T, out, id, context string) string { + t.Helper() + docs := jsonErrorDocs(out) + if len(docs) != 1 { + t.Fatalf("%s: %d JSON error documents in output, want exactly 1 (§E5):\n%s", context, len(docs), out) + } + obj := docs[0] + checkJSONError(t, obj, out, context) + failed, _ := obj["failed"].([]any) + for _, f := range failed { + entry, _ := f.(map[string]any) + if entry["id"] != id { + continue + } + msg, _ := entry["error"].(string) + if strings.TrimSpace(msg) == "" { + t.Errorf("%s: failed entry for %s has empty %q field:\n%s", context, id, "error", out) + } + return msg + } + t.Fatalf("%s: JSON error has no failed entry for %s:\n%s", context, id, out) + return "" +} + // --------------------------------------------------------------------------- // Store fixture: direct SQL against the workspace's database (§V2/§V3) // --------------------------------------------------------------------------- diff --git a/cmd/bd/update_proxied_integration_test.go b/cmd/bd/update_proxied_integration_test.go index 3de2485f7..efea4da05 100644 --- a/cmd/bd/update_proxied_integration_test.go +++ b/cmd/bd/update_proxied_integration_test.go @@ -291,6 +291,54 @@ func TestProxiedServerUpdate(t *testing.T) { } }) + // A refused --claim under --json on the proxied path: the batch report is + // the only JSON document the command prints, and its failed entry names the + // already-claimed class and the holder — the direct route's contract, + // pinned by protocol.TestProtocol_ErrorClass_ClaimFailures_StructuredJSON + // (wy-kxgf4). + t.Run("claim_conflict_json_reports_holder_in_failed_entry", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "uccj") + issue := bdProxiedCreate(t, bd, p.dir, "Contested JSON") + bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--claim", "--actor", "alice") + + stdout, stderr, err := bdProxiedUpdateRaw(t, bd, p.dir, "--json", issue.ID, "--claim", "--actor", "bob") + if err == nil { + t.Fatalf("proxied --json claim of an issue alice holds exited 0, want non-zero\nstdout:\n%s\nstderr:\n%s", stdout, stderr) + } + + // A JSON document starts at column 0, whether compact or indented, so + // count those lines across both streams: one, not one per refusal. + docs := 0 + for _, line := range strings.Split(stdout+"\n"+stderr, "\n") { + if strings.HasPrefix(line, "{") { + docs++ + } + } + if docs != 1 { + t.Errorf("output carries %d JSON documents, want exactly 1 (the batch report)\nstdout:\n%s\nstderr:\n%s", docs, stdout, stderr) + } + + lines := strings.Split(strings.TrimSpace(stderr), "\n") + last := lines[len(lines)-1] + var report struct { + Error string `json:"error"` + Failed []struct { + ID string `json:"id"` + Error string `json:"error"` + } `json:"failed"` + } + if uerr := json.Unmarshal([]byte(last), &report); uerr != nil { + t.Fatalf("last stderr line is not a JSON failure report: %v\nstderr:\n%s", uerr, stderr) + } + if len(report.Failed) != 1 || report.Failed[0].ID != issue.ID { + t.Fatalf("JSON failure report failed list = %+v, want exactly one entry for %s", report.Failed, issue.ID) + } + if msg := report.Failed[0].Error; !strings.Contains(msg, "already claimed") || !strings.Contains(msg, "alice") { + t.Errorf("failed entry error = %q, want the already-claimed class naming the holder alice", msg) + } + }) + t.Run("add_remove_labels", func(t *testing.T) { t.Parallel() p := newSharedProxiedProject(t, bd, "ul")