* feat(storage): engine reads — EventsSince, GetDependentRecords, EventClaimed
`bd activity`/`bd show` render event history, and the library's own callers
need a durable, resumable feed of what changed — but the storage surface had
only the time-granular GetAllEventsSince, no keyset cursor, and no raw
target-keyed dependents read. Add both as additive extension interfaces plus
backend methods; no wire, schema, CLI, or existing-signature changes. Each new
read delegates its SQL to the shared issueops helpers the backends already use.
- Extract the raw "claimed" event literal into a typed EventClaimed constant
(types) and use it at the single write site (issueops/claim.go). The on-disk
value is byte-identical.
- EventsSince(cursor{created_at,id}, limit) — a durable-only keyset read over
the events table, for a change feed that pages forward without dropping or
duplicating same-second ties. New EventQueryStore extension interface +
EventCursor, composed into DoltStorage and implemented on the Dolt backends.
- GetDependentRecords(targetID, depType, limit, afterID) on
DependencyQueryStore — a raw target-keyed dependents read (the inbound edges)
that returns edges from dangling/cross-project/wisp sources rather than
dropping them, so `bd dep list`-style dependents views see the whole set.
Real-Dolt tests cover direction correctness, type filter, keyset paging,
same-second id tie-break, cursor exclusivity, durable-only scope, and the
claimed-constant write path.
(cherry picked from commit 35ae4d186047d99bef6d492132f5767ef2db5d7d)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(storage): make EventsSince sargable + add a per-bead scope
The EventsSince cursor predicate `(created_at > ?) OR (created_at = ? AND id > ?)`
full-scans on Dolt (EXPLAIN: Filter over a bare Table + TopN). Rewrite it to the
logically-equivalent, SARGABLE form
created_at >= ? AND ((created_at > ?) OR (id > ?))
The redundant `created_at >= ?` lower bound flips the plan to
IndexedTableAccess(events) on [events.created_at] (verified by a new
EXPLAIN FORMAT=TREE regression test). The composite (created_at, id) row-value
form is deliberately NOT used: the events table has only single-column
idx_events_created_at (no composite index) on every backend, so the >= lower
bound is the seeking form; the shared issueops query serves each backend.
Also give EventsSince an optional issueID filter ("" = all) implemented off the
same keyset with `issue_id = ?`, so `bd show`'s per-bead event history is one
scoped read of the same primitive rather than a second one. The signature is
changed while unmerged across the interface + dolt/embeddeddolt backends.
Coverage/docs: dolt suite gains issue-filter, limit-clamp (default 100 / cap
500), and the EXPLAIN sargability guard; embeddeddolt gains a mirrored feed
test; the interface doc names idx_events_created_at and states the
commit-visibility-lag caveat (a resuming consumer overlaps a ~45s slack window
and de-duplicates by id).
(cherry picked from commit 3b7903290fad76e15ece171dcf6bdfd5f0f584b8)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* test(storage): single-source the EventsSince sargability guard from production SQL
The EXPLAIN sargability guard asserted a hand-copied literal of the EventsSince
query, so it could pass while the production predicate silently drifted.
Single-source it: export issueops.EventsSinceQuery(issueID, limit) — the exact
SQL EventsSinceInTx runs — and have the durable-events plan guard EXPLAIN that
string (placeholders literalized) instead of a copy. A change to the SARGABLE
predicate now breaks the guard.
Adds a literalizeParams test helper that binds ? placeholders to literals in
order and panics on arity drift, so a drifted placeholder count fails loudly
rather than EXPLAINing malformed SQL.
(cherry picked from commit dda19e737ac17ae4387c6abc4a1acca287b85494)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(storage): dependents reads — total id cursor, sargable target, + CountDependentRecords
Three coupled fixes to the target-keyed dependents read behind `bd dep list`'s
dependents views and the library's own callers:
TOTAL KEYSET. The old cursor paged on source issue_id, which is not a total key
for a fixed target: a source can appear across the durable and wisp dependency
tables, so paging on it could drop or duplicate rows (the Type tie-break was
dead code and the "issue_id is unique" comment was false). Cursor instead on the
dependency row's own primary id (depid.New(issue_id, target), a UUIDv5 that is
stable and globally unique across both tables): ORDER BY id ASC, afterID = last
row's id. types.Dependency gains an additive ID field, scanned by a dedicated
scanDependentRow (the shared scanDependencyRow is left untouched so no
source-keyed read has to select id). The two per-table pages merge by id and
truncate — total, no drop, no dup, proven by a page-size-1 walk across a
boundary that spans both tables (durable + wisp sources).
SARGABLE TARGET. Replace COALESCE(target...)=? (an expression no index can
match) with an explicit per-column OR, depTargetEqualsOr. On an index-merging
planner it plans as a BitmapOr index-merge over the three idx_dep_*_target
indexes where COALESCE was a full scan; on Dolt it is at worst no worse than
COALESCE, and the type-filtered path seeks the (type, target) composite on both.
CountDependentRecords(ctx, targetID, depType): the same sargable predicate,
COUNT only, summed across both tables — callers need a true total membership
count without paging to exhaustion. Implemented once in issueops and wired onto
the DependencyQueryStore interface + the dolt/embeddeddolt backends.
Coverage: dolt + embeddeddolt tests for both reads (two-table span, type filter,
keyset boundary, limit clamp default 100). Method docs name the cursor key and
the two-table raw-read / policy-at-hydration contract.
(cherry picked from commit 16db364d94f8525b9800483dc5ddcdccf94593f8)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(storage): de-dup cross-table depid collisions in dependents reads
depid.New keys a dependency row's id on (issue_id, target) and omits the table,
so the SAME edge present in BOTH dependencies and wisp_dependencies — a wisp
promoted to durable, or two Dolt clones merged — carries one id in both tables.
GetDependentRecordsInTx appended both per-table pages and sorted by id, so a
colliding edge produced a duplicate id in a merged page (and, at a page
boundary, a dropped row on the next `id > afterID`). CountDependentRecordsInTx
summed two raw COUNT(*)s, over-counting the collision beyond the distinct keyset
row count.
De-dup the paged read by id, iterating durable first and keeping the durable
(authoritative, non-ephemeral) row. Make the count agree with that de-dup:
durable rows plus wisp rows whose depid is not already a durable row for the same
target/type (an uncorrelated, bounded NOT IN over the sargable per-column OR
target predicate), so the total is distinct-by-id.
Adds a dolt regression test that seeds the same edge in both tables (FK checks
relaxed to reproduce the post-merge state) and asserts one row per id in pages,
Count == distinct total (3, not the sum 4), and stable keyset paging across the
collision. Fails before this change (id appears twice), passes after.
(cherry picked from commit c6825f8513cd38967fb73856253bd99a5eb65fc2)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(storage): batched target-keyed dependents read (GetDependentRecordsForIssues)
Adds GetDependentRecordsForIssues(ctx, targetIDs) → map[targetID][]*Dependency:
for a SET of target ids in ONE batched read, each id's INCOMING dependency rows
(its dependents), spanning BOTH the durable and wisp dependency tables, ALL dep
types (the caller filters), de-duped by row id. It is the target-keyed mirror of
the source-keyed GetDependencyRecordsForIssues — the whole-page read that lets
`bd dep list`-style dependents views and the library's own callers render every
id's inbound blocking edges without a per-id fan-out, and unlike
GetBlockingInfoForIssues's blocksMap it keeps the full type set (waits-for /
conditional-blocks are not dropped) and each row's real dep_type.
Cross-table de-dup matches GetDependentRecordsInTx: a wisp promoted to durable
carries one depid in both tables, so the durable table is scanned first and a
repeat id is skipped. The target is matched by the coalesced target expression
(depTargetIn), the same predicate the batched blocks/counts reads use.
Wired through issueops + the DependencyQueryStore interface + the dolt /
embeddeddolt backends. (The public-root re-export via beads.DependentQuerier
lands with the narrow public query-interface work.)
Tests: dolt + embeddeddolt batched-read regressions (multi-target keying, both
tables, full type set incl conditional-blocks/waits-for, decoy exclusion, absent
leaf, empty input).
(cherry picked from commit 1f69cedf282471d474ac5b1be633c7a9b18990c8)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(storage): batch transitive is_blocked read on DependencyQueryStore
`bd`'s discovery/ready-list views and the library's own callers need the
denormalized transitive is_blocked value for a PAGE of up to ~200 issues; the
surface only had the single IsBlocked(ctx, id), so a page cost N per-row calls.
Add IsBlockedBatch(ctx, ids) (map[string]bool) to the DependencyQueryStore
interface and implement it once in issueops.IsBlockedBatchInTx: a batched
SELECT id, is_blocked FROM {issues,wisps} WHERE id IN (...) at queryBatchSize=200
— the same denormalized column IsBlocked reads, NOT a recompute — so it returns
the identical transitive value per id, reflecting inherited/ancestor blockedness
(a child of a blocked parent is blocked with no direct blocking edge). ids
present in neither table are absent from the map; cross-table dups prefer the
wisps row, matching loadStatusByIDInTx and the search wisp-merge.
Wired onto the dolt and embeddeddolt backends via the same pattern as
CountDependentRecords (each delegates through its read tx).
Test: a dolt parity suite seeding a direct blocker, an inherited parent-child
block (transitive is_blocked with an EMPTY direct-blocker set), and an unblocked
control, asserting IsBlockedBatch agrees with per-row IsBlocked for every id and
that a missing id is absent from the map.
(cherry picked from commit 1cd441231e2c5a2b45064db01a03bb06de9009b9)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(issueops): IsBlockedBatch issues-wins on cross-table id collision, matching IsBlocked
IsBlockedInTx (per-row) scans issues→wisps and breaks on the first table that
has the id, so ISSUES wins the shared denormalized is_blocked field on a
cross-table (issues vs wisps) id collision. IsBlockedBatchInTx preferred the
wisps row, so the two reads disagreed on the same stored flag for an id present
in BOTH tables.
Make the batch keep the first-seen (issues) value and skip any later (wisps)
duplicate, mirroring the single read's precedence exactly. Both the dolt and
embeddeddolt backends delegate to this shared function, so they stay consistent.
Add a dolt regression seeding the same id in issues (is_blocked=1) and wisps
(is_blocked=0) and asserting IsBlocked(id) == IsBlockedBatch([id])[id] == the
issues value. Verified it fails before the fix (true vs false).
(cherry picked from commit 7dbd4f849d589acb15f8168532fcf8874aa87c99)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* test(embeddeddolt): IsBlockedBatch parity regression on the embedded backend
Mirror the dolt IsBlockedBatch coverage on the embedded Dolt backend: assert the
batched transitive is_blocked read agrees with per-row IsBlocked for every id and
reflects an inherited parent-child block (is_blocked true with an empty
direct-blocker set). Complements the already-present embedded keyset regression.
(cherry picked from commit 414e7eaf8de43eb1786088c2851c18763f6724ba)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(beads): re-export claim surface, error taxonomy, and query interfaces on public root
Public root-package surface for the claim/error/query reads consumers reach by
type-assertion. Pure re-export + a string-coupled conflict shim; no engine
behavior changes.
- IssueClaimer interface (ClaimIssue/ClaimReadyIssue, which live on the
storage.BulkIssueStore extension, not the base Storage) + AsIssueClaimer
type-assertion helper. Callers assert once at startup and fail loud, per the
decorator note.
- Re-export ErrCircuitOpen (storage/dolt) as an aliased root sentinel so
errors.Is works across the boundary (the claim sentinels ErrAlreadyClaimed /
ErrNotClaimable are already re-exported with the other sentinels); a
wrap-preservation test pins this against errors wrapped the way the engine
wraps them.
- Typed conflict detail: the conditional-UPDATE claim path returns no typed
result on conflict — the current assignee/status remains embedded in the
error string. Rather than change that internal signature, expose
ClaimConflict + ParseClaimConflict (with its own test) to recover it.
- Re-export DependencyQueryStore, EventQueryStore, EventCursor aliases and the
EventClaimed constant so consumers reach the new reads by type-assertion.
(cherry picked from commit 70f443ad941117a74f3143f8570f91a0f721ece4)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(beads): derive claim-conflict markers from a storage source of truth
ParseClaimConflict hardcoded the message literals "issue already claimed by "
and "issue not claimable: status ", coupling the root parser to the engine's
fmt.Errorf format three layers away with nothing to catch drift.
- Export the two format fragments next to the sentinels: storage.ClaimedByFragment
(" by ") and storage.NotClaimableStatusFragment (": status "). issueops/claim.go
now wraps with "%w%s%s" using them (on-disk/message bytes unchanged), and
ParseClaimConflict reconstructs its markers as ErrAlreadyClaimed.Error()+fragment
rather than hardcoding — producer and parser can no longer drift independently.
- Harden tailAfter: recover the assignee/status only as the trailing run; if the
tail still contains a known marker (an appended wrap corrupted it) return "".
Documents the repo convention that claim-error wraps PREPEND context.
- Producer-tied tripwires: a dolt-suite round-trip (real ClaimIssue → both
conflict branches, recovered via the storage fragments) and a root external
round-trip (real Dolt store via beads.Open → AsIssueClaimer → ParseClaimConflict
recovers assignee/status). The latter also exercises AsIssueClaimer against a
live Storage.
(cherry picked from commit aced93f3d93c3fb779702df0549fab58369af997)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(beads): bound the claim-conflict token so an appended wrap can't leak garbage
tailAfter took the entire trailing run after the fragment, guarding only against
a further embedded full marker. A plain appended wrap — fmt.Errorf("%w (ctx)",
claimErr) — sailed past that guard and returned "alice (ctx)" as the assignee.
Bound the token to a single whitespace-free run: a status never contains
whitespace and an assignee is a whitespace-free actor id by convention, so if the
tail carries trailing content (whitespace or an appended "(...)" wrap) we return
"" — the documented best-effort empty-field outcome, with ParseClaimConflict
still reporting ok=true on the errors.Is match. A prepended wrap (the repo
convention) and a clean conflict are unaffected.
Tests: a direct tailAfter table (clean, prepended, appended-paren, appended-space,
absent, empty) and a ParseClaimConflict appended-wrap case asserting empty field
with ok=true.
(cherry picked from commit 181f47c7b7b4bb397c5f16992d1e33b75982eb04)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor(beads): narrow public query interfaces + claim-surface drift guards
Public-surface hardening for the library's consumers, done while unmerged
(cheap now, expensive later).
Stop aliasing whole internal engine interfaces on the root. Replace the
`DependencyQueryStore = storage.DependencyQueryStore` / `EventQueryStore =
storage.EventQueryStore` aliases with NARROW, hand-declared root interfaces that
expose exactly what consumers use:
- EventQuerier { EventsSince(...) }
- DependentQuerier { GetDependentRecords(...); CountDependentRecords(...) }
plus AsEventQuerier / AsDependentQuerier helpers mirroring AsIssueClaimer. Every
As* helper now first tries the direct assertion, then storage.UnwrapStore, so a
HookFiringStore-decorated store keeps its capability (AsIssueClaimer gains the
same unwrap; previously it would return false for a decorated store).
Drift guards: compile-time assertions tie each narrow interface to the full
engine interface storage.DoltStorage (in beads.go) AND to both concrete stores —
*dolt.DoltStore and *embeddeddolt.EmbeddedDoltStore (in tests) — so a signature
change to the claim/event/dependents surface breaks the build instead of
silently making As* return false. A live-Dolt test exercises AsEventQuerier /
AsDependentQuerier and their methods end to end.
(cherry picked from commit ddf7b2ab8a2fa41e36f13ccf701983d0bcd01faa)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor(beads): drop the dead UnwrapStore fallback from the As* accessors
The storage.UnwrapStore fallback in AsIssueClaimer/AsEventQuerier/
AsDependentQuerier was provably unreachable. ClaimIssue/ClaimReadyIssue,
EventsSince, and the dependents reads all live on the engine interface
storage.DoltStorage (via BulkIssueStore / EventQueryStore /
DependencyQueryStore), and the compile-time drift guards prove
storage.DoltStorage satisfies each narrow surface. So whenever the fallback's
`s.(storage.DoltStorage)` succeeds, `s` already satisfies the narrow surface and
the leading direct assertion has already returned — branch 2 can only run when
branch 1 failed, and branch 1 failing implies s is not a DoltStorage, so branch 2
fails too. The only decorator, HookFiringStore, embeds storage.DoltStorage and
overrides none of these methods, so it forwards them by promotion and resolves on
the direct assertion.
Reduce the three accessors to a single direct type-assertion and document the
decorator contract (a decorator MUST embed storage.DoltStorage — unlike the
cmd/bd optional interfaces such as StoreLocator/BackupStore, which are not part
of DoltStorage and so genuinely need UnwrapStore, which is unchanged and still
used there). Adds a test that a HookFiringStore-decorated live store resolves
through all three accessors — the guard that would catch a future decorator that
stops forwarding.
(cherry picked from commit 0d9d0500edd3c165f101bbb590dcea7147f3530b)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(beads): re-export the batch transitive-blocked surface on the public root
Add BlockedQuerier (IsBlocked + IsBlockedBatch) and AsBlockedQuerier to the public
beads package, following the established narrow-interface + As* accessor style
(EventQuerier/DependentQuerier): a hand-declared root interface exposing only the
transitive-blocked reads consumers use, reachable via a single direct type
assertion, with a compile-time drift guard (var _ BlockedQuerier =
(storage.DoltStorage)(nil)) so a signature change on the engine breaks the build
here instead of silently making the accessor return false.
The (created_at, id) keyset needs no new re-export: it is additive fields on the
already-re-exported beads.IssueFilter, honored by the already-exported
Storage.SearchIssues / SearchIssuesWithCounts.
query_interfaces tests gain the concrete-store conformance assertions (server +
embedded Dolt), a live-Dolt exercise of AsBlockedQuerier proving IsBlockedBatch
agrees with per-row IsBlocked through the public surface, and the decorator-
contract check that AsBlockedQuerier resolves through a HookFiringStore.
(cherry picked from commit e8b87b6acf601bc2b323d92fbe863c4be7a99386)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(beads): re-export GetDependentRecordsForIssues on the public DependentQuerier
Surface the batched target-keyed dependents read (GetDependentRecordsForIssues,
landed at the storage layer earlier in the dependents-reads work) on the public
root DependentQuerier interface, so a consumer reaching the dependents surface
via AsDependentQuerier can fetch a whole page of inbound edges for a SET of
target ids in one call — the batched mirror of GetDependencyRecordsForIssues —
without a per-id fan-out. A live-Dolt query_interfaces assertion exercises it
through the public surface.
(cherry picked from commit 1f69cedf282471d474ac5b1be633c7a9b18990c8)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(storage): transactional snapshot reads on storage.Transaction
Composite views (bd show-style assemblies of counts, relations, comments, and
history) previously issued each read as its own store call with no shared
snapshot, so related numbers could disagree. Widen storage.Transaction with
the read subset those views need — CountIssuesByGroup, GetIssueCommentsPage,
GetDependentRecords/GetDependentRecordsForIssues/CountDependentRecords,
IsBlocked/IsBlockedBatch, EventsSince — so a caller can assemble the whole
view inside one transaction. Pure surface addition: every method delegates to
the existing InTx implementation; no new SQL, no semantics changes.
On the server backend the transaction spans two sessions (durable + clone-
local). Single-tier reads route by wispness and see this transaction's own
uncommitted writes on both tiers (comments page, blocked checks — including
mixed batches via tier partitioning). Reads that union both tables in one
query (dependents family, grouped counts) run on the durable session and see
uncommitted durable writes plus committed clone-local state; that limitation
is documented per method on the interface and asserted per backend in the
tests. The embedded backend is single-handle and fully read-your-writes.
Conformance adds a snapshot test that mutates inside the transaction and
asserts exact deltas across all the new reads (a non-transactional delegation
fails it), a read-your-writes test covering every method, and wisp-bearing
fixtures; the server backend adds a clone-local-tier read-your-writes test
pinning both the routed reads and the documented spanning-read behavior.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(issueops): drop depTargetEqualsOr's dead alias parameter
Every caller on this branch passes "" — the aliased form's only consumer
lived in a backend package that does not exist here — so golangci-lint's
unparam check rejects the parameter. Inline the bare-column form.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(storage): wrap ErrAlreadyClaimed for open foreign-assignee; split tx conformance tests
Maintainer review fixes for PR #4926 (iteration 1).
Contract (major): issueops.ClaimIssueInTx's open-but-assigned refusal branch
returned a plain error, so the public IssueClaimer contract (wrapped conflict
sentinels, classified by errors.Is / ParseClaimConflict) was false for the
common "open issue pre-assigned to another actor" case. Wrap
storage.ErrAlreadyClaimed while preserving the holder-focused wording, matching
the already-correct domain-stack twin. Adds a conformance test
(ClaimOpenForeignAssignee) and a ParseClaimConflict subtest for the wrapped
open-assigned form.
Complexity (major): split testTransactionSnapshotReads and
testTransactionReadYourWrites into named read + assertion helpers
(readSnapView/assertSnapBaseline/assertSnapDelta and
seedReadYourWritesGraph/assertInTxDependentReads/assertInTxCountsAndEvents) with
equivalent coverage, dropping the worst changed function out of the major
cyclomatic/cognitive band (39/73 -> 11/17 and 23/38 -> 4/5).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(issueops): extract per-table read to cut IsBlockedBatchInTx complexity
Review fix for #4926. IsBlockedBatchInTx inlined the whole two-table batched
scan (gocognit 29, gocyclo 12), which the quality scorecard flagged as a major
readability finding. Extract the per-table batched read into
readIsBlockedIntoFromTable, mirroring the sibling
GetDependentRecordsForIssuesInTx / getDependentRecordsIntoFromTable split, so the
outer function only dispatches the issues+wisps read and nesting resets at the
function boundary.
Behavior-preserving: the issues-win cross-table de-dup and the optional-wisps
table-not-exist skip are unchanged -- same helper-wraps / outer-classifies idiom
as the sibling, and isTableNotExistError unwraps the %w wrap. The embedded
TestIsBlockedBatchEmbedded parity test still passes against a real Dolt backend.
gocognit 29 -> helper 15; gocyclo 12 -> 6.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: CI Bot <ci@beads.test>
394 lines
18 KiB
Go
394 lines
18 KiB
Go
// Package beads provides a minimal public API for extending bd with custom orchestration.
|
|
//
|
|
// Most extensions should use direct SQL queries against bd's database.
|
|
// This package exports only the essential types and functions needed for
|
|
// Go-based extensions that want to use bd's storage layer programmatically.
|
|
//
|
|
// For a working extension example, see examples/bd-example-extension-go.
|
|
package beads
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/dolt"
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// Storage is the interface for beads storage operations
|
|
type Storage = beads.Storage
|
|
|
|
func configuredBackendUnavailable(backend string) error {
|
|
switch backend {
|
|
case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite:
|
|
return configfile.RemovedBackendError(backend)
|
|
default:
|
|
return configfile.UnknownBackendError(backend)
|
|
}
|
|
}
|
|
|
|
// Transaction provides atomic multi-operation support within a database transaction.
|
|
// Use Storage.RunInTransaction() to obtain a Transaction instance.
|
|
type Transaction = beads.Transaction
|
|
|
|
// DependencyAddOptions controls transaction-scoped dependency insertion for
|
|
// Transaction.AddDependencyWithOptions. Exported so embedders' bulk graph
|
|
// writers can set SkipCycleCheck per edge and run one whole-graph
|
|
// Transaction.CycleThroughEdges pass before commit (bd-6dnrw.8) instead of
|
|
// paying the recursive per-edge cycle query — which cannot finish inside a
|
|
// per-command budget on molecule-sized graphs (observed: a 67-node/100-edge
|
|
// batch blowing a 120s deadline mid-transaction, gascity 2026-07-17).
|
|
//
|
|
// Callers that set SkipCycleCheck MUST run Transaction.CycleThroughEdges before
|
|
// commit and fail on new blocks/conditional-blocks/parent-child cycles
|
|
// (waits-for is excluded); skipping the per-edge check trades per-edge cost for
|
|
// one whole-graph check, never graph integrity.
|
|
type DependencyAddOptions = storage.DependencyAddOptions
|
|
|
|
// DependencyRemoveOptions controls transaction-scoped dependency removal for
|
|
// Transaction.RemoveDependencyWithOptions. Exported so embedders can request the
|
|
// dependency_removed history event on an explicit edge removal; the plain
|
|
// RemoveDependency default stays silent for structural edge teardown, mirroring
|
|
// the DependencyAddOptions/AddDependencyWithOptions split.
|
|
type DependencyRemoveOptions = storage.DependencyRemoveOptions
|
|
|
|
// CloseIssueOptions carries the optional inputs to Storage.CloseIssueChecked —
|
|
// an atomic, guarded close that refuses a still-blocked issue with
|
|
// ErrCloseBlocked unless Force is set. Exported so consumers can name it without
|
|
// importing internal/storage.
|
|
type CloseIssueOptions = storage.CloseIssueOptions
|
|
|
|
// CloseIssueResult reports the outcome of Storage.CloseIssueChecked. Unchanged
|
|
// is true when the issue was already closed (idempotent no-op).
|
|
type CloseIssueResult = storage.CloseIssueResult
|
|
|
|
// UpdateIssueOptions carries the optional inputs to Storage.UpdateIssueChecked —
|
|
// an update with an optional ExpectedVersion compare-and-swap that refuses a
|
|
// concurrently-modified issue with ErrVersionMismatch. Exported so consumers can
|
|
// name it without importing internal/storage.
|
|
type UpdateIssueOptions = storage.UpdateIssueOptions
|
|
|
|
// CommentPageCursor is the resume position for Storage.GetIssueCommentsPage — the
|
|
// (created_at, id) of the last comment already returned, with the zero value
|
|
// starting a walk from the beginning of the thread. Exported so consumers can
|
|
// name it without importing internal/storage.
|
|
type CommentPageCursor = storage.CommentPageCursor
|
|
|
|
// RemoteStore provides dolt remote management and replication operations.
|
|
// Use type assertion on a Storage value to access these methods:
|
|
//
|
|
// if rs, ok := store.(beads.RemoteStore); ok {
|
|
// rs.Push(ctx)
|
|
// }
|
|
type RemoteStore = storage.RemoteStore
|
|
|
|
// SyncStore provides high-level sync operations with peers.
|
|
type SyncStore = storage.SyncStore
|
|
|
|
// EventCursor is a keyset position in the durable events stream, ordered by
|
|
// (created_at, id). The zero value means "from the beginning".
|
|
type EventCursor = storage.EventCursor
|
|
|
|
// EventQuerier is the durable-event-feed surface of a Storage: keyset paging
|
|
// over the durable event log, beyond the base Storage's time-only
|
|
// GetAllEventsSince. It is a NARROW, hand-declared root interface exposing
|
|
// exactly what consumers need — not an alias of the internal EventQueryStore —
|
|
// so the published surface stays small and independent of the engine interface.
|
|
// Reach it via AsEventQuerier.
|
|
type EventQuerier interface {
|
|
// EventsSince returns durable events strictly after cursor, ordered by
|
|
// (created_at ASC, id ASC), bounded by limit (0 = a store default, capped).
|
|
// issueID scopes the feed to one bead's history ("" = all).
|
|
EventsSince(ctx context.Context, cursor EventCursor, issueID string, limit int) ([]*Event, error)
|
|
}
|
|
|
|
// DependentQuerier is the target-keyed dependents surface of a Storage: the raw
|
|
// inbound-edge reads that back group-membership. Like EventQuerier it is a
|
|
// NARROW hand-declared root interface (not an alias of DependencyQueryStore),
|
|
// exposing only the calls consumers use. Reach it via AsDependentQuerier.
|
|
type DependentQuerier interface {
|
|
// GetDependentRecords returns raw dependency rows whose target is targetID,
|
|
// paged by the dependency row id (afterID, "" = start). See the engine doc
|
|
// for the two-table span and raw-read/policy-at-hydration contract.
|
|
GetDependentRecords(ctx context.Context, targetID string, depType string, limit int, afterID string) ([]*Dependency, error)
|
|
// GetDependentRecordsForIssues returns raw dependency rows keyed by TARGET id
|
|
// — for a SET of target ids in one batched read, each id's inbound edges (its
|
|
// dependents), across both dependency tables, ALL dep types, de-duped by row
|
|
// id. The batched, target-keyed mirror of GetDependencyRecordsForIssues; same
|
|
// two-table span and raw-read/policy-at-hydration contract as
|
|
// GetDependentRecords, without paging.
|
|
GetDependentRecordsForIssues(ctx context.Context, targetIDs []string) (map[string][]*Dependency, error)
|
|
// CountDependentRecords returns the true total inbound-edge count of targetID
|
|
// (depType "" = all) without paging.
|
|
CountDependentRecords(ctx context.Context, targetID string, depType string) (int, error)
|
|
}
|
|
|
|
// BlockedQuerier is the transitive-blocked surface of a Storage: the
|
|
// denormalized is_blocked flag, single or batched. Like EventQuerier it is a
|
|
// NARROW hand-declared root interface (not an alias of DependencyQueryStore),
|
|
// exposing only the reads consumers use. IsBlockedBatch returns the is_blocked
|
|
// column for a whole page in one round-trip — the same transitive value
|
|
// IsBlocked returns per id, with no N-call fan-out. Reach it via AsBlockedQuerier.
|
|
type BlockedQuerier interface {
|
|
// IsBlocked reports whether issueID is blocked (its denormalized transitive
|
|
// is_blocked flag) and the open direct blockers for display.
|
|
IsBlocked(ctx context.Context, issueID string) (bool, []string, error)
|
|
// IsBlockedBatch returns the denormalized transitive is_blocked flag for each
|
|
// of ids in one batched read. ids present in neither the issues nor wisps
|
|
// table are absent from the map; callers treat absent as not-blocked.
|
|
IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error)
|
|
}
|
|
|
|
// AsEventQuerier returns the EventQuerier view of s, or (nil, false) when the
|
|
// backing store does not expose the durable-event feed. Assert once and fail
|
|
// loud. A single direct assertion is sufficient — see the decorator contract on
|
|
// AsIssueClaimer.
|
|
func AsEventQuerier(s Storage) (EventQuerier, bool) {
|
|
q, ok := s.(EventQuerier)
|
|
return q, ok
|
|
}
|
|
|
|
// AsBlockedQuerier returns the BlockedQuerier view of s, or (nil, false) when the
|
|
// backing store does not expose the transitive-blocked reads. Assert once and
|
|
// fail loud. A single direct assertion is sufficient — see the decorator
|
|
// contract on AsIssueClaimer.
|
|
func AsBlockedQuerier(s Storage) (BlockedQuerier, bool) {
|
|
q, ok := s.(BlockedQuerier)
|
|
return q, ok
|
|
}
|
|
|
|
// AsDependentQuerier returns the DependentQuerier view of s, or (nil, false) when
|
|
// the backing store does not expose the target-keyed dependents reads. Assert
|
|
// once and fail loud. A single direct assertion is sufficient — see the
|
|
// decorator contract on AsIssueClaimer.
|
|
func AsDependentQuerier(s Storage) (DependentQuerier, bool) {
|
|
q, ok := s.(DependentQuerier)
|
|
return q, ok
|
|
}
|
|
|
|
// ErrCircuitOpen is re-exported (aliased, so errors.Is works across the package
|
|
// boundary) from the Dolt storage layer: a read or write rejected because the
|
|
// Dolt circuit breaker is open wraps it. The claim sentinels ErrAlreadyClaimed
|
|
// and ErrNotClaimable — the ones ParseClaimConflict recovers assignee/status
|
|
// detail from — are re-exported with the other error sentinels below.
|
|
var (
|
|
ErrCircuitOpen = dolt.ErrCircuitOpen
|
|
)
|
|
|
|
// IssueClaimer is the atomic-claim surface of a Storage. ClaimIssue and
|
|
// ClaimReadyIssue live on the storage.BulkIssueStore extension rather than the
|
|
// base Storage interface, so callers reach them by type-assertion via
|
|
// AsIssueClaimer rather than off the Storage value directly.
|
|
type IssueClaimer interface {
|
|
// ClaimIssue atomically claims id for actor using compare-and-swap
|
|
// semantics (open ∧ unassigned-or-same-actor). Returns a wrapped
|
|
// ErrAlreadyClaimed or ErrNotClaimable on conflict.
|
|
ClaimIssue(ctx context.Context, id string, actor string) error
|
|
// ClaimReadyIssue atomically claims the first ready issue matching filter,
|
|
// or returns (nil, nil) when none is claimable.
|
|
ClaimReadyIssue(ctx context.Context, filter WorkFilter, actor string) (*Issue, error)
|
|
}
|
|
|
|
// AsIssueClaimer returns the IssueClaimer view of s when the backing store
|
|
// supports atomic claim (Dolt-backed stores do), and (nil, false) otherwise.
|
|
// Assert once at startup and fail loud.
|
|
//
|
|
// DECORATOR CONTRACT: a single direct type-assertion is sufficient — no unwrap.
|
|
// ClaimIssue/ClaimReadyIssue (like EventsSince and the dependents reads) live on
|
|
// the engine interface storage.DoltStorage, and the compile-time drift guards
|
|
// below prove storage.DoltStorage satisfies each narrow surface. A store
|
|
// decorator therefore MUST embed storage.DoltStorage — as HookFiringStore does —
|
|
// which promotes these methods so the assertion reaches them THROUGH the
|
|
// decorator. (This is unlike the cmd/bd optional interfaces — StoreLocator,
|
|
// BackupStore, Flattener, … — which are NOT part of DoltStorage, do not promote,
|
|
// and so genuinely need storage.UnwrapStore.) A former storage.UnwrapStore
|
|
// fallback here was provably dead: whenever s satisfies storage.DoltStorage it
|
|
// already satisfies the narrow surface (drift guard), so the direct assertion
|
|
// always wins; and the only decorator, HookFiringStore, forwards by promotion.
|
|
func AsIssueClaimer(s Storage) (IssueClaimer, bool) {
|
|
c, ok := s.(IssueClaimer)
|
|
return c, ok
|
|
}
|
|
|
|
// Compile-time drift guards: the full engine interface storage.DoltStorage must
|
|
// satisfy each narrow public surface, so a signature change to the claim / event
|
|
// / dependents methods on the engine breaks the build here instead of silently
|
|
// making As* return false at runtime. Concrete-store conformance is asserted in
|
|
// the tests (both Dolt stores).
|
|
var (
|
|
_ IssueClaimer = (storage.DoltStorage)(nil)
|
|
_ EventQuerier = (storage.DoltStorage)(nil)
|
|
_ DependentQuerier = (storage.DoltStorage)(nil)
|
|
_ BlockedQuerier = (storage.DoltStorage)(nil)
|
|
)
|
|
|
|
// VersionControlReader provides read-only version control operations.
|
|
// Write operations (Branch, Checkout, Merge, DeleteBranch) are not yet
|
|
// part of the public API. If you need them, please open an issue.
|
|
type VersionControlReader interface {
|
|
CurrentBranch(ctx context.Context) (string, error)
|
|
ListBranches(ctx context.Context) ([]string, error)
|
|
CommitExists(ctx context.Context, commitHash string) (bool, error)
|
|
GetCurrentCommit(ctx context.Context) (string, error)
|
|
Status(ctx context.Context) (*VCStatus, error)
|
|
Log(ctx context.Context, limit int) ([]CommitInfo, error)
|
|
}
|
|
|
|
// Replication and version control types from internal/storage
|
|
type (
|
|
RemoteInfo = storage.RemoteInfo
|
|
SyncResult = storage.SyncResult
|
|
SyncStatus = storage.SyncStatus
|
|
Conflict = storage.Conflict
|
|
CommitInfo = storage.CommitInfo
|
|
VCStatus = storage.Status
|
|
StatusEntry = storage.StatusEntry
|
|
)
|
|
|
|
// Open opens a Dolt-backed beads database at the given path.
|
|
// This always opens in embedded mode. Use OpenFromConfig to respect
|
|
// server mode settings from metadata.json.
|
|
func Open(ctx context.Context, dbPath string) (Storage, error) {
|
|
return dolt.New(ctx, &dolt.Config{Path: dbPath, CreateIfMissing: true})
|
|
}
|
|
|
|
// OpenFromConfig opens the Dolt implementation using configuration from
|
|
// metadata.json. Unlike Open, this respects Dolt server mode settings and database
|
|
// name configuration.
|
|
// beadsDir is the path to the .beads directory.
|
|
func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) {
|
|
return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true})
|
|
}
|
|
|
|
// FindDatabasePath finds the beads database in the current directory tree
|
|
func FindDatabasePath() string {
|
|
return beads.FindDatabasePath()
|
|
}
|
|
|
|
// FindBeadsDir finds the .beads/ directory in the current directory tree.
|
|
// Returns empty string if not found.
|
|
func FindBeadsDir() string {
|
|
return beads.FindBeadsDir()
|
|
}
|
|
|
|
// DatabaseInfo contains information about a beads database
|
|
type DatabaseInfo = beads.DatabaseInfo
|
|
|
|
// FindAllDatabases finds all beads databases in the system
|
|
func FindAllDatabases() []DatabaseInfo {
|
|
return beads.FindAllDatabases()
|
|
}
|
|
|
|
// RedirectInfo contains information about a beads directory redirect
|
|
type RedirectInfo = beads.RedirectInfo
|
|
|
|
// GetRedirectInfo checks if the current beads directory is redirected.
|
|
// Returns RedirectInfo with IsRedirected=true if a redirect is active.
|
|
func GetRedirectInfo() RedirectInfo {
|
|
return beads.GetRedirectInfo()
|
|
}
|
|
|
|
// Core types from internal/types
|
|
type (
|
|
Issue = types.Issue
|
|
Status = types.Status
|
|
IssueType = types.IssueType
|
|
Dependency = types.Dependency
|
|
DependencyType = types.DependencyType
|
|
Label = types.Label
|
|
Comment = types.Comment
|
|
Event = types.Event
|
|
EventType = types.EventType
|
|
BlockedIssue = types.BlockedIssue
|
|
TreeNode = types.TreeNode
|
|
IssueFilter = types.IssueFilter
|
|
WorkFilter = types.WorkFilter
|
|
StaleFilter = types.StaleFilter
|
|
DependencyCounts = types.DependencyCounts
|
|
IssueWithCounts = types.IssueWithCounts
|
|
IssueWithDependencyMetadata = types.IssueWithDependencyMetadata
|
|
SortPolicy = types.SortPolicy
|
|
EpicStatus = types.EpicStatus
|
|
WispFilter = types.WispFilter
|
|
)
|
|
|
|
// Status constants
|
|
const (
|
|
StatusOpen = types.StatusOpen
|
|
StatusInProgress = types.StatusInProgress
|
|
StatusBlocked = types.StatusBlocked
|
|
StatusDeferred = types.StatusDeferred
|
|
StatusClosed = types.StatusClosed
|
|
)
|
|
|
|
// IssueType constants
|
|
const (
|
|
TypeBug = types.TypeBug
|
|
TypeFeature = types.TypeFeature
|
|
TypeTask = types.TypeTask
|
|
TypeEpic = types.TypeEpic
|
|
TypeChore = types.TypeChore
|
|
)
|
|
|
|
// DependencyType constants
|
|
const (
|
|
DepBlocks = types.DepBlocks
|
|
DepRelated = types.DepRelated
|
|
DepParentChild = types.DepParentChild
|
|
DepDiscoveredFrom = types.DepDiscoveredFrom
|
|
DepConditionalBlocks = types.DepConditionalBlocks // B runs only if A fails (bd-kzda)
|
|
)
|
|
|
|
// SortPolicy constants
|
|
const (
|
|
SortPolicyHybrid = types.SortPolicyHybrid
|
|
SortPolicyPriority = types.SortPolicyPriority
|
|
SortPolicyOldest = types.SortPolicyOldest
|
|
)
|
|
|
|
// EventType constants
|
|
const (
|
|
EventCreated = types.EventCreated
|
|
EventUpdated = types.EventUpdated
|
|
EventClaimed = types.EventClaimed
|
|
EventStatusChanged = types.EventStatusChanged
|
|
EventCommented = types.EventCommented
|
|
EventClosed = types.EventClosed
|
|
EventReopened = types.EventReopened
|
|
EventDependencyAdded = types.EventDependencyAdded
|
|
EventDependencyRemoved = types.EventDependencyRemoved
|
|
EventLabelAdded = types.EventLabelAdded
|
|
EventLabelRemoved = types.EventLabelRemoved
|
|
EventCompacted = types.EventCompacted
|
|
)
|
|
|
|
// MaxFieldLen re-exports the maximum length (in characters) of the assignee,
|
|
// owner, and label fields, paired with the ErrFieldTooLong sentinel below.
|
|
const MaxFieldLen = types.MaxFieldLen
|
|
|
|
// Re-exported error sentinels so consumers match on errors.Is rather than
|
|
// on message text. Each is an ALIAS of the internal sentinel, so the identity
|
|
// is preserved across the package boundary.
|
|
var (
|
|
ErrNotFound = storage.ErrNotFound
|
|
ErrAlreadyClaimed = storage.ErrAlreadyClaimed
|
|
ErrNotClaimable = storage.ErrNotClaimable
|
|
ErrCloseBlocked = storage.ErrCloseBlocked
|
|
ErrVersionMismatch = storage.ErrVersionMismatch
|
|
ErrSelfDependency = domain.ErrSelfDependency
|
|
ErrDependencyCycle = domain.ErrDependencyCycle
|
|
ErrFieldTooLong = types.ErrFieldTooLong
|
|
)
|
|
|
|
// DependencyTypeConflictError is returned by AddDependency when an edge of a
|
|
// different type already exists between the pair; callers errors.As it to read
|
|
// the existing/requested types instead of parsing the message.
|
|
type DependencyTypeConflictError = domain.DependencyTypeConflictError
|
|
|
|
// DependencyHierarchyConflictError is returned by AddDependency when a blocking
|
|
// edge would gate an issue on its own ancestor/descendant (a gate that can
|
|
// never clear).
|
|
type DependencyHierarchyConflictError = domain.DependencyHierarchyConflictError
|