beads/issueops/errors.go
Julian Knutsen d801ec43dc
feat(issueops): put every issue capability behind one library surface
Beads had two implementations of most issue verbs: one for the direct route
(the CLI talking to a store it opened itself) and one for the proxied-server
route (the CLI talking through a unit of work over a running Dolt server).
They drifted — different commit messages, different transaction boundaries,
different refusals, occasionally different answers.

Seven role interfaces now live in the leaf package issueops: Lifecycle,
Reader, ReadyClaimer, BatchCloser, DependencyEditor, Commenter and Relations.
Each is reached only through a store accessor, never a constructor, because
the accessor is where the hook and telemetry decorators add their layers.
Three implementations back every role — dolt, embeddeddolt, and the
unit-of-work provider the proxied route uses. Both routes call the same role
for close, dep add/remove/list, comment, ready --claim and update.

A depguard rule (httpapi-domain-boundary) denies internal/storage/domain from
internal/httpapi, so a handler cannot reach uw.IssueUseCase() past the roles
and open a second front door one lint-clean commit at a time.

Behaviour users will notice, all in the CHANGELOG:
  - bd close a b c is one Dolt commit, not three, and --claim-next moved
    inside that transaction so it fires only when something landed
  - the open-children guard moved into the transaction and its hand-rolled
    cmd/bd copy is gone, removing a read-then-write window that made
    bd close <child> <parent> depend on argument order
  - bd dep add --file honours deferred version commit
  - embedded bd comment writes the role's message and author
  - dep verb commit messages are the role's on the direct route

Wisp-sourced dependency edges are restored. Moving bd dep add onto the role
had pinned an edge's SOURCE to the issues plane, and the two routes did not
even fail alike: direct refused with "issue <id> not found", proxied threw an
fk_dep_issue violation. The comment justifying the pin claimed the issues
plane was "the only one its unit-of-work sibling can reach" — that was false;
domain.DependencyUseCase declared a full set of wisp twins with no production
caller. All three implementations now route per edge by the edge's own
source. A mixed request stays one transaction: parent-child-first ordering
and the whole-graph cycle gate span both planes, and a refusal rolls back
both. Behind the role, three bulk add verbs collapsed into one source-routed
AddDependencies, so no plane-pinned variant is left to reach for by mistake.

Six Provenance fields with no production caller were deleted rather than
wired — CloseRequest, CloseBatchRequest, ClaimNextRequest, AddCommentRequest,
AddDependenciesRequest, RemoveDependencyRequest. Each role already composes an
id-bearing message, so a caller could only restate the default and make it
unreachable from production. Two are not caller-settable even in principle:
CloseBatchCommitMessage names what LANDED and ClaimNextCommitMessage names the
id the claim WON. UpdateRequest and ReopenRequest keep theirs; commit messages
users see are unchanged.

Verified: build, vet and gofmt clean; golangci-lint 0 issues; protocol corpus
byte-identical under BEADS_PROTOCOL_REQUIRE_DOLT=1; all twelve
DependencyEditor conformance wirings green (four contract functions against
each implementation); TestEmbeddedDepAddWispSource runs bd dep add <wisp-id>
at the front door and was demonstrated RED against the pinned routing first.
Three internal/storage/dolt failures reproduce on pristine origin/main.

Known gaps are enumerated in the PR description rather than left to be found:
comment listing is on no role, bd dep tree and bd dep cycles have no role,
bd create and bd reopen are on Lifecycle only on the direct route, per-edge
line attribution is lost in bd dep add --file, multi-store bd close
--claim-next rides only the first store's batch, and the is_blocked staging gap
(bd-2y9ke, predates this change). Seven of the eight role interfaces now have a
shared conformance contract in backend/conformance, run at all three
implementations; main's Claimer, added in parallel by #5334, is the eighth and
has none yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-04 12:27:56 -07:00

173 lines
7.8 KiB
Go

package issueops
import (
"errors"
"fmt"
)
// ErrAlreadyClaimed is returned when attempting to claim an issue that is already
// claimed by another user. The error message contains the current assignee.
var ErrAlreadyClaimed = errors.New("issue already claimed")
// ErrNotClaimable is returned when attempting to claim an issue that is not in a
// claimable state, such as closed, deferred, or already in progress without the
// same actor owning the claim.
var ErrNotClaimable = errors.New("issue not claimable")
// ClaimConflictError reports the state that refused a claim — the current
// assignee and status, read inside the same transaction that lost the
// compare-and-set. It wraps the refusal rather than replacing it, so the
// sentinel still matches, the refusal's carefully-worded prose survives
// byte-for-byte, and a caller can classify the conflict from typed fields
// instead of parsing that prose.
//
// Err is set by every implementation that returns this type; a Claimer whose
// same-transaction re-read fails returns the bare refusal instead.
type ClaimConflictError struct {
// IssueID names the issue that refused the claim.
IssueID string
// Assignee is the holder observed by the losing transaction. It is empty
// when the refusal was about the status rather than a foreign holder.
Assignee string
// Status is the status observed by the losing transaction.
Status Status
// Err is the wrapped refusal. It matches ErrAlreadyClaimed or
// ErrNotClaimable.
Err error
}
func (e *ClaimConflictError) Error() string { return e.Err.Error() }
// Unwrap makes ClaimConflictError match the refusal it carries.
func (e *ClaimConflictError) Unwrap() error { return e.Err }
// ErrUnsupported reports something the caller asked for that this backend
// cannot serve — a capability accessor it does not implement, or a request
// field it will not honor. It is a TYPE rather than a sentinel because the
// two facts a caller needs are which operation refused and which backend
// refused it, and neither survives a formatted string.
//
// A backend returns it instead of quietly doing something narrower. The case
// that made that rule explicit is Reader's Offset: the store-backed body
// rendered LIMIT without OFFSET, so a caller that paged with it received the
// first page over and over with no error to notice.
//
// It lives here so a caller holding only a role interface can classify the
// refusal with errors.As without importing internal/storage.
type ErrUnsupported struct {
Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues"
Backend string // e.g. "dolt-server"
}
func (e *ErrUnsupported) Error() string {
return fmt.Sprintf("operation %q not supported by the %s backend", e.Op, e.Backend)
}
// ErrAssigneeMismatch is returned by UnclaimIssueIfAssignee when the issue's
// current assignee does not match the expected assignee (including when the
// issue is no longer assigned at all). The caller's view of the claim was
// stale; the issue is left untouched.
var ErrAssigneeMismatch = errors.New("assignee mismatch")
// ErrNotFound is returned when a requested entity does not exist in the database.
var ErrNotFound = errors.New("not found")
// ErrValidation classifies deterministic request-validation failures.
var ErrValidation = errors.New("validation failed")
// ErrNotInitialized is returned when the database has not been initialized
// (e.g., issue_prefix config is missing).
var ErrNotInitialized = errors.New("database not initialized")
// ErrPrefixMismatch is returned when an issue ID does not match the configured prefix.
var ErrPrefixMismatch = errors.New("prefix mismatch")
// ErrCloseBlocked is returned by CloseIssueChecked when an issue cannot be
// closed because it is still blocked (is_blocked=1: an open blocking dependency
// or an open blocking gate). Bypass with CloseIssueOptions.Force.
var ErrCloseBlocked = errors.New("cannot close blocked issue")
// ErrCloseOpenChildren is returned when an unforced close finds open
// parent-child dependents.
var ErrCloseOpenChildren = errors.New("cannot close issue with open children")
// CloseOpenChildrenError reports the issue and open-child count that refused a
// guarded close.
type CloseOpenChildrenError struct {
IssueID string
OpenChildren int
}
func (e *CloseOpenChildrenError) Error() string {
return fmt.Sprintf("cannot close %s: %d open child issue(s); close children first or use --force to override", e.IssueID, e.OpenChildren)
}
// Unwrap makes CloseOpenChildrenError match ErrCloseOpenChildren.
func (e *CloseOpenChildrenError) Unwrap() error {
return ErrCloseOpenChildren
}
// ErrAlreadyExists is returned when a create operation is given an ID that is
// already occupied. The issue and wisp tables share one ID space.
var ErrAlreadyExists = errors.New("issue already exists")
// ErrVersionMismatch is returned by a *Checked op given an ExpectedVersion that
// no longer matches the row's current version (row_lock) — an optimistic
// concurrency failure. Callers errors.Is it to distinguish a lost-update
// precondition from other errors.
var ErrVersionMismatch = errors.New("version mismatch")
// ErrStatusMismatch is returned by UpdateIssueChecked given an ExpectedStatus
// that no longer matches the issue's current status. The caller's view of the
// issue was stale; the issue is left untouched. The assignee analog is
// ErrAssigneeMismatch, shared with UnclaimIssueIfAssignee.
var ErrStatusMismatch = errors.New("status mismatch")
// ErrSelfDependency is returned when a dependency edge would point an issue at
// itself. It is the static prefix of the formatted message, wrapped so callers
// can errors.Is it while the human-readable text is preserved byte-for-byte.
var ErrSelfDependency = errors.New("cannot add self-dependency")
// ErrDependencyCycle is returned when adding a dependency edge would introduce a
// scheduling cycle. It is scoped to the dependency-add family — the single and
// bulk add paths (add/AddDependencies) and the dolt cross-tier check — so
// callers can errors.Is any dependency-add cycle rejection. The whole-graph
// construction paths (ApplyIssueGraph/ApplyWispGraph) are a separate family and
// deliberately do not carry this sentinel yet.
var ErrDependencyCycle = errors.New("adding dependency would create a cycle")
// DependencyTypeConflictError is returned when an edge already exists between
// the same pair with a DIFFERENT type. Its message is byte-identical to the
// embedded issueops path (internal/storage/issueops/dependencies.go) so
// `bd dep add` surfaces the same user-facing retype error on the domain/db seam
// as on the embedded store. It is a typed error so the use-case can pass it
// through unwrapped instead of burying it under an "add dep: insert:" prefix.
type DependencyTypeConflictError struct {
IssueID string
DependsOnID string
ExistingType string
RequestedType string
}
func (e *DependencyTypeConflictError) Error() string {
return fmt.Sprintf("dependency %s -> %s already exists with type %q (requested %q); remove it first with 'bd dep remove' then re-add",
e.IssueID, e.DependsOnID, e.ExistingType, e.RequestedType)
}
// DependencyHierarchyConflictError is returned when a blocking dependency
// would gate an issue on one of its own ancestors or descendants. Either shape
// can never clear under the parent-child close/blocking semantics.
type DependencyHierarchyConflictError struct {
IssueID string
BlockerID string
BlockerIsAncestor bool
}
func (e *DependencyHierarchyConflictError) Error() string {
if e.BlockerIsAncestor {
return fmt.Sprintf("%s cannot be blocked by its ancestor %s: %s cannot close until its descendants finish, so the gate would never clear",
e.IssueID, e.BlockerID, e.BlockerID)
}
return fmt.Sprintf("%s cannot be blocked by its descendant %s: blocked status cascades to descendants, so %s would inherit the block and never close",
e.IssueID, e.BlockerID, e.BlockerID)
}