Compare commits

...
Sign in to create a new pull request.

2 commits

Author SHA1 Message Date
Eddie the Engineer
db65a1574b test(protocol): pin claim refusals on the single --json batch report (wy-kxgf4)
Adopt-PR review fixup for #4756, iteration 1. It takes option (a) from
the review synthesis, which is also maphew's CHANGES_REQUESTED fix: drop
the eager per-claim JSON object and pin §E4/§E5 on main's centralized
batch report instead.

Major 1 (claude+codex, maphew's blocker). Under --json, a refused claim
printed two JSON documents on stderr: the indented reportClaimFailure
object, then reportUpdateFailures' compact {error, failed,
schema_version} summary. A consumer reading the whole stream, or main's
documented "last stderr line", did not get one document. Main has
already moved on (wy-ghg0d). That summary reports every per-id refusal,
and the refused id's failed[] entry already names the class and the
holder or state:

    {"error":"1 of 1 issues failed to update","failed":[{"id":"…",
     "error":"updating issue: issue already claimed by alice"}],
     "schema_version":1}

So cmd/bd/errors.go, update.go and update_proxied_server.go go back to
base byte for byte. reportClaimFailure and its two call sites are gone,
and text output, stdout and exit codes are main's. That supersedes the
helper the contributor commit describes. The PR now changes only tests,
so its title and squash message should say so at finalize. This also
covers the commit-message nit.

Major 2 (the proxied claim arm was not gated on `claim`, so a proxied
--assignee fence refusal read "failed to claim") is moot: the object it
mislabelled no longer exists. Both routes report through the same
summary. The message-drift minor is moot too. So is the synthesis's
follow-up about the direct route's non-claim fence refusals under
--json: they already land in the same failed[] list. The remaining
"updating issue:" vs "claiming issue:" entry prefixes are pre-existing on
main.

TestProtocol_ErrorClass_ClaimFailures_StructuredJSON stays un-skipped
and is re-pinned. It now requires:
- exactly one top-level JSON error document (the new jsonErrorDocs steps
  over each decoded object, so failed[] entries are not counted);
- §E5's error and schema_version on that document;
- a failed[] entry for the refused id that names "already claimed" and
  "alice", or "not claimable" and "closed".

TestProxiedServerUpdate gains
claim_conflict_json_reports_holder_in_failed_entry, the proxied
guardrail the review found missing. Two test-gap asks are dropped
because they targeted the claim-only branch, which is gone: the
--assignee --json negative case, and --format json (which reaches the
same jsonOutput-keyed reporter).

Validation (local Dolt 2.2.0 server, scrubbed env):
- cmd/bd/protocol, whole package, with BEADS_PROTOCOL_REQUIRE_DOLT=1:
  109 pass, 1 pre-existing PTY skip.
- Mutant (this PR's original errors.go, update.go and
  update_proxied_server.go restored): the protocol test and the new
  proxied subtest both fail on "2 JSON error documents"; both pass at
  this head.
- TestProxiedServerUpdate (proxied-lane env): all subtests pass.
- TestParityUpdate* (including TestParityUpdateJSONFailureReport) and
  TestMultiIDUpdate*: pass.
- make ci-pr-lint: 0 issues (native, windows, darwin).

Follow-up, not in this PR: typed claim-conflict fields in failed[]
(issueops.ClaimConflictError's holder and status), so consumers need
not match on message text.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 01:32:09 +00:00
Steve Yegge
0882aac55d fix(cli): emit claim failures as structured JSON under --json (wy-kxgf4)
Protocol v0 §E5 requires that with --json, errors are emitted as a JSON
object carrying at least "error" and schema_version: 1. bd honored that on
the not-found path but not on the claim paths: `bd update <id> --claim
--json` printed

    Error claiming t04...-qqr: issue already claimed by alice

as plain text on stderr, so an agent driving bd with --json got an
unparseable line for the single most common contended-write failure it has
to branch on. The §E4 message contract held (the class and the holder/state
are named); the §E5 structured contract did not.

Route both claim paths (the direct-store loop in update.go and the
SQL-server proxied path) through a new reportClaimFailure helper: under
--json it emits {error, schema_version:1} via jsonStderrError, otherwise the
plain-text wording is unchanged, byte for byte, since §E4 tests pin it. The
JSON object goes to stderr so a mixed batch's stdout stays the clean array
of the issues that did update; the stream split itself is proposal OQ-5 and
is not pinned.

Un-skips TestProtocol_ErrorClass_ClaimFailures_StructuredJSON, which was
written against the clause and skipped pending this fix; it now passes and
becomes the guardrail. Full cmd/bd/protocol package green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-08 01:32:09 +00:00
3 changed files with 143 additions and 37 deletions

View file

@ -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 <missing> --json` emits {error, schema_version:1} (pinned above).
// The claim path does not: `bd update <id> --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)
}
}

View file

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

View file

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