diff --git a/cmd/bd/assign.go b/cmd/bd/assign.go index 1e1e15214..15b4b03b8 100644 --- a/cmd/bd/assign.go +++ b/cmd/bd/assign.go @@ -17,6 +17,11 @@ var assignCmd = &cobra.Command{ Shorthand for 'bd update --assignee '. +Refuses to overwrite another actor's live in_progress claim without --force +(bd-98s5c); issues assigned to a claim.pools alias are exempt, matching +--claim. For a holder-aware transfer prefer +'bd update --if-assignee -a '. + Examples: bd assign bd-123 alice bd assign bd-123 "" # unassign`, @@ -33,8 +38,10 @@ Examples: } }() + force, _ := cmd.Flags().GetBool("force") + if usesProxiedServer() { - return runAssignProxiedServer(rootCtx, args) + return runAssignProxiedServer(rootCtx, args, force) } id := args[0] @@ -63,6 +70,13 @@ Examples: return HandleErrorRespectJSON("%s", err) } + // bd-98s5c: bd assign is shorthand for an unguarded assignee update — + // same live-claim fence as bd update -a. + if err := validateIssueReassignable(id, result.Issue, actor, assignee, + storeClaimPoolAliases(ctx, issueStore), force); err != nil { + return HandleErrorRespectJSON("%s", err) + } + updates := map[string]interface{}{ "assignee": assignee, } @@ -102,6 +116,7 @@ Examples: } func init() { + assignCmd.Flags().Bool("force", false, "Allow overwriting another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim)") assignCmd.ValidArgsFunction = issueIDCompletion rootCmd.AddCommand(assignCmd) } diff --git a/cmd/bd/assign_fence_embedded_test.go b/cmd/bd/assign_fence_embedded_test.go new file mode 100644 index 000000000..480214e35 --- /dev/null +++ b/cmd/bd/assign_fence_embedded_test.go @@ -0,0 +1,213 @@ +//go:build cgo + +package main + +import ( + "errors" + "os" + "os/exec" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// bdRunFailCode runs an arbitrary bd command expecting failure and returns +// combined output plus the process exit code. +func bdRunFailCode(t *testing.T, bd, dir string, args ...string) (string, int) { + t.Helper() + cmd := exec.Command(bd, args...) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("expected bd %s to fail, but it succeeded:\n%s", strings.Join(args, " "), out) + } + var ee *exec.ExitError + if !errors.As(err, &ee) { + t.Fatalf("bd %s failed without an exit code: %v\n%s", strings.Join(args, " "), err, out) + } + return string(out), ee.ExitCode() +} + +// bdRunOK runs an arbitrary bd command expecting success. +func bdRunOK(t *testing.T, bd, dir string, args ...string) string { + t.Helper() + cmd := exec.Command(bd, args...) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("bd %s failed: %v\n%s", strings.Join(args, " "), err, out) + } + return string(out) +} + +// TestReassignFenceCLI drives the bd-98s5c live-claim reassign fence +// end-to-end: plain `bd update -a` and `bd assign` were the last unfenced +// cross-actor takeover path (--claim, unclaim, and close all refuse without +// --force). The fence must refuse ONLY the silent steamroll — a different +// actor overwriting a live in_progress claim with a third assignee — and must +// leave routine dispatch untouched: open-bead reassigns, self-edits, +// idempotent re-asserts, pool-alias takes, and holder-aware --if-assignee +// transfers all proceed without --force. +func TestReassignFenceCLI(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") + } + t.Parallel() + + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "rf") + + claimAs := func(t *testing.T, holder string) *types.Issue { + t.Helper() + issue := bdCreate(t, bd, dir, "Held work", "--type", "task") + bdUpdate(t, bd, dir, issue.ID, "--actor", holder, "--assignee", holder, "--status", "in_progress") + return issue + } + + t.Run("update_refuses_live_foreign_claim", func(t *testing.T) { + issue := claimAs(t, "holder") + + out, code := bdUpdateFailCode(t, bd, dir, issue.ID, "--actor", "thief", "--assignee", "thief") + if code != 1 { + t.Errorf("fence refusal exit code = %d, want 1 (policy refusal, never 13/guard-mismatch)\n%s", code, out) + } + for _, frag := range []string{"holder", "held by", "--force"} { + if !strings.Contains(out, frag) { + t.Errorf("refusal should contain %q, got:\n%s", frag, out) + } + } + // The old --claim refusal copy taught the steamroller ("use bd + // unclaim"); the fence copy must never reintroduce that shape. + if strings.Contains(out, "use bd unclaim") { + t.Errorf("refusal copy teaches the unclaim steamroller:\n%s", out) + } + + got := bdShow(t, bd, dir, issue.ID) + if got.Assignee != "holder" || got.Status != types.StatusInProgress { + t.Errorf("refused reassign clobbered the row: assignee=%q status=%s, want holder/in_progress", got.Assignee, got.Status) + } + + // --force is the sanctioned override for abandoned claims. + bdUpdate(t, bd, dir, issue.ID, "--actor", "thief", "--assignee", "thief", "--force") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "thief" { + t.Errorf("--force reassign did not apply: assignee=%q, want thief", got.Assignee) + } + }) + + t.Run("assign_refuses_live_foreign_claim", func(t *testing.T) { + issue := claimAs(t, "holder") + + out, code := bdRunFailCode(t, bd, dir, "assign", issue.ID, "thief", "--actor", "thief") + if code != 1 { + t.Errorf("assign fence exit code = %d, want 1\n%s", code, out) + } + if !strings.Contains(out, "holder") { + t.Errorf("assign refusal should name the holder, got:\n%s", out) + } + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "holder" { + t.Errorf("refused assign clobbered the row: assignee=%q, want holder", got.Assignee) + } + + bdRunOK(t, bd, dir, "assign", issue.ID, "thief", "--actor", "thief", "--force") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "thief" { + t.Errorf("assign --force did not apply: assignee=%q, want thief", got.Assignee) + } + }) + + t.Run("unassign_of_live_foreign_claim_refused", func(t *testing.T) { + issue := claimAs(t, "holder") + + // Stripping a live claim via -a "" is unclaim in disguise; same fence. + _, code := bdUpdateFailCode(t, bd, dir, issue.ID, "--actor", "thief", "--assignee", "") + if code != 1 { + t.Errorf("unassign fence exit code = %d, want 1", code) + } + out, _ := bdRunFailCode(t, bd, dir, "assign", issue.ID, "", "--actor", "thief") + if !strings.Contains(out, "holder") { + t.Errorf("assign-to-empty refusal should name the holder, got:\n%s", out) + } + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "holder" { + t.Errorf("refused unassign clobbered the row: assignee=%q, want holder", got.Assignee) + } + }) + + // NEGATIVE regression fences for the load-bearing status==in_progress + // clause and the self/idempotent exemptions: routine dispatch must stay + // frictionless or every dispatcher grows a habitual --force. + t.Run("open_assigned_reassign_needs_no_force", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Open dispatch", "--type", "task", "--assignee", "alice") + bdUpdate(t, bd, dir, issue.ID, "--actor", "dispatcher", "--assignee", "bob") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "bob" { + t.Errorf("open-bead reassign should not be fenced: assignee=%q, want bob", got.Assignee) + } + }) + + t.Run("holder_edits_own_claim_freely", func(t *testing.T) { + issue := claimAs(t, "holder") + bdUpdate(t, bd, dir, issue.ID, "--actor", "holder", "--assignee", "successor") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "successor" { + t.Errorf("self-reassign should not be fenced: assignee=%q, want successor", got.Assignee) + } + }) + + t.Run("idempotent_reassert_of_holder_passes", func(t *testing.T) { + issue := claimAs(t, "holder") + bdUpdate(t, bd, dir, issue.ID, "--actor", "replayer", "--assignee", "holder") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "holder" { + t.Errorf("idempotent re-assert should pass: assignee=%q, want holder", got.Assignee) + } + }) + + t.Run("if_assignee_transfer_needs_no_force", func(t *testing.T) { + // The holder-aware CAS (bd-wsqvw park transition) names the holder + // explicitly — nothing silent — and --force/--if-assignee are + // mutually exclusive, so the fence must not fire under the guard. + issue := claimAs(t, "holder") + bdUpdate(t, bd, dir, issue.ID, "--actor", "supervisor", "--if-assignee", "holder", "--assignee", "parked") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "parked" { + t.Errorf("guarded park should pass without --force: assignee=%q, want parked", got.Assignee) + } + }) + + t.Run("force_and_if_assignee_mutually_exclusive", func(t *testing.T) { + issue := claimAs(t, "holder") + out, _ := bdUpdateFailCode(t, bd, dir, issue.ID, "--force", "--if-assignee", "holder", "--assignee", "x") + if !strings.Contains(out, "force") || !strings.Contains(out, "if-assignee") { + t.Errorf("expected flag-exclusion error naming both flags, got:\n%s", out) + } + }) + + t.Run("claim_conflict_copy_preserved_under_claim_flag", func(t *testing.T) { + // --claim -a X on a foreign live claim must keep failing through the + // claim CAS with the canonical "already claimed" copy — the fence + // defers to it (the CAS is itself the anti-steal gate, and existing + // automation keys on that message). + issue := claimAs(t, "holder") + out, _ := bdUpdateFailCode(t, bd, dir, issue.ID, "--actor", "thief", "--claim", "--assignee", "thief") + if !strings.Contains(out, "already claimed") && !strings.Contains(out, "already assigned") { + t.Errorf("expected the claim CAS conflict copy, got:\n%s", out) + } + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "holder" { + t.Errorf("claim+assignee combo clobbered the row: assignee=%q, want holder", got.Assignee) + } + }) + + t.Run("pool_alias_holder_is_takeable", func(t *testing.T) { + // The claim.pools carve-out: --claim deliberately treats a + // pool-assigned issue as claimable by any actor; without the same + // carve-out, --claim and -a would give opposite answers on the same + // bead — and the refusal would say "coordinate with the holder" when + // the holder is a queue alias with nobody behind it. + bdRunOK(t, bd, dir, "config", "set", "claim.pools", "fable-crew") + issue := bdCreate(t, bd, dir, "Queue item", "--type", "task") + bdUpdate(t, bd, dir, issue.ID, "--actor", "dispatcher", "--assignee", "fable-crew", "--status", "in_progress") + + bdUpdate(t, bd, dir, issue.ID, "--actor", "worker-1", "--assignee", "worker-1") + if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "worker-1" { + t.Errorf("pool-alias take should pass without --force: assignee=%q, want worker-1", got.Assignee) + } + }) +} diff --git a/cmd/bd/assign_fence_proxied_test.go b/cmd/bd/assign_fence_proxied_test.go new file mode 100644 index 000000000..97776bdfb --- /dev/null +++ b/cmd/bd/assign_fence_proxied_test.go @@ -0,0 +1,87 @@ +//go:build cgo + +package main + +import ( + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// TestProxiedServerReassignFence proves the bd-98s5c live-claim reassign +// fence holds on the proxied-server path — the topology where cross-actor +// collisions actually happen, since every shared-dolt-server clone writes +// through it. A silent steamroll refuses with exit 1 (policy refusal, never +// ExitGuardMismatch), --force overrides, and the idempotent re-assert stays a +// success for retry/replay safety. +func TestProxiedServerReassignFence(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + + t.Run("update_refuses_then_force_overrides", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rfa") + issue := bdProxiedCreate(t, bd, p.dir, "Held via proxy") + bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--actor", "holder", "--assignee", "holder", "--status", "in_progress") + + out, code := bdProxiedUpdateFailCode(t, bd, p.dir, issue.ID, "--actor", "thief", "--assignee", "thief") + if code != 1 { + t.Errorf("fence refusal exit code = %d, want 1 (policy refusal, not %d/guard-mismatch)\n%s", code, ExitGuardMismatch, out) + } + for _, frag := range []string{"held by", "holder", "--force"} { + if !strings.Contains(out, frag) { + t.Errorf("refusal should contain %q, got:\n%s", frag, out) + } + } + got := bdProxiedShow(t, bd, p.dir, issue.ID) + if got.Assignee != "holder" || got.Status != types.StatusInProgress { + t.Errorf("refused reassign clobbered the row: assignee=%q status=%s, want holder/in_progress", got.Assignee, got.Status) + } + + // Idempotent re-assert of the current holder is a success (replay + // safety on the retrying proxied path). + bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--actor", "replayer", "--assignee", "holder") + + bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--actor", "thief", "--assignee", "thief", "--force") + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Assignee != "thief" { + t.Errorf("--force reassign did not apply: assignee=%q, want thief", got.Assignee) + } + }) + + t.Run("assign_refuses_then_force_overrides", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rfb") + issue := bdProxiedCreate(t, bd, p.dir, "Assigned via proxy") + bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--actor", "holder", "--assignee", "holder", "--status", "in_progress") + + out, err := bdProxiedRun(t, bd, p.dir, "assign", issue.ID, "thief", "--actor", "thief") + if err == nil { + t.Fatalf("proxied assign over a live foreign claim should fail, got:\n%s", out) + } + if !strings.Contains(string(out), "holder") { + t.Errorf("assign refusal should name the holder, got:\n%s", out) + } + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Assignee != "holder" { + t.Errorf("refused assign clobbered the row: assignee=%q, want holder", got.Assignee) + } + + if out, err := bdProxiedRun(t, bd, p.dir, "assign", issue.ID, "thief", "--actor", "thief", "--force"); err != nil { + t.Fatalf("assign --force failed: %v\n%s", err, out) + } + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Assignee != "thief" { + t.Errorf("assign --force did not apply: assignee=%q, want thief", got.Assignee) + } + }) + + t.Run("open_bead_dispatch_stays_frictionless", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rfc") + issue := bdProxiedCreate(t, bd, p.dir, "Open dispatch via proxy", "--assignee", "alice") + bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--actor", "dispatcher", "--assignee", "bob") + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Assignee != "bob" { + t.Errorf("open-bead reassign should not be fenced: assignee=%q, want bob", got.Assignee) + } + }) +} diff --git a/cmd/bd/edit_proxied_server.go b/cmd/bd/edit_proxied_server.go index 10bd681fb..e342cb06f 100644 --- a/cmd/bd/edit_proxied_server.go +++ b/cmd/bd/edit_proxied_server.go @@ -119,7 +119,7 @@ func runEditProxiedServer(cmd *cobra.Command, ctx context.Context, args []string return HandleErrorRespectJSON("title cannot be empty") } - updated, err := proxiedUpdateIssueFields(ctx, id, "bd: edit "+id, map[string]any{fieldToEdit: newValue}) + updated, err := proxiedUpdateIssueFields(ctx, id, "bd: edit "+id, map[string]any{fieldToEdit: newValue}, false) if err != nil { fmt.Fprintf(os.Stderr, "Your edits are preserved in: %s\n", tmpPath) //nolint:gosec // G705: stderr, not a browser context return HandleErrorRespectJSON("updating issue: %v", err) diff --git a/cmd/bd/mutate_proxied_server.go b/cmd/bd/mutate_proxied_server.go index ce43ffa54..25fc9d416 100644 --- a/cmd/bd/mutate_proxied_server.go +++ b/cmd/bd/mutate_proxied_server.go @@ -40,8 +40,18 @@ func proxiedMutateIssue(ctx context.Context, id, commitMsg string, mutate func(c return updated, nil } -func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates map[string]any) (*types.Issue, error) { +// force applies only to assignee updates: it bypasses the live-claim reassign +// fence (bd-98s5c). Callers whose updates never carry "assignee" pass false. +func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates map[string]any, force bool) (*types.Issue, error) { return proxiedMutateIssue(ctx, id, commitMsg, func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error { + // bd-98s5c: an unguarded assignee update (bd assign via the proxied + // server) must not silently overwrite another actor's live claim. + if newAssignee, ok := updates["assignee"].(string); ok { + if err := validateIssueReassignable(id, issue, actor, newAssignee, + uowClaimPoolAliases(ctx, uw), force); err != nil { + return err + } + } if isWisp { return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, actor) } @@ -49,10 +59,10 @@ func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates }) } -func runAssignProxiedServer(ctx context.Context, args []string) error { +func runAssignProxiedServer(ctx context.Context, args []string, force bool) error { id := args[0] assignee := args[1] - updated, err := proxiedUpdateIssueFields(ctx, id, "bd: assign "+id, map[string]any{"assignee": assignee}) + updated, err := proxiedUpdateIssueFields(ctx, id, "bd: assign "+id, map[string]any{"assignee": assignee}, force) if err != nil { return HandleErrorRespectJSON("assign %s: %v", id, err) } @@ -77,7 +87,7 @@ func runPriorityProxiedServer(ctx context.Context, args []string) error { if err != nil { return HandleErrorRespectJSON("%v", err) } - updated, err := proxiedUpdateIssueFields(ctx, id, "bd: priority "+id, map[string]any{"priority": priority}) + updated, err := proxiedUpdateIssueFields(ctx, id, "bd: priority "+id, map[string]any{"priority": priority}, false) if err != nil { return HandleErrorRespectJSON("priority %s: %v", id, err) } diff --git a/cmd/bd/show_unit_helpers.go b/cmd/bd/show_unit_helpers.go index 0d6f23b7a..2716dbd17 100644 --- a/cmd/bd/show_unit_helpers.go +++ b/cmd/bd/show_unit_helpers.go @@ -4,6 +4,8 @@ import ( "context" "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/validation" ) @@ -32,6 +34,47 @@ func validateIssueClosable(id string, issue *types.Issue, actor string, force bo )(id, issue) } +// validateIssueReassignable checks whether an assignee update may proceed: +// plain `bd update -a` / `bd assign` must not silently overwrite another +// actor's live in_progress claim (bd-98s5c) — it was the last unfenced +// cross-actor takeover path after --claim, unclaim, and close were fenced. +// +// Call it only when the update actually carries an assignee change; +// newAssignee may be "" (unassign), which is fenced the same way. Do NOT call +// it when the caller passed an explicit --if-assignee guard: that CAS names +// the holder, so nothing about it is silent, and it is how sanctioned X→Y +// transfers (park) work without --force (--force and --if-assignee are +// mutually exclusive). +func validateIssueReassignable(id string, issue *types.Issue, actor, newAssignee string, poolAliases func() []string, force bool) error { + return validation.AssigneeNotStolen(actor, newAssignee, poolAliases, force)(id, issue) +} + +// storeClaimPoolAliases returns a lazy claim.pools reader against a direct +// store, for the reassign fence's pool-alias carve-out. Config read errors +// yield no aliases — the fence fails closed (refuses) rather than allowing a +// takeover it can't verify. +func storeClaimPoolAliases(ctx context.Context, st storage.DoltStorage) func() []string { + return func() []string { + raw, err := st.GetConfig(ctx, "claim.pools") + if err != nil { + return nil + } + return issueops.ParseClaimPools(raw) + } +} + +// uowClaimPoolAliases is storeClaimPoolAliases' proxied-server sibling: the +// same lazy claim.pools read through the unit of work's transaction. +func uowClaimPoolAliases(ctx context.Context, uw uow.UnitOfWork) func() []string { + return func() []string { + raw, err := uw.ConfigUseCase().GetConfig(ctx, "claim.pools") + if err != nil { + return nil + } + return issueops.ParseClaimPools(raw) + } +} + func applyLabelUpdates(ctx context.Context, st storage.DoltStorage, issueID, actor string, setLabels, addLabels, removeLabels []string) error { // Set labels (replaces all existing labels) if len(setLabels) > 0 { diff --git a/cmd/bd/update.go b/cmd/bd/update.go index 5407c6b6b..ce65ebf12 100644 --- a/cmd/bd/update.go +++ b/cmd/bd/update.go @@ -320,6 +320,9 @@ pointless).`, // Get claim flag claimFlag, _ := cmd.Flags().GetBool("claim") + // --force bypasses the live-claim reassign fence (bd-98s5c); mutually + // exclusive with --if-assignee at the flag-group level. + forceFlag, _ := cmd.Flags().GetBool("force") if len(updates) == 0 && !claimFlag { fmt.Println("No updates specified") @@ -401,6 +404,26 @@ pointless).`, continue } + // bd-98s5c: an unguarded assignee update must not silently + // overwrite another actor's live claim. Skipped under + // --if-assignee: that CAS names the holder explicitly, which is + // how sanctioned X→Y transfers (park) stay possible without + // --force. Also skipped under --claim: the claim CAS is itself + // the anti-steal gate (a foreign live claim fails it with the + // canonical "already claimed" copy before any field update runs), + // and an assignee edit that rides a WON claim only ever touches + // the actor's own fresh claim. A policy refusal, so it exits 1, + // not 13. + if newAssignee, ok := updates["assignee"].(string); ok && ifAssignee == nil && !claimFlag { + if err := validateIssueReassignable(id, issue, actor, newAssignee, + storeClaimPoolAliases(ctx, issueStore), forceFlag); err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + recordFailure(id, err.Error()) + closeIfUnmutated(result) + continue + } + } + // Handle claim operation atomically using compare-and-swap semantics if claimFlag { if err := issueStore.ClaimIssue(ctx, result.ResolvedID, actor); err != nil { @@ -793,9 +816,17 @@ func init() { updateCmd.Flags().StringSlice("set-labels", nil, "Set labels, replacing all existing (repeatable)") updateCmd.Flags().String("parent", "", "New parent issue ID (reparents the issue, use empty string to remove parent)") updateCmd.Flags().Bool("claim", false, "Atomically claim the issue (sets assignee to you, status to in_progress; idempotent if already claimed by you; issues assigned to a pool alias listed in the claim.pools config are claimable too)") + // Live-claim reassign fence override (bd-98s5c) + updateCmd.Flags().Bool("force", false, "Allow -a/--assignee to overwrite another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim)") // Conditional (compare-and-set) update guards (bd-wsqvw) updateCmd.Flags().String("if-assignee", "", "Apply the update only if the current assignee equals this value (--if-assignee '' requires unassigned); a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim") updateCmd.Flags().String("if-status", "", "Apply the update only if the current status equals this value; a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim") + // --force (unconditional bypass of the reassign fence) and --if-assignee + // (write only while a specific assignee still holds it) encode + // contradictory intent — same rationale as unclaim's pairing. Rejecting the + // combination stops a script that habitually passes --force from silently + // dropping its --if-assignee guard. + updateCmd.MarkFlagsMutuallyExclusive("force", "if-assignee") updateCmd.Flags().String("session", "", "Claude Code session ID for status=closed (or set CLAUDE_SESSION_ID env var)") // Time-based scheduling flags (GH#820) // Examples: diff --git a/cmd/bd/update_input.go b/cmd/bd/update_input.go index 3e6bb9a03..7b2da3dd4 100644 --- a/cmd/bd/update_input.go +++ b/cmd/bd/update_input.go @@ -35,6 +35,9 @@ type updateInput struct { // guard). ifAssignee *string ifStatus *string + // bd-98s5c: --force bypasses the live-claim reassign fence (mutually + // exclusive with --if-assignee at the flag-group level). + force bool } func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, error) { @@ -76,6 +79,7 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, e assignee, _ := cmd.Flags().GetString("assignee") in.fields["assignee"] = assignee } + in.force, _ = cmd.Flags().GetBool("force") description, descChanged, err := getDescriptionFlag(cmd) if err != nil { return nil, HandleErrorRespectJSON("%v", err) diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index e698b737b..da6ce69a6 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -159,6 +159,24 @@ func applyUpdateProxiedAttempt(ctx context.Context, id string, in *updateInput) return nil, &updateIDFailure{ID: id, Error: err.Error()}, false, nil } + // bd-98s5c: an unguarded assignee update must not silently overwrite + // another actor's live claim. Skipped under --if-assignee: that CAS names + // the holder explicitly (park stays possible without --force). Also + // skipped under --claim: the claim CAS is itself the anti-steal gate (a + // foreign live claim fails it with the canonical "already claimed" copy), + // and an assignee edit that rides a WON claim only ever touches the + // actor's own fresh claim. The proxied-server path is where cross-actor + // collisions actually happen — every shared-dolt-server clone writes + // through here. A policy refusal: terminal per-issue failure, exit 1, + // never GuardMismatch/13. + if newAssignee, ok := in.fields["assignee"].(string); ok && in.ifAssignee == nil && !in.claim { + if err := validateIssueReassignable(id, current, actor, newAssignee, + uowClaimPoolAliases(ctx, uw), in.force); err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + return nil, &updateIDFailure{ID: id, Error: err.Error()}, false, nil + } + } + spec := buildUpdateSpecForIssue(current, in) notesOverwritten := replacesExistingNotes(current.Notes, in.fields) diff --git a/internal/storage/issueops/claim.go b/internal/storage/issueops/claim.go index f5602052d..29e328bfc 100644 --- a/internal/storage/issueops/claim.go +++ b/internal/storage/issueops/claim.go @@ -260,13 +260,22 @@ func ClaimPoolAliasesInTx(ctx context.Context, tx DBTX) ([]string, error) { if err != nil { return nil, err } + return ParseClaimPools(raw), nil +} + +// ParseClaimPools parses a raw claim.pools config value (comma-separated, +// whitespace-trimmed) into the pool alias list. Shared by the claim CAS +// (ClaimPoolAliasesInTx, and its domain/db dual) and the cmd-layer reassign +// fence (bd-98s5c), so the alias set can never drift between --claim and +// -a/--assignee — the two verbs must agree on which holders are pools. +func ParseClaimPools(raw string) []string { var pools []string for _, p := range strings.Split(raw, ",") { if p = strings.TrimSpace(p); p != "" { pools = append(pools, p) } } - return pools, nil + return pools } // ClaimableSourceStatusesInTx returns the set of statuses an issue may be diff --git a/internal/validation/issue.go b/internal/validation/issue.go index b5995baa1..195850047 100644 --- a/internal/validation/issue.go +++ b/internal/validation/issue.go @@ -2,6 +2,7 @@ package validation import ( "fmt" + "slices" "github.com/steveyegge/beads/internal/types" ) @@ -86,6 +87,46 @@ func AssigneeMatches(actor string, force bool) IssueValidator { } } +// AssigneeNotStolen validates that a plain assignee update does not silently +// overwrite another actor's live claim (bd-98s5c). newAssignee is the value +// the write would set (may be "" for an unassign — fenced the same way, since +// stripping a live claim is what bd unclaim refuses without --force). +// +// The refusal fires only when every clause holds; each one is load-bearing: +// - Assignee != "" — unassigned issues are freely assignable. +// - Assignee != actor — an actor editing its own claim is untouched. +// - Assignee != newAssignee — an idempotent re-assert of the current holder +// stays a success (retry/replay safety on the proxied path). +// - Status == in_progress — reassigning an OPEN bead stays frictionless: +// dispatchers hand-dole open beads and pool-queue takes happen constantly, +// which is why this cannot reuse the unclaim/close ownership rule verbatim. +// - holder is not a claim.pools alias — --claim deliberately treats +// pool-assigned issues as takeable by any actor; without the same +// carve-out here, --claim and -a would give opposite answers on the same +// bead. poolAliases is a thunk so call sites don't pay the config read on +// the overwhelmingly common non-conflicting paths. +// +// Like AssigneeMatches, authority is identity-by-string: bd has no identity +// layer, so this removes silent cross-actor takeovers without adding new +// identity guarantees. +func AssigneeNotStolen(actor, newAssignee string, poolAliases func() []string, force bool) IssueValidator { + return func(id string, issue *types.Issue) error { + if issue == nil || force { + return nil + } + if issue.Assignee == "" || issue.Assignee == actor || issue.Assignee == newAssignee { + return nil + } + if issue.Status != types.StatusInProgress { + return nil + } + if poolAliases != nil && slices.Contains(poolAliases(), issue.Assignee) { + return nil + } + return fmt.Errorf("cannot reassign %s: held by %q (in_progress); coordinate with the holder (bd mail %s) — pass --force only if their claim is abandoned (crashed agent, expired lease), or use bd reclaim", id, issue.Assignee, issue.Assignee) + } +} + // NotClosed validates that an issue is not already closed. func NotClosed() IssueValidator { return func(id string, issue *types.Issue) error { diff --git a/internal/validation/issue_test.go b/internal/validation/issue_test.go index 3b6fd0531..c672d97c3 100644 --- a/internal/validation/issue_test.go +++ b/internal/validation/issue_test.go @@ -177,6 +177,131 @@ func TestAssigneeMatches(t *testing.T) { } } +func TestAssigneeNotStolen(t *testing.T) { + inProgress := func(assignee string) *types.Issue { + return &types.Issue{ID: "bd-test", Assignee: assignee, Status: types.StatusInProgress} + } + poolsCalled := false + pools := func() []string { + poolsCalled = true + return []string{"fable-crew", "night-crew"} + } + + tests := []struct { + name string + issue *types.Issue + actor string + newAssignee string + pools func() []string + force bool + wantErr bool + }{ + { + name: "nil issue passes (delegated check)", + issue: nil, + actor: "alice", + wantErr: false, + }, + { + name: "unassigned in_progress issue is freely assignable", + issue: inProgress(""), + actor: "alice", + newAssignee: "bob", + wantErr: false, + }, + { + name: "actor editing its own claim passes", + issue: inProgress("alice"), + actor: "alice", + newAssignee: "bob", + wantErr: false, + }, + { + name: "idempotent re-assert of the current holder passes", + issue: inProgress("bob"), + actor: "alice", + newAssignee: "bob", + wantErr: false, + }, + { + name: "reassigning an OPEN assigned bead stays frictionless", + issue: &types.Issue{ID: "bd-test", Assignee: "bob", Status: types.StatusOpen}, + actor: "alice", + newAssignee: "carol", + wantErr: false, + }, + { + name: "live foreign claim refuses without force", + issue: inProgress("bob"), + actor: "alice", + newAssignee: "carol", + wantErr: true, + }, + { + name: "unassign of a live foreign claim refuses (unclaim's rule)", + issue: inProgress("bob"), + actor: "alice", + newAssignee: "", + wantErr: true, + }, + { + name: "live foreign claim with force passes", + issue: inProgress("bob"), + actor: "alice", + newAssignee: "carol", + force: true, + wantErr: false, + }, + { + name: "claim.pools alias holder is takeable (matches --claim)", + issue: inProgress("fable-crew"), + actor: "alice", + newAssignee: "alice", + pools: pools, + wantErr: false, + }, + { + name: "nil pool thunk fails closed on a foreign claim", + issue: inProgress("fable-crew"), + actor: "alice", + newAssignee: "alice", + pools: nil, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := AssigneeNotStolen(tt.actor, tt.newAssignee, tt.pools, tt.force)("bd-test", tt.issue) + if (err != nil) != tt.wantErr { + t.Errorf("AssigneeNotStolen() error = %v, wantErr %v", err, tt.wantErr) + } + if err != nil { + // The copy must name the holder, point at coordination, and + // name --force explicitly (so script authors can adopt it + // deterministically) — never an eviction recipe like the old + // "use bd unclaim" claim-refusal copy (wy-zs5s2 item 2). + for _, frag := range []string{"held by", "coordinate with the holder", "--force", "bd mail"} { + if !strings.Contains(err.Error(), frag) { + t.Errorf("AssigneeNotStolen() error %q should contain %q", err.Error(), frag) + } + } + } + }) + } + + // The pool thunk must be consulted only after the cheap clauses pass — + // call sites hand it a live config read, and routine dispatch (open-bead + // reassigns, self-edits) must not pay that round trip. + poolsCalled = false + if err := AssigneeNotStolen("alice", "bob", pools, false)("bd-test", &types.Issue{ID: "bd-test", Assignee: "bob", Status: types.StatusOpen}); err != nil { + t.Errorf("open-bead reassign should pass, got %v", err) + } + if poolsCalled { + t.Errorf("pool thunk consulted on an open-bead reassign; the config read should be lazy") + } +} + func TestNotClosed(t *testing.T) { tests := []struct { name string