* feat(metadata): MergeMetadata — atomic single-key metadata merge
SlotSet did a read-modify-write across TWO transactions: GetIssue (tx 1),
metadata[key]=value in memory, then UpdateIssue (tx 2). Two concurrent SlotSet
calls — even on DIFFERENT keys — both read the same base metadata and each
wrote back its whole blob, so the second clobbered the first's key. SlotClear
had the same bug. Add MergeMetadata, which does the read-modify-write inside
ONE transaction (so a concurrent conflict is retried and re-reads), stores a
JSON value (nested objects/arrays, not just strings), and reimplement SlotSet
and SlotClear on top of it so they inherit the atomicity.
- issueops.MergeMetadataInTx / DeleteMetadataInTx: read the metadata (routed
issues/wisps; missing issue -> ErrNotFound), merge/delete the one key, and
write the whole object back THROUGH UpdateIssueInTx — so the operation keeps
everything the old SlotSet got from UpdateIssue (the EventUpdated history
event with actor attribution, the configured metadata-schema validation, and
updated_at), now atomic. The read and write share the caller's transaction,
so a concurrent merge of a different key is retried and re-read, never
clobbered.
- Storage.MergeMetadata implemented on DoltStore (perm withRetryTx +
DOLT_ADD(issues,events) + DOLT_COMMIT; wisp path no commit) and
EmbeddedDoltStore (withConn); forwarded on InstrumentedStorage; auto-promoted
on HookFiringStore; no-op on the configStore mock. SlotSet/SlotClear rebuilt
on it (a string value marshals to a JSON string, byte-compatible with the
historical rewrite).
- Cross-backend conformance covers MergeMetadata + atomic SlotClear; the
8-goroutine concurrent-no-clobber test proves the B1 fix on real Dolt, and
a test asserts the EventUpdated event and schema validation are preserved.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(concurrency): expose a per-row version on Issue reads (RowVersion)
The engine's internal row_lock column — a random non-zero int64 the engine
rewrites on every status/ownership-mutating write and on the generic update
path — was not surfaced on the public types.Issue. Consumers that wanted a
fine-grained optimistic-concurrency token had only updated_at, which is stored
at second granularity, so two same-second writes were indistinguishable. Expose
row_lock read-only as types.Issue.RowVersion so a caller can tell same-second
writes apart.
- types.Issue gains RowVersion int64 (json:"-": a Go-only concurrency token,
never on the CLI/export JSON wire — it is opaque and equality-only). Added
row_lock to the canonical sqlbuild.IssueBaseColumns and a matching scan target
in issueops.ScanIssueFrom; both engine write stacks, wisps, and the counts /
dependents parallel scans share those, so the field hydrates everywhere from a
single-point change. Read-only — no CAS/write behavior (that is a follow-up).
- Doc is precise about coverage: RowVersion changes on claim/close/unclaim and
the generic update path; it does NOT change on some direct-UPDATE paths
(restore, compaction text), which bump updated_at — so a complete change key
combines RowVersion with updated_at, status, and labels. A created row is
already non-zero (create stamps row_lock); 0 only appears on legacy rows
backfilled by migration 0054's DEFAULT 0.
- Tests: RowVersion hydrates on read and on the list path, changes on a mutating
write, distinguishes two same-second writes (identical updated_at, distinct
RowVersion), and never appears on any JSON surface.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(deps): return a typed error on dependency type-conflict
Adding a dependency between a pair that already has an edge of a different type
is a deterministic rejection, but the two engine write paths disagreed on how
they surfaced it: one returned a typed *DependencyTypeConflictError, the other a
plain fmt.Errorf string. So a caller could errors.As the conflict on one path
but had to string-match the message on the other. Make both paths return the
same typed error, and re-export the two dependency-conflict types on the public
beads package so `bd` (and the library's own call sites) classify by errors.As
instead of parsing message text.
- issueops.AddDependencyInTx now returns *domain.DependencyTypeConflictError for
the type-conflict case (byte-identical message — the struct's Error() is the
exact former string, so no string-matcher changes). The hierarchy/cross-type
case already returned *domain.DependencyHierarchyConflictError on both paths;
self-dependency and cycle are already typed sentinels.
- beads.go re-exports DependencyTypeConflictError and
DependencyHierarchyConflictError as type aliases, so errors.As against the
public type matches the value the engine returns.
- Tests assert errors.As + the four fields + the byte-identical message on both
write paths (permanent issues->issues and the wisp-source BeginTx/Commit seam),
and lock the re-exports; the deterministic conflict is returned immediately
(never retried as a transient serialization error).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(deps): emit dependency_added / dependency_removed events
`bd dep add` and `bd dep remove` recorded no event, so the events feed never
surfaced dependency changes even though the event types (types.EventDependencyAdded
/ EventDependencyRemoved) have existed since the original SQLite backend, which
emitted them on every add/remove. The emission was dropped when that backend was
removed for the Dolt-only migration and never ported to the current write paths.
Restore it on both Dolt write plumbings, matching the original shape (an events
row on the source issue: "Added dependency: <src> <type> <target>" /
"Removed dependency on <target>").
- issueops.AddDependencyInTx / RemoveDependencyInTx record the event via
RecordEventInTable on the source's event table (wisp-routed), on the genuine
add/remove only — the idempotent same-type re-add and the no-op remove of a
missing edge record nothing.
- The event is committed with the edge: DoltStore.AddDependency/RemoveDependency
DOLT_ADD `events`, and the transaction-path (RunInTransaction / batch /
graph-apply) methods mark the source's event table dirty (events or wisp_events)
so StageAndCommit commits it — without this the event row would dangle in the
working set.
- Emission is gated to the explicit dep-add/remove verb on both plumbings: the
proxied-server repo only records when the use-case sets DepInsertOpts.EmitEvent,
which create-with-deps (implicit parent-child / --deps / waits-for, via a direct
repo Insert) does not — so `bd create --parent` produces the same history on
either backend (the embedded create path via PersistDependencies likewise emits
nothing).
- Tests on both plumbings: add/remove emit exactly once and commit (verified via
`events AS OF 'HEAD'`), idempotent re-add and no-op remove emit nothing, wisp
sources route to wisp_events, and create-with-deps emits no dependency_added.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(close): optional ExpectedVersion CAS on CloseIssueChecked
CloseIssueChecked guards a close on is_blocked in-transaction, but a caller that
read an issue and then closes it has no way to say "only if it hasn't changed
since I read it" — a lost-update window. Add an optional compare-and-swap on the
row's version (the RowVersion / row_lock token): when the caller supplies an
ExpectedVersion, the close proceeds only if the row still has that version, else
it refuses with a typed ErrVersionMismatch. The version read and the close share
one transaction, so it is a true CAS with no read-then-write gap.
- storage.ErrVersionMismatch (re-exported as beads.ErrVersionMismatch) and
CloseIssueOptions.ExpectedVersion *int64 (nil disables the check; a pointer so
nil "no check" is distinct from "require version 0").
- issueops.CheckVersionInTx reads row_lock (wisp-routed; ErrNotFound on a missing
row) and returns ErrVersionMismatch on divergence. CloseIssueCheckedInTx runs
it FIRST — before the is_blocked guard and before the Force short-circuit, so
Force bypasses only the guard, never the CAS (the version check is an
orthogonal precondition). A mismatch returns before any write, so the tx rolls
back leaving the issue open with no `closed` event (atomic refuse).
- The CAS has two limbs: the read-side check catches a writer that committed
before the close began, and on the retry-wrapped permanent path a commit-time
row_lock conflict is replayed by withRetryTx so the re-read refuses.
- Tests on both stores: match closes, stale refuses atomically (still open, zero
closed events), a committed concurrent write invalidates a captured version,
nil is unchanged behavior, Force does not bypass, missing id → ErrNotFound,
wisp sources route to the wisps table, and an already-closed re-close with the
post-close version stays idempotent (Unchanged).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(close): document RowVersion CAS coverage boundary on ExpectedVersion
Both adoption reviewers flagged that the public ExpectedVersion godoc and the
shared CloseIssueCheckedInTx doc could be misread as a full-row "unchanged"
check. RowVersion (row_lock) only tracks lifecycle/ownership writes
(status/assignee/started_at), so concurrent label, dependency, rename, or
is_blocked writes leave it untouched and are intentionally outside this CAS
boundary. Document that on both sites, grounded in the freshRowLock invariant.
Doc-only; no behavior change.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor(cli): bd close delegates to the engine's guarded close
The embedded `bd close` path ran its own is_blocked pre-check and then closed in
a separate call — a read-then-write TOCTOU that duplicated a guard the engine
provides atomically. The verb now builds CloseIssueOptions and delegates to
CloseIssueChecked, which runs the guard and the close in ONE transaction; the
CLI's duplicated guard is deleted. --force maps to Options.Force; a blocked
close refuses with the blockers named and the --force hint.
Behavior-preserving on purpose (verified against the previous binary):
- The engine guard now uses the exact historical CLI predicate — refuse only on
a LIVE direct blocker (blocked && len(blockers) > 0), not on the bare
denormalized is_blocked column. A transitively-blocked child (is_blocked
inherited from a blocked parent, zero direct blockers) still closes without
--force, and a stale is_blocked with since-closed blockers self-heals, exactly
as before.
- An already-closed issue stays an idempotent success: it still appears in the
--json array and the text report (same output shape), still exits 0, but no
longer produces a spurious closed->closed audit entry, a no-op commit, or the
real-close side effects (molecule auto-close, newly-unblocked, claim-next).
Tests cover: direct blocker refuses atomically (still open) and closes with
--force; transitively-blocked and stale-is_blocked beads close without --force;
already-closed emits in --json alone and in a mixed batch; idempotent exit 0 —
on the engine (both stores) and through the bd binary.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(update): UpdateIssueChecked — optional ExpectedVersion CAS on the update
UpdateIssue applies a field-map update with no optimistic-concurrency option, so
a caller that wants "update only if unchanged since I read it" had to
read-then-write — a lost-update window. Add UpdateIssueChecked: when the caller
supplies an ExpectedVersion (the RowVersion / row_lock token), the version read
and the update share ONE transaction, refusing with the typed ErrVersionMismatch
if the row has moved — a true compare-and-swap. Nil disables the check and is
byte-identical to UpdateIssue, which is left untouched on the hot path.
- storage.UpdateIssueOptions{ExpectedVersion *int64} (aliased as
beads.UpdateIssueOptions) + Storage.UpdateIssueChecked, mirroring the
CloseIssueChecked pattern: CheckVersionInTx runs first inside the same
transaction on every route — the permanent withRetryTx path, the wisp path,
AND the demote route (an update carrying no_history/wisp routes through the
demote flow; a pure demoteToWispInTx extraction lets the check compose
atomically with the row move — verified byte-identical to the old
DemoteToWisp).
- Implemented on DoltStore and EmbeddedDoltStore; InstrumentedStorage wraps it;
HookFiringStore fires on_update only on success (never on a refused update).
- Tests on both stores: match updates and bumps RowVersion; stale refuses
atomically (field unchanged, zero updated events); a committed concurrent
write invalidates a captured version; nil behaves exactly like UpdateIssue;
wisp match/stale; demote-route match (migrates + applies) and stale (still in
issues, unchanged); missing id → ErrNotFound; the hook decorator fires once on
success and never on refusal.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor(cli): proxied bd close delegates to a library checked close
The proxied-server `bd close` path duplicated the close guard in the CLI:
it queried blockers via the dependency use-case, refused with its own message,
and then closed in a separate use-case call. Move the guard into the library —
IssueUseCase gains CloseIssueChecked / CloseWispChecked, which run the same
live-direct-blocker predicate (refuse only on blocked && len(blockers) > 0)
and then the untouched unchecked close — and thin the CLI verb to a single
delegated call. Both `bd close` paths now enforce the guard in the library and
emit the byte-identical refusal: the same storage.ErrCloseBlocked sentinel
("cannot close blocked issue: <id> is blocked by [...]") plus the
"(use --force to override)" hint.
- Guard and close run on the one pinned unit-of-work connection (the whole
close batch is a single transaction), and the guard is read-only and refuses
before any write — a refused id leaves the shared batch transaction clean,
and an all-refused batch skips the commit entirely, exactly as before.
- The unchecked CloseIssue / CloseWisp are untouched: internal closes (molecule
auto-close, gate closes, bd todo done) intentionally stay unguarded.
- Behavior-parity preserved: guard ordering (validate → epic-child → gate →
blocked), exit codes, JSON/batch shape, already-closed handling, audit fields,
and commit-message contents are unchanged; a transitively-blocked bead
(is_blocked with no direct open blocker) still closes without --force, and
--force still bypasses. The guard-failure diagnostic now uses the embedded
path's generic wording (further convergence; nothing matched the old text).
- Tests: use-case level on real Dolt (direct blocker refuses with blockers
named + still open, transitive-only closes, force closes, already-closed
parity, wisp refuse/force) plus the proxied CLI integration suite.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(review): cross-backend dependency-event + RowVersion parity
Maintainer review fixups for PR #4911 (adopt-pr review loop):
- RowVersion: the proxied/domain create (insertIssueRow) and generic Update
paths never stamped or rewrote row_lock, so an issue written through the
proxied-server backend read back RowVersion 0 on create and unchanged on
update -- a stale CAS token that violated the types.Issue.RowVersion
contract on that backend. Stamp a fresh non-zero row_lock on insert (and the
duplicate-key rewrite) and append RowLockClause() to the generic update,
mirroring the classic issueops insert/update invariant. Adds domain/db
regression tests proving CreateIssue/CreateWisp are non-zero and
UpdateIssue/UpdateWisp change it.
- Dependency events: embedded issueops AddDependencyInTx/RemoveDependencyInTx
recorded history unconditionally, so structural create-with-deps
(bd create --parent/--deps/--waits-for) and reparent (bd update --parent)
emitted dependency_added/removed on embedded but were silent on the proxied
backend, diverging issue history for identical commands. Gate the embedded
emit on EmitEvent and thread it through AddDependencyWithOptions /
RemoveDependencyWithOptions on both the store and transaction interfaces:
the plain AddDependency/RemoveDependency are the no-event structural default
(create-with-deps, reparent), while the explicit dep verbs (bd dep add/remove,
bd link, bd relate/unrelate) pass EmitEvent -- matching the proxied
DepInsertOpts.EmitEvent gate. DoltStore stages the events table only when an
event was actually written (GH#2455). Corrects the false
"parity with PersistDependencies" comments and adds symmetric embedded/proxied
dep-event coverage for create-with-parent/deps and structural removal.
- Retain iteration-1 fixups: heal molecules on already-closed re-close,
idempotent proxied checked-close, and documented public Storage growth.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(storage): drop always-constant event param from fireDependencyHookByID (unparam)
golangci-lint (latest, v2.12.2 in CI) unparam flags fireDependencyHookByID:
its `event` parameter always receives hooks.EventUpdate. The parameter was
already effectively constant before this PR (both base call sites passed
EventUpdate); this PR adds two more call sites, all EventUpdate. Remove the
dead parameter and hardcode hooks.EventUpdate at the single runner.Run call.
All four call sites pass hooks.EventUpdate, so behavior is unchanged; go
build, go vet, and a scoped golangci-lint run pass clean.
Maintainer fixup during adoption finalize (PR #4911).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <ci@beads.test>
214 lines
9 KiB
Go
214 lines
9 KiB
Go
package beads_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// TestReExportCloseBlocked proves the public beads.ErrCloseBlocked alias is the
|
|
// same value as the internal sentinel and composes through errors.Is when
|
|
// wrapped — the property CloseIssueChecked callers rely on to detect a guard
|
|
// refusal without importing internal/storage.
|
|
func TestReExportCloseBlocked(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
if beads.ErrCloseBlocked != storage.ErrCloseBlocked {
|
|
t.Error("beads.ErrCloseBlocked is not the internal sentinel value (identity broken)")
|
|
}
|
|
wrapped := fmt.Errorf("x: %w", beads.ErrCloseBlocked)
|
|
if !errors.Is(wrapped, beads.ErrCloseBlocked) {
|
|
t.Errorf("errors.Is(wrapped, beads.ErrCloseBlocked) = false; err = %v", wrapped)
|
|
}
|
|
}
|
|
|
|
// TestReExportVersionMismatch proves the public beads.ErrVersionMismatch alias
|
|
// is the same value as the internal sentinel and composes through errors.Is when
|
|
// wrapped — the property a CloseIssueChecked caller relies on to detect an
|
|
// optimistic-concurrency refusal without importing internal/storage.
|
|
func TestReExportVersionMismatch(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
if beads.ErrVersionMismatch != storage.ErrVersionMismatch {
|
|
t.Error("beads.ErrVersionMismatch is not the internal sentinel value (identity broken)")
|
|
}
|
|
wrapped := fmt.Errorf("x: %w", beads.ErrVersionMismatch)
|
|
if !errors.Is(wrapped, beads.ErrVersionMismatch) {
|
|
t.Errorf("errors.Is(wrapped, beads.ErrVersionMismatch) = false; err = %v", wrapped)
|
|
}
|
|
}
|
|
|
|
// TestUpdateIssueOptionsIsExported proves the public beads.UpdateIssueOptions
|
|
// alias is usable from outside the module and its ExpectedVersion compare-and-
|
|
// swap field round-trips — the type a caller names to opt a
|
|
// Storage.UpdateIssueChecked into optimistic concurrency without importing
|
|
// internal/storage. The zero value must leave ExpectedVersion nil (no check).
|
|
func TestUpdateIssueOptionsIsExported(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
v := int64(7)
|
|
opts := beads.UpdateIssueOptions{ExpectedVersion: &v}
|
|
if opts.ExpectedVersion == nil || *opts.ExpectedVersion != 7 {
|
|
t.Fatalf("ExpectedVersion did not round-trip through the exported alias: %+v", opts)
|
|
}
|
|
if (beads.UpdateIssueOptions{}).ExpectedVersion != nil {
|
|
t.Fatal("zero-value UpdateIssueOptions must have a nil ExpectedVersion (no check)")
|
|
}
|
|
}
|
|
|
|
// TestReExportedSentinelIdentity proves each public sentinel is the SAME value
|
|
// as the internal one it aliases, so errors.Is composes across the package
|
|
// boundary without any bridging.
|
|
func TestReExportedSentinelIdentity(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
cases := []struct {
|
|
name string
|
|
exported error
|
|
internal error
|
|
}{
|
|
{"ErrNotFound", beads.ErrNotFound, storage.ErrNotFound},
|
|
{"ErrAlreadyClaimed", beads.ErrAlreadyClaimed, storage.ErrAlreadyClaimed},
|
|
{"ErrNotClaimable", beads.ErrNotClaimable, storage.ErrNotClaimable},
|
|
{"ErrVersionMismatch", beads.ErrVersionMismatch, storage.ErrVersionMismatch},
|
|
{"ErrSelfDependency", beads.ErrSelfDependency, domain.ErrSelfDependency},
|
|
{"ErrDependencyCycle", beads.ErrDependencyCycle, domain.ErrDependencyCycle},
|
|
{"ErrFieldTooLong", beads.ErrFieldTooLong, types.ErrFieldTooLong},
|
|
}
|
|
for _, tc := range cases {
|
|
if tc.exported != tc.internal {
|
|
t.Errorf("beads.%s is not the internal sentinel value (identity broken)", tc.name)
|
|
}
|
|
}
|
|
}
|
|
|
|
// stubDepRepo satisfies domain.DependencySQLRepository via the embedded
|
|
// interface; only the two methods dependencyUseCaseImpl.add consults before
|
|
// returning a self-dep/cycle sentinel are implemented. Any other call would
|
|
// nil-panic, which keeps the stub honest about the exact surface these
|
|
// branches touch.
|
|
type stubDepRepo struct {
|
|
domain.DependencySQLRepository
|
|
hasCycle bool
|
|
}
|
|
|
|
func (s stubDepRepo) ValidateBlockingHierarchy(context.Context, *types.Dependency) error {
|
|
return nil
|
|
}
|
|
|
|
func (s stubDepRepo) HasCycle(context.Context, string, string) (bool, error) {
|
|
return s.hasCycle, nil
|
|
}
|
|
|
|
// TestReExportedSentinelCatchesRealProductionError drives ACTUAL converted
|
|
// production returns — the domain dependency use case's self-dep and cycle
|
|
// branches — and asserts the PUBLIC aliases match them via errors.Is. This is
|
|
// the property the re-export exists to provide, verified end to end through
|
|
// real code rather than by wrapping a sentinel with itself.
|
|
func TestReExportedSentinelCatchesRealProductionError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
uc := domain.NewDependencyUseCase(stubDepRepo{})
|
|
selfErr := uc.AddDependency(context.Background(),
|
|
&types.Dependency{IssueID: "a", DependsOnID: "a", Type: types.DepBlocks}, "tester")
|
|
if !errors.Is(selfErr, beads.ErrSelfDependency) {
|
|
t.Errorf("errors.Is(real self-dep err, beads.ErrSelfDependency) = false; err = %v", selfErr)
|
|
}
|
|
|
|
uc = domain.NewDependencyUseCase(stubDepRepo{hasCycle: true})
|
|
cycleErr := uc.AddDependency(context.Background(),
|
|
&types.Dependency{IssueID: "a", DependsOnID: "b", Type: types.DepBlocks}, "tester")
|
|
if !errors.Is(cycleErr, beads.ErrDependencyCycle) {
|
|
t.Errorf("errors.Is(real cycle err, beads.ErrDependencyCycle) = false; err = %v", cycleErr)
|
|
}
|
|
}
|
|
|
|
// insertErrDepRepo returns preset errors from the two methods the domain
|
|
// dependency use-case consults before its typed-conflict passthrough branches:
|
|
// ValidateBlockingHierarchy (hierarchy conflict) and Insert (type conflict). Any
|
|
// other call nil-panics through the embedded interface, keeping the stub honest
|
|
// about the surface these branches touch.
|
|
type insertErrDepRepo struct {
|
|
domain.DependencySQLRepository
|
|
hierarchyErr error
|
|
insertErr error
|
|
}
|
|
|
|
func (r insertErrDepRepo) ValidateBlockingHierarchy(context.Context, *types.Dependency) error {
|
|
return r.hierarchyErr
|
|
}
|
|
|
|
func (r insertErrDepRepo) HasCycle(context.Context, string, string) (bool, error) {
|
|
return false, nil
|
|
}
|
|
|
|
func (r insertErrDepRepo) Insert(context.Context, *types.Dependency, string, domain.DepInsertOpts) error {
|
|
return r.insertErr
|
|
}
|
|
|
|
// TestReExportedDependencyConflictTypes proves the public
|
|
// beads.DependencyTypeConflictError and beads.DependencyHierarchyConflictError
|
|
// aliases are the SAME struct types the engine returns: driving ACTUAL domain
|
|
// use-case passthrough returns (the conflict is passed through unwrapped, the
|
|
// property both write stacks now share), errors.As classifies each through the
|
|
// public alias and reads its fields — no message parsing.
|
|
func TestReExportedDependencyConflictTypes(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
// Type conflict: a different-type edge already exists between the pair.
|
|
typeConflict := &domain.DependencyTypeConflictError{
|
|
IssueID: "a", DependsOnID: "b", ExistingType: "blocks", RequestedType: "related",
|
|
}
|
|
uc := domain.NewDependencyUseCase(insertErrDepRepo{insertErr: typeConflict})
|
|
err := uc.AddDependency(context.Background(),
|
|
&types.Dependency{IssueID: "a", DependsOnID: "b", Type: types.DepRelated}, "tester")
|
|
var gotType *beads.DependencyTypeConflictError
|
|
if !errors.As(err, &gotType) {
|
|
t.Fatalf("errors.As(real type-conflict err, *beads.DependencyTypeConflictError) = false; err = %v", err)
|
|
}
|
|
if gotType.IssueID != "a" || gotType.DependsOnID != "b" ||
|
|
gotType.ExistingType != "blocks" || gotType.RequestedType != "related" {
|
|
t.Errorf("extracted type-conflict fields = %+v, want {a b blocks related}", gotType)
|
|
}
|
|
|
|
// Hierarchy conflict: a blocking edge would gate an issue on its ancestor.
|
|
hierConflict := &domain.DependencyHierarchyConflictError{
|
|
IssueID: "child", BlockerID: "ancestor", BlockerIsAncestor: true,
|
|
}
|
|
uc = domain.NewDependencyUseCase(insertErrDepRepo{hierarchyErr: hierConflict})
|
|
err = uc.AddDependency(context.Background(),
|
|
&types.Dependency{IssueID: "child", DependsOnID: "ancestor", Type: types.DepBlocks}, "tester")
|
|
var gotHier *beads.DependencyHierarchyConflictError
|
|
if !errors.As(err, &gotHier) {
|
|
t.Fatalf("errors.As(real hierarchy-conflict err, *beads.DependencyHierarchyConflictError) = false; err = %v", err)
|
|
}
|
|
if gotHier.IssueID != "child" || gotHier.BlockerID != "ancestor" || !gotHier.BlockerIsAncestor {
|
|
t.Errorf("extracted hierarchy-conflict fields = %+v, want {child ancestor true}", gotHier)
|
|
}
|
|
}
|
|
|
|
// TestReExportFieldTooLong proves the public beads.ErrFieldTooLong alias is the
|
|
// same value as the internal types sentinel and composes through errors.Is when
|
|
// wrapped — the property length-validation callers rely on to detect an
|
|
// over-length assignee/owner/label without importing internal/types. It also
|
|
// checks the MaxFieldLen constant re-export tracks the source of truth.
|
|
func TestReExportFieldTooLong(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
if beads.ErrFieldTooLong != types.ErrFieldTooLong {
|
|
t.Error("beads.ErrFieldTooLong is not the internal sentinel value (identity broken)")
|
|
}
|
|
wrapped := fmt.Errorf("x: %w", beads.ErrFieldTooLong)
|
|
if !errors.Is(wrapped, beads.ErrFieldTooLong) {
|
|
t.Errorf("errors.Is(wrapped, beads.ErrFieldTooLong) = false; err = %v", wrapped)
|
|
}
|
|
if beads.MaxFieldLen != types.MaxFieldLen {
|
|
t.Errorf("beads.MaxFieldLen = %d, want types.MaxFieldLen = %d", beads.MaxFieldLen, types.MaxFieldLen)
|
|
}
|
|
}
|