* fix(bd): canonicalize actor==assignee comparisons in unclaim.go and AuthorizeAssigneeTransferWithPools Follow-up to ga-wzl83, which canonicalized the two pure-Go validators in internal/validation/issue.go but explicitly left out two higher-risk sites. UnclaimIssueInTx / UnclaimIssueIfAssigneeInTx compared actor/expectedAssignee to the stored assignee verbatim, both in a Go-side precheck AND in the SQL UPDATE's WHERE clause -- so canonicalizing only the Go side would not have fixed `bd unclaim` end-to-end. Replaced the `assignee = ?` SQL predicate with a `row_lock = ?` CAS against the RowVersion read moments earlier: every ownership/status/started_at mutation always rewrites row_lock (the documented freshRowLock invariant in lease.go), so this detects the exact same race the old predicate did -- and more (status/started_at races too) -- without embedding a spelling-sensitive string comparison in SQL. AuthorizeAssigneeTransferWithPools (the single fence both the DBTX and unit-of-work backends evaluate, per its own doc comment) compared before.Assignee to request.Actor and to request.Patch.Assignee.Value verbatim, so a caller naming the current holder under a different layer's identity spelling was wrongly fenced as a stranger. Both fixes reuse the canonicalActor/actorMatches shape from ga-wzl83, kept as a small package-local duplicate in issueops (internal/storage/issueops importing internal/validation would invert the layering). Verified: new cross-spelling cases in aggregate_authorize_transfer_test.go and new end-to-end cases in unclaim_embedded_test.go / unclaim_conditional_embedded_test.go (against a real embedded Dolt backend) all fail with the exact bug-report symptom against the pre-fix code and pass after the fix, with no regressions in the existing suites. ga-5ksp5 * fix(bd): close the sibling-CAS disagreement gate review flagged on #5439 Review verdict on #5439 was "MERGE AFTER ONE FIX": after this branch's unclaim.go/aggregate.go fix, bd unclaim --if-assignee succeeds under a respelled identity while bd update --expected-assignee on the same bead still fails ErrAssigneeMismatch — the same verbatim actor==assignee defect (ga-wzl83), left in two more places. - internal/storage/issueops/update_cas.go:46 (CheckExpectedFieldsInTx) now compares under actorMatches (package-local, unexported — same package as identity.go, no new import needed). - internal/storage/domain/issue.go:643 (ApplyUpdate, the unit-of-work twin) now compares under validation.ActorMatches. domain cannot import internal/storage/issueops (issueops already imports domain in several files — the reverse would cycle), but domain -> internal/validation is safe (validation depends only on internal/types), so this reuses the already-shipped validation copy instead of adding a third duplicate. Two non-blocking asks from the same review, addressed: - Exported internal/validation's canonicalActor/actorMatches to CanonicalActor/ActorMatches so domain/issue.go could reuse them (the reviewer's own point: "an issueops -> validation import creates no cycle... layering inversion is a style call, not a compile fact" applies equally to domain -> validation). Also fixed a garbled mid-sentence doc comment on ActorMatches while touching the file (separate nit from the same review, on #5438). - Added a cross-package parity test (internal/storage/issueops/identity_parity_test.go) that runs the existing CanonicalActor/ActorMatches case tables through both this package's local duplicate and validation's exported version, so the two copies can't silently drift. Mutation-tested: dropped the hyphen separator from issueops's copy, confirmed the two hyphen-related cases correctly fail, reverted. New conformance test (backend/conformance, wired into all three backend legs) proves the fix end-to-end: an ExpectedAssignee guard now accepts a different spelling of the current holder and still refuses a genuinely different identity. Added as a SEPARATE function rather than extending the existing RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits — that test's later "order-dependent composition" arm depends on the row's assignee staying exactly "holder" through to the end, which a mid-test respelling would have broken. Verification: internal/validation, internal/storage/issueops, internal/storage/domain(+db,fs,git) all green. New conformance test passes on embeddeddolt and uow (dolt backend skips locally, no Docker — matches the existing documented limitation, CI covers it). Broader regression subset (Update/Claim/Unclaim, 28 embeddeddolt + 22 uow cases) green, no regressions. go build/vet/gofmt clean. Filed ga-4ymii for the reviewer's second (also non-blocking) ask: the remaining verbatim sites at issueops/claim.go (SQL CAS + idempotent re-claim), its domain/db and domain/issue.go uow twins, and issueops/lease.go's heartbeat holder check — out of scope for this PR per the reviewer's own framing ("please file the follow-up"). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(bd): dispatch the respelled-assignee contract case onto the role seam TestRoleContractCasesCoverEveryContractCase (main, post-dating this branch's fork point) caught a real gap: the ga-5ksp5 contract case added to this branch's earlier commit (RunIssueOperationsUpdateConditionalGuardAccepts- RespelledAssignee) had no roleContractCases dispatch row, so an external backend running RunRoleContracts would never see it. The reason isn't a missed row so much as the whole RunIssueOperationsUpdate* family this case was written beside having been renamed and moved to RunLifecycleUpdate* in backend/conformance/lifecycle_update_contract.go by main's "de-stage the hard Lifecycle contracts onto the role seam" refactor, which landed on main after this branch forked. Ported the case to match: same logic, adapted to the new fixture's idioms (fixture.Lifecycle.Update instead of fixture.Operations.Update, lifecycleUpdateRow(...).Priority instead of a raw SQL assertion, storage.ErrAssigneeMismatch instead of publicops.ErrAssigneeMismatch, seedLifecycleUpdateIssue instead of seedClosePolicyIssue) — not a mechanical copy. Also wired it into the three per-backend TestLifecycleUpdateContract dispatch lists (dolt, embeddeddolt, uow) beside its ConditionalGuardsGateOrdinaryEdits sibling, so it actually runs against real backends rather than only satisfying the completeness guard. Verified: TestRoleContractCasesCoverEveryContractCase passes; the ported case passes against embeddeddolt (0.35s) and uow (0.17s) for real, not just compiles (dolt backend test skips in this sandbox — no Docker); full backend/conformance suite and repo build clean. --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
307 lines
11 KiB
Go
307 lines
11 KiB
Go
package validation
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// IssueValidator validates an issue and returns an error if validation fails.
|
|
// Validators can be composed using Chain() for complex validation logic.
|
|
type IssueValidator func(id string, issue *types.Issue) error
|
|
|
|
// Chain composes multiple validators into a single validator.
|
|
// Validators are executed in order and the first error stops the chain.
|
|
func Chain(validators ...IssueValidator) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
for _, v := range validators {
|
|
if err := v(id, issue); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Exists validates that an issue is not nil.
|
|
func Exists() IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil {
|
|
return fmt.Errorf("issue %s not found", id)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// NotTemplate validates that an issue is not a template.
|
|
// Templates are read-only and cannot be modified.
|
|
func NotTemplate() IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil {
|
|
return nil // Let Exists() handle nil check if needed
|
|
}
|
|
if issue.IsTemplate {
|
|
return fmt.Errorf("cannot modify template %s: templates are read-only; use 'bd mol pour' to create a work item", id)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// NotPinned validates that an issue is not pinned, by either of the two ways
|
|
// bd expresses a pin: the Pinned boolean column or the pinned status. Returns
|
|
// an error if either trigger fires, unless force is true.
|
|
//
|
|
// Both triggers are load-bearing because consumers disagree on which one they
|
|
// write and read (ga-z3vht). Gas Town pins by status — it enumerates pins with
|
|
// List(ListOptions{Status: StatusPinned}) across 21 sites (hook_check.go,
|
|
// prime_output.go, molecule_step.go, up.go) — while Gas City reads the boolean
|
|
// (compute_awake_set.go). Checking only one strips the other consumer's
|
|
// protection outright, so do not "simplify" either clause away.
|
|
func NotPinned(force bool) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil {
|
|
return nil // Let Exists() handle nil check if needed
|
|
}
|
|
if !force && (issue.Pinned || issue.Status == types.StatusPinned) {
|
|
return fmt.Errorf("cannot modify pinned issue %s (use --force to override)", id)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// CanonicalActor normalizes an identity string so two spellings of the same
|
|
// Gas Town identity compare equal. The same identity arrives at bd in more
|
|
// than one spelling depending on which layer produced the string it was
|
|
// handed: a dotted alias like "gastown.mayor" gets its dot replaced wherever
|
|
// a dot is unsafe for that context — "__" in a session name, "_" in a Dolt
|
|
// table/database name, "-" elsewhere — and bd only ever sees the resulting
|
|
// string, never the substitution itself (ga-wzl83). None of ".", "_", "-"
|
|
// carries meaning in an identity string: each is always a positional
|
|
// separator between a rig and a role/agent name, never part of either name.
|
|
// Collapsing any run of them to one canonical separator lets two spellings
|
|
// of the same identity compare equal without weakening comparisons between
|
|
// genuinely different identities, whose non-separator characters still
|
|
// differ (e.g. "gastown.mayor" vs "gastown.dog-3" stay distinct).
|
|
//
|
|
// Empty stays empty: an actual absence of an actor must never canonicalize
|
|
// to the same value as a non-empty one, or AssigneeMatches would start
|
|
// accepting an empty actor against an assigned issue.
|
|
func CanonicalActor(s string) string {
|
|
if s == "" {
|
|
return ""
|
|
}
|
|
var b strings.Builder
|
|
b.Grow(len(s))
|
|
inSeparator := false
|
|
for _, r := range s {
|
|
switch r {
|
|
case '.', '_', '-':
|
|
if !inSeparator {
|
|
b.WriteByte('_')
|
|
inSeparator = true
|
|
}
|
|
default:
|
|
b.WriteRune(r)
|
|
inSeparator = false
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// ActorMatches reports whether actor has the same authority as assignee:
|
|
// either they're byte-identical, or they canonicalize to the same identity
|
|
// (see CanonicalActor). The byte-identical check is not redundant — it
|
|
// avoids paying canonicalization on the overwhelmingly common exact-match
|
|
// path (ga-5ksp5 gate review, #5438: fixes a garbled doc comment, no
|
|
// behavior change).
|
|
func ActorMatches(assignee, actor string) bool {
|
|
return assignee == actor || CanonicalActor(assignee) == CanonicalActor(actor)
|
|
}
|
|
|
|
// AssigneeMatches validates that the actor has authority to close the issue.
|
|
// Authority means the issue is unassigned or the actor matches the current
|
|
// assignee. Returns an error on mismatch unless force is true.
|
|
//
|
|
// Authority is identity-by-string: actor is compared to assignee under
|
|
// CanonicalActor, so two principals sharing one canonical actor name both
|
|
// pass — including the same principal spelled two different ways by two
|
|
// different layers of Gas Town (ga-wzl83). bd has no identity layer, so this
|
|
// matches the existing semantics of the actor field — the guard removes
|
|
// silent cross-actor closes without adding new identity guarantees.
|
|
//
|
|
// This guards against the silent-success bug where actor A closes a bead that
|
|
// was concurrently re-claimed by actor B: storage accepts the close (id-only
|
|
// WHERE clause), so without this check bd reports "✓ Closed" even though A had
|
|
// no authority over the bead. (be-035)
|
|
func AssigneeMatches(actor string, force bool) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil || force {
|
|
return nil
|
|
}
|
|
if issue.Assignee == "" || ActorMatches(issue.Assignee, actor) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override", id, issue.Assignee, actor)
|
|
}
|
|
}
|
|
|
|
// 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 doesn't canonicalize to actor — an actor editing its
|
|
// own claim is untouched, under any spelling of its own identity.
|
|
// - Assignee doesn't canonicalize to newAssignee — an idempotent re-assert
|
|
// of the current holder stays a success (retry/replay safety on the
|
|
// proxied path), even when the re-assert names the holder under a
|
|
// different spelling.
|
|
// - 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 — compared under
|
|
// CanonicalActor rather than verbatim (ga-wzl83), so this removes silent
|
|
// cross-actor takeovers without adding new identity guarantees, and without
|
|
// falsely treating the current holder as a stranger when actor or
|
|
// newAssignee names it under a different layer's spelling of the same
|
|
// identity.
|
|
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 == "" || ActorMatches(issue.Assignee, actor) || ActorMatches(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 {
|
|
if issue == nil {
|
|
return nil
|
|
}
|
|
if issue.Status == types.StatusClosed {
|
|
return fmt.Errorf("issue %s is already closed", id)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// NotHooked validates that an issue is not in hooked status.
|
|
func NotHooked(force bool) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil {
|
|
return nil
|
|
}
|
|
if !force && issue.Status == types.StatusHooked {
|
|
return fmt.Errorf("cannot modify hooked issue %s (use --force to override)", id)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// HasStatus validates that an issue has one of the allowed statuses.
|
|
func HasStatus(allowed ...types.Status) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil {
|
|
return nil
|
|
}
|
|
for _, status := range allowed {
|
|
if issue.Status == status {
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("issue %s has status %s, expected one of: %v", id, issue.Status, allowed)
|
|
}
|
|
}
|
|
|
|
// HasType validates that an issue has one of the allowed types.
|
|
func HasType(allowed ...types.IssueType) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil {
|
|
return nil
|
|
}
|
|
for _, t := range allowed {
|
|
if issue.IssueType == t {
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("issue %s has type %s, expected one of: %v", id, issue.IssueType, allowed)
|
|
}
|
|
}
|
|
|
|
// EpicHasOpenChildren validates that an epic does not have open children.
|
|
// If the issue is an epic with open children, returns an error unless force is true.
|
|
// Non-epic issues pass through without validation.
|
|
func EpicHasOpenChildren(force bool, openChildCount int) IssueValidator {
|
|
return func(id string, issue *types.Issue) error {
|
|
if issue == nil || force {
|
|
return nil
|
|
}
|
|
if issue.IssueType != types.TypeEpic {
|
|
return nil
|
|
}
|
|
if openChildCount > 0 {
|
|
return fmt.Errorf("epic %s has %d open child issue(s); close children first or use --force to override", id, openChildCount)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// forUpdate returns a validator chain for update operations.
|
|
// Validates: issue exists and is not a template.
|
|
func forUpdate() IssueValidator {
|
|
return Chain(
|
|
Exists(),
|
|
NotTemplate(),
|
|
)
|
|
}
|
|
|
|
// forClose returns a validator chain for close operations.
|
|
// Validates: issue exists, is not a template, and is not pinned (unless force).
|
|
func forClose(force bool) IssueValidator {
|
|
return Chain(
|
|
Exists(),
|
|
NotTemplate(),
|
|
NotPinned(force),
|
|
)
|
|
}
|
|
|
|
// forDelete returns a validator chain for delete operations.
|
|
// Validates: issue exists and is not a template.
|
|
func forDelete() IssueValidator {
|
|
return Chain(
|
|
Exists(),
|
|
NotTemplate(),
|
|
)
|
|
}
|
|
|
|
// forReopen returns a validator chain for reopen operations.
|
|
// Validates: issue exists, is not a template, and is closed.
|
|
func forReopen() IssueValidator {
|
|
return Chain(
|
|
Exists(),
|
|
NotTemplate(),
|
|
HasStatus(types.StatusClosed),
|
|
)
|
|
}
|