feat(init): put bd init's identity seam behind Bootstrapper and InitVerifier (bd-zl3u8)

`bd init` had two implementations of what a workspace's identity IS. The direct
route read issue_prefix out of the config plane at init.go:1358 and _project_id
four hundred lines later, decided adopt-vs-write with two helper predicates, and
wrote both keys by name. The proxied route called domain.BootstrapUseCase, which
held its own list of which keys an identity is made of, wrote them
unconditionally, and folded the Dolt remote into the same call. The two agreed on
the key names and disagreed on the rule, and no test compared them.

ONLY THE IDENTITY SEAM IS A ROLE. Everything else init does — creating .beads/,
writing metadata.json and config.yaml, initializing git, installing hooks,
starting a Dolt server — CREATES the substrate or the workspace around it, and a
role is reached through an accessor ON a store, so it cannot be what makes the
store exist. init.go alone is 3,060 lines; this commit touches the part that
happens inside the database.

TWO ROLES, AGAINST THE VersionReconciler PRECEDENT. That one is a read and a
write on one role because they are two shapes of one question, and every word of
that is true here too. The test that separates them is different: can one caller
be entitled to the READ and not the WRITE? Here yes, and not hypothetically —
`bd init --team-server` adopts a bts-provisioned identity and is forbidden to
write one, and a gateway credential may be read-only. Those paths now hold an
InitVerifier and never obtain a Bootstrapper, which the type system checks;
with one role they would hold the writer and the suppression would stay where it
is today, in three should* predicates on the CLI.

Q8 ANSWERED IN THE ROLE. Bootstrap over an already-identified substrate is
ErrAlreadyIdentified, carried by an *AlreadyIdentifiedError naming what was
found, decided from the same read the write would have followed inside ONE
transaction. Either marker is enough: a substrate several rigs share carries a
prefix one of them chose, and overwriting it renames every id the others are
about to mint. The guard now sits below both front doors instead of in front of
one, so gateway and adopt paths inherit it, and re-identifying is something
somebody asks for rather than something init does twice.

THE ROLE OWNS THE IDENTITY AND NOTHING ELSE. BootstrapProject wrote six values;
BootstrapRequest carries two. The fingerprints, the synced-at marker and the
recorded binary version are refreshed on EVERY init, adopt or not — a fresh clone
of an already-identified database needs its own fingerprints precisely because it
bootstrapped nothing — so a refusable one-time write would mean either a refusal
that stops recording them or a write that is no longer one-time. bd_version has a
second reason: it is VersionReconciler's key. The Dolt remote left too; it is
where the database syncs to, not what it is, and putting them in one call is what
let a remote that could not be created fail a bootstrap that had already
succeeded. domain.BootstrapUseCase is DELETED and domain.ConfigUseCase gains
SetMetadata, the write half of the GetMetadata it already published, so the
unit-of-work body can read, refuse and write in one transaction.

THE DEFECT. Proxied `bd init` against a database another rig had already
identified rewrote both markers with its own derived values. It verifies and
adopts now, printing the direct route's existing line, with the role's refusal as
the backstop. The direct route's two identity reads also became one snapshot, so
the prefix it adopts and the project id it reconciles against can no longer come
from either side of a concurrent write; shouldConsultInitProjectID still gates
whether the id is USED, so which identities init adopts is unchanged.

CONFORMANCE. backend/conformance/bootstrapper_contract.go holds twelve cases —
both roles in one file, because every promise on either is a statement about the
other — run at all three implementations with ZERO PARKS and zero divergences.
They deliberately do not re-test the decision: the validator's and the refusal's
whole tables are pinned without a database in internal/workapi/bootstrap_test.go.
What only a real backend can show is asserted instead: that the identity is there
for the NEXT caller (a new transaction on the unit-of-work backend), that a
refusal and a validation failure leave the markers EXACTLY as they were, that the
verifier reports an unreadable identity as an error rather than as an empty one,
and that a bootstrap costs at most one version-control entry. Two independent
bodies plus an engine check, not three votes: dolt and embeddeddolt share
internal/storage/issueops.BootstrapInTx and VerifyIdentityInTx and differ only in
how they reach a transaction. The bodies live there rather than in an importable
store<role> package because the read and the write it qualifies must see one
snapshot, which storage.DoltStorage cannot express — so there is no constructor
for a depguard entry to deny.

NO HTTP OPERATION, and that is a decision. A server can only serve a database it
is already bound to, and binding it required the identity this role writes, so
the only caller that could reach such an endpoint would be asking a running
server to identify a workspace that is by construction already identified — which
is the refusal. Bootstrapping over an unauthenticated surface is a different risk
class from reading one. The read half already has an endpoint:
ContextResponse.project_id on GET /v0/beads/context is InitVerifier's answer, on
the wire, today. Recorded in both leaf docs and in the checklist.

USER-VISIBLE, for the wave's changelog pass: proxied init adopts instead of
overwriting on a shared database; `bd init` no longer heals a substrate carrying
a prefix and no project id, which is Q8 as written; an explicit BEADS_DIR outside
the repo now gets a project id written from its own metadata.json instead of
being left half-identified. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-ini-0..7.

A-ini-0 IS A FALSE PREMISE IN THE BRIEF, not a finding about the code: bd-zl3u8,
bd-jtp1h and bd-yby99 do not exist in the workspace at BEADS_DIR. Verified by two
bd binaries failing to open it and by a direct SQL read of all 5,603 issues.
Everything else the brief asserted about the code checked out, so the spec used
was the brief plus Q8 plus A2.

Verified: build, vet, gofmt clean; golangci-lint 0 issues (its unparam check is
what found resolveInitIssuePrefix's now-dead `write` return, removed here);
TestBootstrapperContract 12/12 at dolt, embeddeddolt and uow; internal/workapi,
internal/storage, internal/telemetry, internal/jira, issueops, the root layering
pins and the whole internal/storage/domain and internal/storage/uow packages
green; internal/httpapi green and `make api-check` clean with no spec or
generated diff; TestInit* and TestResolveInit*/TestApplyInitGateway* and
TestCorpusGolden and TestDoctor* green under BEADS_TEST_EMBEDDED_DOLT=1;
TestProxiedServerExternalCreate, TestProxiedServerPing and TestProxiedServerUpdate
green under BEADS_TEST_PROXIED_SERVER=1, each of which runs
`bd init --proxied-server` in its harness; TestProxiedLookup green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
CI Bot 2026-08-06 02:51:42 +00:00
commit 27ffb42e1f
35 changed files with 2239 additions and 357 deletions

View file

@ -0,0 +1,409 @@
package conformance
import (
"context"
"errors"
"testing"
publicops "github.com/steveyegge/beads/issueops"
)
// This file holds the contract every implementation of publicops.Bootstrapper
// and publicops.InitVerifier must satisfy. Each case asserts what
// issueops/bootstrapper.go and issueops/initverifier.go PROMISE, cited by line,
// rather than what any one backend happens to do today; a backend that
// disagrees is parked at its own wiring site with skipKnownDivergence so the
// case still runs on the ones that agree.
//
// THE TWO ROLES SHARE ONE CONTRACT FILE because they share one plane and every
// promise on either of them is a statement about the other. Bootstrap's promise
// is "a later VerifyIdentity answers with this result"; the verifier's promise
// is that absence and unreadability are different answers, which is only
// checkable against a substrate a bootstrap did or did not reach. Splitting
// them would mean each file seeding the state the other one writes.
//
// WHAT THIS CONTRACT IS FOR, given that the decision is elsewhere. All three
// backends validate through workapi.ValidateBootstrapRequest and decide the
// refusal through workapi.RefuseIdentifiedSubstrate, and those two functions'
// whole tables — each required field, the trailing-hyphen normalization, all
// three identified shapes — are pinned without a database in
// internal/workapi/bootstrap_test.go. Repeating them here would be testing one
// pure function three times over three sql-servers. What only a real backend
// can show is the SUBSTRATE half:
//
// - that the identity is there for the NEXT caller, which on the
// unit-of-work backend means a different transaction;
// - that a REFUSAL WROTE NOTHING — a statement about the keys on disk rather
// than about the error the validator already returned, and the one that
// matters most, because the whole point of Q8's ruling is that running init
// twice must not relabel a workspace other rigs are already minting ids
// against;
// - that the verifier reports a FAILED READ as an error rather than as an
// empty identity, which is the difference between "this database is
// unprovisioned, bootstrap it" and "this connection dropped";
// - that a bootstrap costs AT MOST ONE version-control entry rather than one
// per key.
//
// THE IDENTITY IS GLOBAL TO A WORKSPACE and cannot be namespaced the way the
// issue contracts namespace their seeded ids: two keys are the point, and a
// case that wrote them under a per-test name would assert nothing about the
// pair the roles actually read. Every case therefore SEEDS the identity
// explicitly through the fixture's out-of-band hook before it asserts, so the
// cases are order-independent over one shared plane rather than a sequence that
// has to run in order.
//
// There are three wirings and only TWO independent bodies between them: dolt
// and embeddeddolt both run internal/storage/issueops.BootstrapInTx and
// VerifyIdentityInTx and differ only in how they reach a transaction, so they
// are one vote plus an engine check; the unit-of-work provider is the second,
// and it reads, refuses and writes through the domain config use case inside
// one transaction it labels itself.
// BootstrapperFixture supplies adapter-specific storage access for the identity
// assertions.
type BootstrapperFixture struct {
// Bootstrapper and InitVerifier are the two surfaces under test, taken
// from the backend's own capability accessors.
Bootstrapper publicops.Bootstrapper
InitVerifier publicops.InitVerifier
// SeedIdentity writes the two identity markers OUT OF BAND, past both
// roles, and is how every case establishes the state it asserts about. An
// empty string means "this substrate carries no such marker", which the
// roles read identically to an absent row (initverifier.go:13-19).
//
// It is NOT a roleFixtureKit hook — the kit is frozen, and it can seed a
// prefix but has no way to UNSEED one, which is the state a bootstrap needs
// to be reachable at all on a database its own test harness already
// initialized. Each wiring supplies its own short closure over the config
// and metadata seams that backend already publishes, the way the version
// contract supplies RecordMarkers.
SeedIdentity func(ctx context.Context, prefix, projectID string) error
// CountHistory reports how many history entries the fixture's branch has.
// A nil hook means "this backend cannot observe history", and the case that
// needs it SKIPS with that reason rather than passing quietly.
CountHistory func(context.Context) (int, error)
}
// RunBootstrapperIdentifiesAFreshSubstrate pins bootstrapper.go's core promise —
// "A LATER VerifyIdentity IS THE PROMISE" — on the state every workspace starts
// in: nothing recorded, and a first bootstrap that both markers and the next
// caller can see.
func RunBootstrapperIdentifiesAFreshSubstrate(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "", "")
before := verifyWorkspaceIdentity(t, ctx, fixture)
if before.Prefix != "" || before.ProjectID != "" {
t.Fatalf("VerifyIdentity() = %+v on an unbootstrapped substrate, want both empty", before)
}
result := bootstrap(t, ctx, fixture, publicops.BootstrapRequest{
Prefix: "acmefresh",
ProjectID: "proj-fresh",
})
if result.Prefix != "acmefresh" || result.ProjectID != "proj-fresh" {
t.Fatalf("Bootstrap() = %+v, want the identity it was given", result)
}
assertWorkspaceIdentity(t, ctx, fixture, "acmefresh", "proj-fresh")
}
// RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen pins
// bootstrapper.go:24-30: the value a later VerifyIdentity answers with is the
// normalized one, and BootstrapResult.Prefix says so rather than echoing the
// request.
//
// It is here as well as in the pure test because the normalization has to
// survive the WRITE. Two of the three backends pass this key through a settings
// plane that normalizes it again and one does not, which is exactly the way a
// caller ends up with a prefix that depends on which route it initialized from.
func RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "", "")
result := bootstrap(t, ctx, fixture, publicops.BootstrapRequest{
Prefix: "acmetrim-",
ProjectID: "proj-trim",
})
if result.Prefix != "acmetrim" {
t.Fatalf("Bootstrap() result prefix = %q, want the stored form %q", result.Prefix, "acmetrim")
}
assertWorkspaceIdentity(t, ctx, fixture, "acmetrim", "proj-trim")
}
// RunBootstrapperRefusesAnIdentifiedSubstrate is Q8's ruling, asserted from the
// side that matters: not that the error came back, which the pure test already
// pins, but that the identity standing on the substrate is EXACTLY the one that
// was there before.
//
// bootstrapper.go's "THE REFUSAL WRITES NOTHING" is what makes running `bd init`
// twice safe on a database several rigs share. A body that refused after writing
// the prefix would pass an error-only assertion and still have renamed every id
// the other rigs are about to mint.
func RunBootstrapperRefusesAnIdentifiedSubstrate(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "acmeheld", "proj-held")
_, err := fixture.Bootstrapper.Bootstrap(ctx, publicops.BootstrapRequest{
Prefix: "acmeintruder",
ProjectID: "proj-intruder",
})
if !errors.Is(err, publicops.ErrAlreadyIdentified) {
t.Fatalf("Bootstrap() over an identified substrate error = %v, want ErrAlreadyIdentified", err)
}
var refusal *publicops.AlreadyIdentifiedError
if !errors.As(err, &refusal) {
t.Fatalf("Bootstrap() error = %v, want an *AlreadyIdentifiedError naming what it found", err)
}
if refusal.Prefix != "acmeheld" || refusal.ProjectID != "proj-held" {
t.Fatalf("refusal = %+v, want it to name the identity already on the substrate", refusal)
}
assertWorkspaceIdentity(t, ctx, fixture, "acmeheld", "proj-held")
}
// RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix pins the "EITHER marker"
// half of the refusal.
//
// This is the shape that is NOT a re-init: a database several rigs share, or one
// a provisioning tool stamped with a prefix, carries the prefix without a
// project id. A bootstrap that keyed its refusal on the project id alone would
// overwrite it and rename every id those rigs are about to mint.
func RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "acmeprefixonly", "")
_, err := fixture.Bootstrapper.Bootstrap(ctx, publicops.BootstrapRequest{
Prefix: "acmeintruder",
ProjectID: "proj-intruder",
})
if !errors.Is(err, publicops.ErrAlreadyIdentified) {
t.Fatalf("Bootstrap() over a prefix-only substrate error = %v, want ErrAlreadyIdentified", err)
}
assertWorkspaceIdentity(t, ctx, fixture, "acmeprefixonly", "")
}
// RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID pins the other half.
// It is the state a bootstrap that failed partway leaves behind on a backend
// with no transaction to roll back, and bootstrapper.go's "ATOMICITY IS NOT
// PROMISED ACROSS THE WHOLE WRITE" says it is refused rather than finished —
// the safe direction, because the alternative is a retry that completes an
// identity it did not choose.
func RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "", "proj-idonly")
_, err := fixture.Bootstrapper.Bootstrap(ctx, publicops.BootstrapRequest{
Prefix: "acmeintruder",
ProjectID: "proj-intruder",
})
if !errors.Is(err, publicops.ErrAlreadyIdentified) {
t.Fatalf("Bootstrap() over a project-id-only substrate error = %v, want ErrAlreadyIdentified", err)
}
assertWorkspaceIdentity(t, ctx, fixture, "", "proj-idonly")
}
// RunBootstrapperRefusesAnInvalidRequestWithoutWriting pins bootstrapper.go's
// ErrValidation clauses against the substrate rather than against the error.
//
// Both facts matter and the second is why this case reads the identity back: a
// body that validated AFTER its first write would leave a prefix on a substrate
// the caller was told it had failed to bootstrap, and the next attempt would
// then hit the refusal above.
func RunBootstrapperRefusesAnInvalidRequestWithoutWriting(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "", "")
_, err := fixture.Bootstrapper.Bootstrap(ctx, publicops.BootstrapRequest{
Prefix: "acmeinvalid",
})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("Bootstrap() with no project id error = %v, want ErrValidation", err)
}
assertWorkspaceIdentity(t, ctx, fixture, "", "")
}
// RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete pins the case
// that separates a failure from a refusal.
//
// A canceled context is the one failure every backend can be made to have. It is
// not the only one they will meet in the field, but a body that respects
// cancellation on the way in is a body that has not written before it looked —
// and the workspace it leaves behind is one the next attempt can still
// bootstrap, rather than one the refusal above will reject forever.
func RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "", "")
canceled, cancel := context.WithCancel(ctx)
cancel()
if _, err := fixture.Bootstrapper.Bootstrap(canceled, publicops.BootstrapRequest{
Prefix: "acmecanceled",
ProjectID: "proj-canceled",
}); err == nil {
t.Fatal("Bootstrap() on a canceled context = nil error, want the failure reported rather than a silent success")
}
assertWorkspaceIdentity(t, ctx, fixture, "", "")
}
// RunBootstrapperRecordsAtMostOneHistoryEntry pins bootstrapper.go's "AT MOST
// ONE VERSION-CONTROL ENTRY".
//
// The promise is deliberately an upper bound rather than a number: the identity
// lands on planes that travel, so a backend that commits at all is right to
// record the bootstrap, and one whose front door commits the whole of `bd init`
// afterwards is right to record none. What it forbids is the shape a caller
// writing these six values through six ordinary setters gets, which is six
// entries.
func RunBootstrapperRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
if fixture.CountHistory == nil {
t.Skip("fixture cannot observe history on this backend")
}
seedWorkspaceIdentity(t, ctx, fixture, "", "")
before, err := fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory() before: %v", err)
}
bootstrap(t, ctx, fixture, publicops.BootstrapRequest{
Prefix: "acmehist",
ProjectID: "proj-hist",
})
after, err := fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory() after: %v", err)
}
if after-before > 1 {
t.Fatalf("history entries %d -> %d, want a bootstrap to record at most one", before, after)
}
}
// RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate pins
// initverifier.go:13-19: "" is a NORMAL ANSWER, not an error and not a missing
// row to classify.
//
// It is the answer the one caller that matters acts on — `bd init` deciding
// whether there is anything to adopt — and turning it into ErrNotFound would
// make the ordinary case look like a failure.
func RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "", "")
result, err := fixture.InitVerifier.VerifyIdentity(ctx, publicops.VerifyIdentityRequest{})
if err != nil {
t.Fatalf("VerifyIdentity() on an unidentified substrate error = %v, want the empty answer with a nil error", err)
}
if result.Prefix != "" || result.ProjectID != "" {
t.Fatalf("VerifyIdentity() = %+v, want both markers empty", result)
}
}
// RunInitVerifierReportsAPartialIdentityAsItStands pins the verifier's job on
// the state the refusal cases care about: it REPORTS what is there, marker by
// marker, rather than collapsing a half-identified substrate into identified or
// unidentified.
//
// That is what lets its caller tell a database a provisioning tool stamped with
// a prefix apart from a bootstrap that failed partway — two states with the same
// answer to "is this identified?" and different answers to "what should happen
// next?".
func RunInitVerifierReportsAPartialIdentityAsItStands(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "acmepartial", "")
result := verifyWorkspaceIdentity(t, ctx, fixture)
if result.Prefix != "acmepartial" || result.ProjectID != "" {
t.Fatalf("VerifyIdentity() = %+v, want the prefix reported and the project id empty", result)
}
}
// RunInitVerifierReportsAFailedReadAsAnError is the promise everything else on
// that role is for (initverifier.go:47-56): an ABSENT identity and an
// UNREADABLE one are different answers.
//
// The two states are one line apart at every call site — an unprovisioned
// database gets bootstrapped, a database that merely could not be reached must
// not be — so a body that reported the read failure as two empty strings would
// hand `bd init` a second identity for a workspace that already had one. A
// canceled context is the failure every backend can be made to have.
func RunInitVerifierReportsAFailedReadAsAnError(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
seedWorkspaceIdentity(t, ctx, fixture, "acmeunread", "proj-unread")
canceled, cancel := context.WithCancel(ctx)
cancel()
result, err := fixture.InitVerifier.VerifyIdentity(canceled, publicops.VerifyIdentityRequest{})
if err == nil {
t.Fatalf("VerifyIdentity() on a canceled context = %+v with a nil error, want the failure reported rather than an empty identity", result)
}
}
// RunInitVerifierWritesNothing pins initverifier.go's "IT WRITES NOTHING",
// including the version-control entry: a verifier that repaired or recorded what
// it found would be the bootstrap these two roles exist to keep separate, and a
// read that committed would put an entry in the log of every workspace `bd init`
// merely LOOKED at.
func RunInitVerifierWritesNothing(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
t.Helper()
if fixture.CountHistory == nil {
t.Skip("fixture cannot observe history on this backend")
}
seedWorkspaceIdentity(t, ctx, fixture, "acmereadonly", "proj-readonly")
before, err := fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory() before: %v", err)
}
verifyWorkspaceIdentity(t, ctx, fixture)
after, err := fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory() after: %v", err)
}
if after != before {
t.Fatalf("history entries %d -> %d, want a read to record none", before, after)
}
assertWorkspaceIdentity(t, ctx, fixture, "acmereadonly", "proj-readonly")
}
// seedWorkspaceIdentity puts the identity in a known state past both roles.
func seedWorkspaceIdentity(t *testing.T, ctx context.Context, fixture BootstrapperFixture, prefix, projectID string) {
t.Helper()
if fixture.SeedIdentity == nil {
t.Fatal("fixture.SeedIdentity is nil: every case seeds the identity it asserts about")
}
if err := fixture.SeedIdentity(ctx, prefix, projectID); err != nil {
t.Fatalf("seed identity (%q, %q): %v", prefix, projectID, err)
}
}
// bootstrap runs a bootstrap that is expected to succeed.
func bootstrap(t *testing.T, ctx context.Context, fixture BootstrapperFixture, req publicops.BootstrapRequest) publicops.BootstrapResult {
t.Helper()
result, err := fixture.Bootstrapper.Bootstrap(ctx, req)
if err != nil {
t.Fatalf("Bootstrap(%+v): %v", req, err)
}
return result
}
func verifyWorkspaceIdentity(t *testing.T, ctx context.Context, fixture BootstrapperFixture) publicops.VerifyIdentityResult {
t.Helper()
result, err := fixture.InitVerifier.VerifyIdentity(ctx, publicops.VerifyIdentityRequest{})
if err != nil {
t.Fatalf("VerifyIdentity(): %v", err)
}
return result
}
// assertWorkspaceIdentity reads the pair back THROUGH InitVerifier, which is the
// promise being checked: bootstrapper.go says a later VerifyIdentity is what
// "bootstrapped" means, and on the unit-of-work backend that read is a new
// transaction — the only place a write that never committed shows up.
func assertWorkspaceIdentity(t *testing.T, ctx context.Context, fixture BootstrapperFixture, prefix, projectID string) {
t.Helper()
got := verifyWorkspaceIdentity(t, ctx, fixture)
if got.Prefix != prefix || got.ProjectID != projectID {
t.Fatalf("VerifyIdentity() = %+v, want {Prefix:%q ProjectID:%q}", got, prefix, projectID)
}
}

View file

@ -30,6 +30,7 @@ import (
"github.com/steveyegge/beads/internal/templates/agents"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
"golang.org/x/term"
)
@ -76,33 +77,40 @@ func applyInitGatewayCredential(ctx context.Context, beadsDir string, doltCfg *d
return nil
}
// resolveInitIssuePrefix decides how init sets the issue_prefix. readErr is the
// error (if any) from reading the current issue_prefix out of the database.
// resolveInitIssuePrefix decides which issue_prefix init would set. readErr is
// the error (if any) from reading the workspace's identity out of the database.
//
// Non-gateway (legacy, unchanged): if none is configured yet, set the sanitized
// prefix (dots -> underscores so issue IDs stay valid identifiers); if one exists,
// leave it (avoid clobbering a shared database). readErr is ignored here, exactly
// Non-gateway (legacy, unchanged): if none is configured yet, return the
// sanitized prefix (dots -> underscores so issue IDs stay valid identifiers); if
// one exists, return "" — there is nothing to set, because init must not clobber
// a prefix a shared database already carries. readErr is ignored here, exactly
// as legacy init ignored it. Gateway: the prefix is server-provisioned, so an
// existing value is adopted (no write). A missing value is a provisioning-contract
// violation — bd will not choose a prefix for a hosted database — but only when the
// read genuinely succeeded and returned empty: a read error means we could not
// consult the server, so it is surfaced as the transient failure it is rather than
// misdiagnosed as an unprovisioned database.
func resolveInitIssuePrefix(gateway bool, existing, dbName, prefix string, readErr error) (value string, write bool, err error) {
// existing value is adopted. A missing value is a provisioning-contract
// violation — bd will not choose a prefix for a hosted database — but only when
// the read genuinely succeeded and returned empty: a read error means we could
// not consult the server, so it is surfaced as the transient failure it is
// rather than misdiagnosed as an unprovisioned database.
//
// It used to also return WHETHER to write. That half is gone: whether the prefix
// may be written is the same question as whether the substrate is unidentified,
// and issueops.Bootstrapper answers it inside the transaction it writes in
// rather than here, several hundred lines earlier. A "" value means what it
// always meant — nothing for init to set.
func resolveInitIssuePrefix(gateway bool, existing, dbName, prefix string, readErr error) (value string, err error) {
if existing != "" {
return "", false, nil
return "", nil
}
if gateway {
if readErr != nil {
return "", false, fmt.Errorf(
return "", fmt.Errorf(
"reading issue_prefix from hosted database %q: %w", dbName, readErr)
}
return "", false, fmt.Errorf(
return "", fmt.Errorf(
"hosted database %q has no issue_prefix -- provisioning-contract violation; "+
"bd will not choose one for a hosted database (re-provision server-side, then re-run init)",
dbName)
}
return strings.ReplaceAll(prefix, ".", "_"), true, nil
return strings.ReplaceAll(prefix, ".", "_"), nil
}
// resolveInitProjectID decides init's project identity by reconciling the local
@ -218,6 +226,62 @@ func shouldInitSharedGlobalDB(sharedServer, sharedServerMode, gateway bool) bool
return (sharedServer || sharedServerMode) && !gateway
}
// seedInitWorkspaceIdentity records the workspace's identity through
// issueops.Bootstrapper, or adopts the one already on the substrate.
//
// VERIFY, THEN BOOTSTRAP OR ADOPT. The role REFUSES an already-identified
// substrate, which is Q8's ruling and the guard that now sits below both front
// doors rather than only in front of one; asking first is how a front door tells
// a workspace it may identify from one it must leave alone. That refusal is what
// makes `bd init` safe to run against a database another rig is already minting
// ids in: before this, the proxied route rewrote both markers every time.
//
// found is the identity the caller already read with InitVerifier, in the same
// snapshot it read the prefix in. projectID is "" only when init composed no
// metadata.json — an explicit BEADS_DIR whose Dolt data lives elsewhere — and the
// workspace's own metadata.json is then the place to ask.
func seedInitWorkspaceIdentity(
ctx context.Context,
store storage.DoltStorage,
found issueops.VerifyIdentityResult,
prefix, projectID, beadsDir string,
) error {
if store == nil {
return nil
}
if found.Prefix != "" || found.ProjectID != "" {
// Adopt. The caller has already reconciled metadata.json against
// found.ProjectID; re-stamping the substrate with the value it gave us
// would be a write with nothing to say.
return nil
}
if projectID == "" {
// No metadata.json was composed on this path. Take the id the workspace
// already records so the substrate and the file agree, and mint one only
// when neither exists — a prefix without an identity is exactly the
// half-bootstrapped state the role refuses to complete later.
if existing, err := configfile.Load(beadsDir); err == nil && existing != nil {
projectID = existing.ProjectID
}
if projectID == "" {
projectID = configfile.GenerateProjectID()
}
}
bootstrapper, err := store.Bootstrapper()
if err != nil {
return fmt.Errorf("failed to reach the workspace identity: %v", err)
}
_, err = bootstrapper.Bootstrap(ctx, issueops.BootstrapRequest{
Prefix: prefix,
ProjectID: projectID,
})
if err != nil {
return fmt.Errorf("failed to record the workspace identity: %v", err)
}
return nil
}
var initCmd = &cobra.Command{
Use: "init",
GroupID: "setup",
@ -1353,25 +1417,33 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// These settings define fundamental behavior (issue IDs, sync workflow).
// Failure here indicates a serious problem that prevents normal operation.
// Set the issue prefix in config (only if not already configured —
// avoid clobbering when multiple rigs share the same Dolt database)
existing, existingErr := store.GetConfig(ctx, "issue_prefix")
// Read the workspace's identity ONCE, through issueops.InitVerifier.
//
// It used to be two reads at two places — the prefix here and
// _project_id four hundred lines down — each with its own error
// handling. The role reads the pair in one snapshot, so the prefix this
// init adopts and the project id it reconciles against cannot come from
// either side of another rig's write, and an UNREADABLE identity is an
// error rather than an empty one the gateway paths would misdiagnose as
// an unprovisioned database.
initVerifier, err := store.InitVerifier()
if err != nil {
_ = store.Close()
return fmt.Errorf("failed to reach the workspace identity: %v", err)
}
dbIdentity, identityReadErr := initVerifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
// Sanitize dots to underscores so issue IDs (e.g. "GPUPolynomials_jl-1")
// remain valid identifiers. Must match DoltDatabase sanitization above.
// In gateway mode the prefix is server-provisioned: adopt an existing one,
// refuse to invent a missing one. A read error is surfaced as a transient
// failure rather than misread as an unprovisioned (contract-violating) db.
issuePrefix, writePrefix, err := resolveInitIssuePrefix(doltCfg.Gateway, existing, dbName, prefix, existingErr)
// seedInitWorkspaceIdentity, below, is where issuePrefix lands.
issuePrefix, err := resolveInitIssuePrefix(doltCfg.Gateway, dbIdentity.Prefix, dbName, prefix, identityReadErr)
if err != nil {
_ = store.Close()
return err
}
if writePrefix {
if err := store.SetConfig(ctx, "issue_prefix", issuePrefix); err != nil {
_ = store.Close()
return fmt.Errorf("failed to set issue prefix: %v", err)
}
}
// === TRACKING METADATA (Pattern B: Warn and Continue) ===
// Tracking metadata enhances functionality (diagnostics, version checks, collision detection)
@ -1414,6 +1486,13 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
}
}
// bootstrapProjectID is the identity seedInitWorkspaceIdentity will
// record, resolved inside the metadata.json block below because that is
// where local and database identities are reconciled. It stays "" when
// that block does not run, and the seeding step reads the workspace's
// own metadata.json for it instead.
bootstrapProjectID := ""
// Create or preserve metadata.json for database metadata (bd-zai fix)
if useLocalBeads {
// First, check if metadata.json already exists
@ -1456,18 +1535,19 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// (GH#4637 Part A) and fails before this code runs at all. Without the
// Gateway skip, init would save the stale id as success and every later
// normal open would hard-fail with PROJECT IDENTITY MISMATCH.
//
// The id itself comes from the single InitVerifier read taken
// beside the prefix, rather than from a second GetMetadata here.
// shouldConsultInitProjectID still decides whether to USE it, so
// which identities init adopts is unchanged; what changed is that
// the two halves of one identity can no longer be read either side
// of another rig's write.
adoptedFromDB := ""
var adoptReadErr error
if store != nil && shouldConsultInitProjectID(doltCfg.Gateway, cfg.ProjectID, database, bootstrappedFromRemote) {
existingID, err := store.GetMetadata(ctx, "_project_id")
if err != nil {
adoptReadErr = err
} else if existingID != "" {
adoptedFromDB = existingID
}
adoptedFromDB = dbIdentity.ProjectID
}
localID := cfg.ProjectID
resolvedID, identityChanged, err := resolveInitProjectID(doltCfg.Gateway, localID, adoptedFromDB, dbName, adoptReadErr)
resolvedID, identityChanged, err := resolveInitProjectID(doltCfg.Gateway, localID, adoptedFromDB, dbName, identityReadErr)
if err != nil {
_ = store.Close()
return err
@ -1557,14 +1637,10 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// Non-fatal - continue anyway
}
// Write project identity to database for cross-project verification (GH#2372).
// Skip in gateway mode: the identity is server-authoritative and the
// credential may be read-only, so bd must not write it back.
if store != nil && shouldWriteProjectIDLocally(doltCfg.Gateway, cfg.ProjectID) {
if err := store.SetMetadata(ctx, "_project_id", cfg.ProjectID); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to write project ID to database: %v\n", err)
}
}
// The identity write itself happens once, below this block, through
// issueops.Bootstrapper — see seedInitWorkspaceIdentity. This is
// where the id it uses is decided.
bootstrapProjectID = cfg.ProjectID
// Create config.yaml template (prefix is stored in DB, not config.yaml)
if err := createConfigYaml(beadsDir, false, ""); err != nil {
@ -1619,11 +1695,27 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
}
}
// Seed the workspace's identity, through issueops.Bootstrapper, in the
// one place this route writes it. Gateway mode skips it: the identity
// is server-authoritative and the credential may be read-only, so bd
// adopts what it verified rather than writing it back.
if shouldWriteInitStateToDB(doltCfg.Gateway) {
if err := seedInitWorkspaceIdentity(ctx, store, dbIdentity, issuePrefix, bootstrapProjectID, beadsDir); err != nil {
_ = store.Close()
return err
}
}
// Initialize last_import_time metadata to mark the database as synced.
// This prevents bd doctor from reporting "No last_import_time recorded in database"
// after init completes. Sets the metadata to current time in RFC3339 format.
// (mybd-9gw: sync divergence fix). Skipped in gateway mode: this is client-local
// sync state that must not be written into the shared, server-owned database.
//
// It is NOT part of the bootstrap, and neither are the fingerprints
// above: those four values are refreshed on EVERY init, adopt or not,
// while the identity is written once and adopted forever. See
// issueops.Bootstrapper.
if shouldWriteInitStateToDB(doltCfg.Gateway) {
if err := store.SetMetadata(ctx, "last_import_time", time.Now().Format(time.RFC3339)); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to initialize last_import_time: %v\n", err)
@ -2052,8 +2144,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// appears in IDs, so the summary must show it instead of a prefix that
// will never be minted.
effectivePrefix := prefix
if existing != "" {
effectivePrefix = existing
if dbIdentity.Prefix != "" {
effectivePrefix = dbIdentity.Prefix
}
fmt.Printf(" Database: %s\n", ui.RenderAccent(dbName))
fmt.Printf(" Issue prefix: %s\n", ui.RenderAccent(effectivePrefix))

View file

@ -94,7 +94,7 @@ func TestApplyInitGatewayCredentialPresetWins(t *testing.T) {
// Gateway with no server-provisioned issue_prefix is a provisioning-contract
// violation: bd refuses to choose one for a hosted database.
func TestResolveInitIssuePrefixGatewayMissing(t *testing.T) {
value, write, err := resolveInitIssuePrefix(true, "", "myhosteddb", "fallback", nil)
value, err := resolveInitIssuePrefix(true, "", "myhosteddb", "fallback", nil)
if err == nil {
t.Fatal("expected a provisioning-contract error for a hosted db with no issue_prefix")
}
@ -102,8 +102,8 @@ func TestResolveInitIssuePrefixGatewayMissing(t *testing.T) {
!strings.Contains(err.Error(), "myhosteddb") {
t.Fatalf("error should name the db and the contract violation, got: %v", err)
}
if write || value != "" {
t.Fatalf("nothing must be written on violation: value=%q write=%v", value, write)
if value != "" {
t.Fatalf("nothing must be set on violation: value=%q", value)
}
}
@ -112,7 +112,7 @@ func TestResolveInitIssuePrefixGatewayMissing(t *testing.T) {
// simply failed to read it.
func TestResolveInitIssuePrefixGatewayReadError(t *testing.T) {
readErr := errors.New("dial tcp: connection refused")
value, write, err := resolveInitIssuePrefix(true, "", "myhosteddb", "fallback", readErr)
value, err := resolveInitIssuePrefix(true, "", "myhosteddb", "fallback", readErr)
if err == nil {
t.Fatal("expected the read error to be surfaced")
}
@ -122,19 +122,19 @@ func TestResolveInitIssuePrefixGatewayReadError(t *testing.T) {
if strings.Contains(err.Error(), "provisioning-contract violation") {
t.Fatalf("a transient read error must not be reported as a contract violation, got: %v", err)
}
if write || value != "" {
t.Fatalf("nothing must be written on a read error: value=%q write=%v", value, write)
if value != "" {
t.Fatalf("nothing must be set on a read error: value=%q", value)
}
}
// Gateway with an already-provisioned issue_prefix: adopt it (no write).
func TestResolveInitIssuePrefixGatewayAdopts(t *testing.T) {
value, write, err := resolveInitIssuePrefix(true, "hq", "myhosteddb", "fallback", nil)
value, err := resolveInitIssuePrefix(true, "hq", "myhosteddb", "fallback", nil)
if err != nil {
t.Fatalf("adoption must not error: %v", err)
}
if write || value != "" {
t.Fatalf("adoption must not write: value=%q write=%v", value, write)
if value != "" {
t.Fatalf("adoption must not set a prefix: value=%q", value)
}
}
@ -142,23 +142,23 @@ func TestResolveInitIssuePrefixGatewayAdopts(t *testing.T) {
// This is the byte-identical legacy behavior — and a read error is ignored here,
// exactly as legacy init ignored it (the guard is gateway-only).
func TestResolveInitIssuePrefixNonGatewaySets(t *testing.T) {
value, write, err := resolveInitIssuePrefix(false, "", "mydb", "GPUPolynomials.jl", errors.New("ignored"))
value, err := resolveInitIssuePrefix(false, "", "mydb", "GPUPolynomials.jl", errors.New("ignored"))
if err != nil {
t.Fatalf("non-gateway set must not error even with a read error: %v", err)
}
if !write || value != "GPUPolynomials_jl" {
t.Fatalf("value=%q write=%v, want (GPUPolynomials_jl, true)", value, write)
if value != "GPUPolynomials_jl" {
t.Fatalf("value=%q, want GPUPolynomials_jl", value)
}
}
// Non-gateway with an existing prefix: no-op (do not clobber a shared db).
func TestResolveInitIssuePrefixNonGatewayExisting(t *testing.T) {
value, write, err := resolveInitIssuePrefix(false, "existing", "mydb", "prefix", nil)
value, err := resolveInitIssuePrefix(false, "existing", "mydb", "prefix", nil)
if err != nil {
t.Fatalf("non-gateway existing must not error: %v", err)
}
if write || value != "" {
t.Fatalf("existing prefix must be preserved: value=%q write=%v", value, write)
if value != "" {
t.Fatalf("existing prefix must be preserved: value=%q", value)
}
}

View file

@ -19,6 +19,8 @@ import (
"github.com/steveyegge/beads/internal/storage/git"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
type initProxiedServerInput struct {
@ -176,45 +178,78 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err)
}
adoptedPrefix, adoptedProjectID := prefix, projectID
err = uow.RunTx(ctx, initUOWProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
if in.teamServer {
// bts owns the shared database: adopt identity and write nothing —
// no identity, no tracking metadata (repo_id/clone_id are per-clone
// fingerprints; last-init-wins overwrites feed false cross-project
// mismatch diagnostics), no Dolt remote. Empty message skips the
// Dolt commit.
p, id, err := adoptTeamServerIdentity(ctx, uw.ConfigUseCase(), dbName, prefix, in.prefix != "", projectID)
if err != nil {
return "", err
}
adoptedPrefix, adoptedProjectID = p, id
return "", nil
}
bootstrapParams := domain.BootstrapProjectParams{
Prefix: prefix,
ProjectID: projectID,
BdVersion: Version,
LastImportTime: time.Now(),
RepoID: repoID,
CloneID: cloneID,
}
if remoteURL != "" {
bootstrapParams.RemoteName = "origin"
bootstrapParams.RemoteURL = remoteURL
}
if _, err := uw.BootstrapUseCase().BootstrapProject(ctx, bootstrapParams); err != nil {
return "", fmt.Errorf("bootstrap project: %w", err)
}
return "bd init", nil
})
// The identity goes through the two roles, so this route and the direct one
// share one definition of what a workspace's identity is and one rule about
// when it may be written. The order is VERIFY, then bootstrap or adopt:
// Bootstrapper REFUSES an already-identified substrate, which is the guard
// below both front doors, and asking first is how a front door tells a
// re-init from the collision that guard exists for.
verifier, err := proxiedInitVerifier(initUOWProvider)
if err != nil {
return HandleError("%v", err)
}
adoptedPrefix, adoptedProjectID := prefix, projectID
if in.teamServer {
// bts owns the shared database: adopt identity and write nothing — no
// identity, no tracking metadata (repo_id/clone_id are per-clone
// fingerprints; last-init-wins overwrites feed false cross-project
// mismatch diagnostics), no Dolt remote.
adoptedPrefix, adoptedProjectID, err = adoptTeamServerIdentity(ctx, verifier, dbName, prefix, in.prefix != "", projectID)
if err != nil {
return HandleError("%v", err)
}
} else {
existing, err := verifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
if err != nil {
return HandleError("reading project identity from database %q: %v", dbName, err)
}
switch {
case existing.Prefix != "" || existing.ProjectID != "":
// Another rig — or an earlier init — already identified this
// database. ADOPT it. Before this went through the roles, this
// route rewrote the prefix and the project id every time, which is
// what renamed the ids a co-tenant was about to mint; the direct
// route has adopted here since it was written.
adoptedPrefix, adoptedProjectID = existing.Prefix, existing.ProjectID
if !in.quiet {
fmt.Printf(" %s Adopted project identity from existing database\n", ui.RenderPass("✓"))
}
default:
bootstrapper, err := proxiedBootstrapper(initUOWProvider)
if err != nil {
return HandleError("%v", err)
}
result, err := bootstrapper.Bootstrap(ctx, issueops.BootstrapRequest{
Prefix: prefix,
ProjectID: projectID,
})
if err != nil {
return HandleError("bootstrap project: %v", err)
}
adoptedPrefix, adoptedProjectID = result.Prefix, result.ProjectID
}
// The per-clone tracking state is written on EVERY init, adopt or not,
// which is why it is not on the role: a fresh clone of an
// already-identified database needs its own fingerprints precisely
// because it bootstrapped nothing.
if err := recordProxiedInitTrackingState(ctx, initUOWProvider, repoID, cloneID); err != nil {
return HandleError("%v", err)
}
// The Dolt remote is configured SEPARATELY from the identity, the way
// the direct route has always configured it. They are different facts
// with different lifetimes — where this database syncs to, versus what
// it is — and folding them into one call is what let a remote that could
// not be created fail a bootstrap that had already succeeded.
if remoteURL != "" {
if err := configureProxiedInitDoltRemote(ctx, initUOWProvider, remoteURL); err != nil {
return HandleError("%v", err)
}
}
}
// metadata.json was written with a locally-minted project id before any
// DB connection existed; the adopted id must replace it before the tail
// git-commits .beads/.
@ -277,18 +312,102 @@ func resolveProxiedInitRemoteURL(ctx context.Context, gitUC domain.GitUseCase, i
return ""
}
type teamServerIdentityReader interface {
GetConfig(ctx context.Context, key string) (string, error)
GetMetadata(ctx context.Context, key string) (string, error)
// proxiedInitVerifier and proxiedBootstrapper hand back the two identity
// surfaces through the provider's OWN capability accessors — the same two-step
// proxiedCounter performs, and for the same reason: the accessor is where each
// layer is added.
//
// They are asked for SEPARATELY rather than as one surface because the roles are
// separate, and team-server mode is what that separation is for: it holds a
// verifier and never obtains a bootstrapper, so the path bd must not write on
// cannot reach the write.
func proxiedInitVerifier(provider uow.UnitOfWorkProvider) (issueops.InitVerifier, error) {
src, ok := provider.(uow.InitVerifierSource)
if !ok {
return nil, fmt.Errorf("proxied-server provider %T does not offer the identity-read surface", provider)
}
return src.InitVerifier()
}
func proxiedBootstrapper(provider uow.UnitOfWorkProvider) (issueops.Bootstrapper, error) {
src, ok := provider.(uow.BootstrapperSource)
if !ok {
return nil, fmt.Errorf("proxied-server provider %T does not offer the identity-seeding surface", provider)
}
return src.Bootstrapper()
}
// recordProxiedInitTrackingState seeds the per-clone bookkeeping that used to
// ride along inside BootstrapProject: the repository and clone fingerprints,
// the synced-at marker and the recorded binary version.
//
// It is separate from the identity because its LIFETIME is: the identity is
// written once and then adopted forever, while these four describe the clone
// running init and are refreshed every time it runs. Keeping them in the
// refusable one-time write would have meant a re-init on a shared database
// silently stopped recording them.
func recordProxiedInitTrackingState(ctx context.Context, provider uow.UnitOfWorkProvider, repoID, cloneID string) error {
return uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
cfg := uw.ConfigUseCase()
// An absent fingerprint is recorded as nothing rather than as "": an
// empty row reads back to cross-project verification as a clone whose
// fingerprint failed to compute.
if repoID != "" {
if err := cfg.SetMetadata(ctx, "repo_id", repoID); err != nil {
return "", fmt.Errorf("record repo_id: %w", err)
}
}
if cloneID != "" {
if err := cfg.SetMetadata(ctx, "clone_id", cloneID); err != nil {
return "", fmt.Errorf("record clone_id: %w", err)
}
}
if err := cfg.SetMetadata(ctx, "last_import_time", time.Now().UTC().Format(time.RFC3339)); err != nil {
return "", fmt.Errorf("record last_import_time: %w", err)
}
if err := cfg.SetLocalMetadata(ctx, workapi.MetadataKeyVersion, Version); err != nil {
return "", fmt.Errorf("record bd_version: %w", err)
}
return "bd init", nil
})
}
// configureProxiedInitDoltRemote adds the sync remote, skipping a name that is
// already taken. It is the remote half of what BootstrapProject used to do in
// one call with the identity; the direct route has always kept the two apart.
func configureProxiedInitDoltRemote(ctx context.Context, provider uow.UnitOfWorkProvider, remoteURL string) error {
return uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
remotes, err := uw.DoltRemoteUseCase().ListRemotes(ctx)
if err != nil {
return "", fmt.Errorf("list remotes: %w", err)
}
for _, r := range remotes {
if r.Name == "origin" {
return "", nil
}
}
if err := uw.DoltRemoteUseCase().CreateRemote(ctx, "origin", remoteURL); err != nil {
return "", fmt.Errorf("create remote origin: %w", err)
}
return "", nil
})
}
// adoptTeamServerIdentity reads the bts-provisioned identity out of the shared
// database, following the gateway contract: adopt if present, hard error if
// absent — bd never writes identity in team-server mode.
func adoptTeamServerIdentity(ctx context.Context, reader teamServerIdentityReader, dbName, localPrefix string, prefixIsExplicit bool, localProjectID string) (prefix, projectID string, err error) {
dbPrefix, prefixReadErr := reader.GetConfig(ctx, "issue_prefix")
if _, _, err := resolveInitIssuePrefix(true, dbPrefix, dbName, localPrefix, prefixReadErr); err != nil {
if prefixReadErr == nil {
//
// It takes an issueops.InitVerifier rather than a config reader of its own
// because the distinction it is built around — an ABSENT identity means
// "unprovisioned, tell them to run bts init", an UNREADABLE one means "the
// connection failed, say so" — is now the role's promise rather than this
// function's care. The two markers also arrive as ONE snapshot, so the prefix it
// adopts and the project id it adopts cannot come from either side of a
// concurrent write.
func adoptTeamServerIdentity(ctx context.Context, verifier issueops.InitVerifier, dbName, localPrefix string, prefixIsExplicit bool, localProjectID string) (prefix, projectID string, err error) {
identity, readErr := verifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
if _, err := resolveInitIssuePrefix(true, identity.Prefix, dbName, localPrefix, readErr); err != nil {
if readErr == nil {
return "", "", fmt.Errorf(
"database %q has no project identity (config.issue_prefix) — provision it with 'bts init' (or heal an older bts database with 'bts migrate')",
dbName)
@ -297,23 +416,22 @@ func adoptTeamServerIdentity(ctx context.Context, reader teamServerIdentityReade
}
// An explicit --prefix that disagrees must not be silently ignored; a
// merely derived prefix adopts silently.
if prefixIsExplicit && dbPrefix != localPrefix {
if prefixIsExplicit && identity.Prefix != localPrefix {
return "", "", fmt.Errorf(
"--prefix %q conflicts with issue_prefix %q provisioned in database %q; omit --prefix to adopt the provisioned one",
localPrefix, dbPrefix, dbName)
localPrefix, identity.Prefix, dbName)
}
dbProjectID, idReadErr := reader.GetMetadata(ctx, "_project_id")
adoptedID, _, err := resolveInitProjectID(true, localProjectID, dbProjectID, dbName, idReadErr)
adoptedID, _, err := resolveInitProjectID(true, localProjectID, identity.ProjectID, dbName, readErr)
if err != nil {
if idReadErr == nil {
if readErr == nil {
return "", "", fmt.Errorf(
"database %q has no project identity (metadata._project_id) — provision it with 'bts init' (or heal an older bts database with 'bts migrate')",
dbName)
}
return "", "", err
}
return dbPrefix, adoptedID, nil
return identity.Prefix, adoptedID, nil
}
type proxiedMetadataInputs struct {

View file

@ -7,27 +7,30 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/steveyegge/beads/issueops"
)
// fakeIdentityReader stands in for issueops.InitVerifier, which is what
// adoptTeamServerIdentity now reads the bts-provisioned identity through.
//
// It answers with the PAIR and one error, because that is the shape of the role:
// the two markers are read in one snapshot, so there is no longer a state where
// the prefix read succeeded and the project-id read did not. The two subtests
// that asserted those separately are one subtest now, and it is a stronger
// statement than the two it replaces — a caller cannot see half an identity
// from a connection that dropped.
type fakeIdentityReader struct {
prefix string
prefixErr error
projectID string
projectIDErr error
prefix string
projectID string
readErr error
}
func (f *fakeIdentityReader) GetConfig(_ context.Context, key string) (string, error) {
if key != "issue_prefix" {
return "", errors.New("unexpected config key: " + key)
func (f *fakeIdentityReader) VerifyIdentity(_ context.Context, _ issueops.VerifyIdentityRequest) (issueops.VerifyIdentityResult, error) {
if f.readErr != nil {
return issueops.VerifyIdentityResult{}, f.readErr
}
return f.prefix, f.prefixErr
}
func (f *fakeIdentityReader) GetMetadata(_ context.Context, key string) (string, error) {
if key != "_project_id" {
return "", errors.New("unexpected metadata key: " + key)
}
return f.projectID, f.projectIDErr
return issueops.VerifyIdentityResult{Prefix: f.prefix, ProjectID: f.projectID}, nil
}
func TestAdoptTeamServerIdentity(t *testing.T) {
@ -79,16 +82,12 @@ func TestAdoptTeamServerIdentity(t *testing.T) {
assert.Contains(t, err.Error(), "_project_id")
})
t.Run("prefix read error surfaces as transient, not unprovisioned", func(t *testing.T) {
reader := &fakeIdentityReader{prefixErr: errors.New("connection reset")}
_, _, err := adoptTeamServerIdentity(ctx, reader, "beads_gc", "gc", false, "local-id")
require.Error(t, err)
assert.Contains(t, err.Error(), "connection reset")
assert.NotContains(t, err.Error(), "bts init")
})
t.Run("project id read error surfaces as transient, not unprovisioned", func(t *testing.T) {
reader := &fakeIdentityReader{prefix: "gc", projectIDErr: errors.New("connection reset")}
// The distinction this pins is issueops.InitVerifier's whole reason for
// existing: an ABSENT identity means "unprovisioned, run bts init" and an
// UNREADABLE one means "the connection failed". Reporting the second as the
// first is how a flaky link gets a shared database re-provisioned.
t.Run("read error surfaces as transient, not unprovisioned", func(t *testing.T) {
reader := &fakeIdentityReader{readErr: errors.New("connection reset")}
_, _, err := adoptTeamServerIdentity(ctx, reader, "beads_gc", "gc", false, "local-id")
require.Error(t, err)
assert.Contains(t, err.Error(), "connection reset")

View file

@ -29,6 +29,29 @@ question (`Count` and `CountByGroup` share a predicate and differ only in
whether the answer is a number or a number per bucket). The rule forbids
APPENDING later, not being born whole.
**And one command may be born with TWO roles.** `bd init` is the case:
`Bootstrapper` writes the workspace identity and `InitVerifier` reads it, and
they are separate even though `VersionReconciler` — whose read and write are
also two shapes of one question — is one. The test that separates them is not
"is it the same question" but **can one caller be entitled to the read and not
the write**. bd reads a workspace identity on paths where it is forbidden to
write one: a bts-provisioned team database whose identity the provisioning tool
owns, an authenticating gateway whose credential may be read-only. Handing those
callers a surface with the write on it is the shape that produces writes the
front door then has to suppress flag by flag — `shouldWriteProjectIDLocally`,
`shouldWriteInitStateToDB`, `shouldInitSharedGlobalDB` are three of those. A
capability a caller must not have is a capability it should not be able to
reach.
**Ask what the role's fields' LIFETIMES are before folding them in.** The same
slice teaches this: `bd init` seeds five values, and only two of them —
the prefix and the project id — are written once and adopted forever. The
repository and clone fingerprints, the synced-at marker and the recorded binary
version are refreshed on EVERY init, adopt or not, because a fresh clone of an
already-identified database needs its own. Putting those on a one-time,
refusable write means either a refusal that skips them or a write that is no
longer one-time. They stayed off the role.
## The checklist
Thirteen steps. Steps 1-9 are the role; 10-12 are what makes it the ONLY way
@ -190,6 +213,15 @@ in; 13 is the HTTP surface, which lands with the command rather than after it.
AMBIGUITIES.md for the owner — is the work. Adding an operation because the
checklist has a row for one is not.
`issueops.Bootstrapper` and `issueops.InitVerifier` are the second and third,
and their reason is different enough to be worth its own sentence: a server
can only serve a database it is already bound to, and binding it required
the identity the bootstrapper writes, so the only caller that could reach
such an endpoint would be asking a running server to identify a workspace
that is by construction already identified. The read half has no endpoint
because it already has one — `ContextResponse.project_id` is its answer, on
the wire, today.
**The ROLES database source is the part that surprises.** `httpapi.Config`
carries either a unit-of-work provider or the roles, and the roles are
required TOGETHER: a new operation served from a new role adds a required

View file

@ -670,6 +670,14 @@ func (s *configStore) VersionReconciler() (issueops.VersionReconciler, error) {
return nil, &storage.ErrUnsupported{Op: "VersionReconciler", Backend: "jira-config-stub"}
}
func (s *configStore) Bootstrapper() (issueops.Bootstrapper, error) {
return nil, &storage.ErrUnsupported{Op: "Bootstrapper", Backend: "jira-config-stub"}
}
func (s *configStore) InitVerifier() (issueops.InitVerifier, error) {
return nil, &storage.ErrUnsupported{Op: "InitVerifier", Backend: "jira-config-stub"}
}
func (s *configStore) CycleDetector() (issueops.CycleDetector, error) {
return nil, &storage.ErrUnsupported{Op: "CycleDetector", Backend: "jira-config-stub"}
}

View file

@ -0,0 +1,61 @@
package dolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// Bootstrapper returns the guarded identity-seeding surface for this store.
func (s *DoltStore) Bootstrapper() (issueops.Bootstrapper, error) {
if s == nil {
return nil, &storage.ErrUnsupported{Op: "Bootstrapper", Backend: "nil"}
}
return &bootstrapper{store: s}, nil
}
// bootstrapper seeds a substrate's identity inside ONE transaction.
//
// There is no shared constructor package for this role, for the reason sweeper
// gives: the work is a read and the write that read QUALIFIES, and a
// transaction is not reachable through storage.DoltStorage. The sharing happens
// one level down instead — this body and the embedded store's are a few lines
// each around issueops.BootstrapInTx — and two wrappers over one body is still
// ONE vote, which the conformance contract says out loud.
//
// A front door cannot construct this: the type is unexported and the accessor
// is the only door.
type bootstrapper struct{ store *DoltStore }
var _ issueops.Bootstrapper = (*bootstrapper)(nil)
// Bootstrap seeds the request's identity.
//
// VALIDATION HAPPENS BEFORE THE TRANSACTION, so a refused request costs no
// database work — which is what makes issueops.Bootstrapper's "a refusal writes
// nothing" true of the connection as well as of the keys.
//
// NO VERSION-CONTROL ENTRY IS RECORDED HERE, which the role permits and which
// matches what this store's ordinary SetConfig/SetMetadata already do: they
// land in the working set and the front door's own initial commit is what
// records them. Adding a DOLT_COMMIT would give a bootstrap an entry that `bd
// init`'s commit then duplicates.
func (b *bootstrapper) Bootstrap(ctx context.Context, req issueops.BootstrapRequest) (issueops.BootstrapResult, error) {
req, err := workapi.ValidateBootstrapRequest(req)
if err != nil {
return issueops.BootstrapResult{}, err
}
var result issueops.BootstrapResult
if err := b.store.withWriteTx(ctx, func(tx *sql.Tx) error {
var err error
result, err = storeops.BootstrapInTx(ctx, tx, req)
return err
}); err != nil {
return issueops.BootstrapResult{}, err
}
return result, nil
}

View file

@ -0,0 +1,100 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/workapi"
)
// TestBootstrapperContract runs the Bootstrapper and InitVerifier contract
// against the server-backed store.
//
// The cases are subtests of one parent so the whole role suite shares one store
// and one copy-on-write branch. Sharing matters here the way it does for the
// settings and version roles and not the way it does for the issue roles: the
// identity is GLOBAL to a workspace and cannot be namespaced under the fixture
// prefix, so every case seeds it explicitly instead of relying on what the case
// before it left. setupTestStore already marks the PARENT parallel; no subtest
// here calls t.Parallel, because two of them take a log delta.
func TestBootstrapperContract(t *testing.T) {
fixture, ctx, cleanup := newDoltBootstrapperFixture(t)
defer cleanup()
t.Run("IdentifiesAFreshSubstrate", func(t *testing.T) {
conformance.RunBootstrapperIdentifiesAFreshSubstrate(t, ctx, fixture)
})
t.Run("StoresThePrefixWithoutItsTrailingHyphen", func(t *testing.T) {
conformance.RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen(t, ctx, fixture)
})
t.Run("RefusesAnIdentifiedSubstrate", func(t *testing.T) {
conformance.RunBootstrapperRefusesAnIdentifiedSubstrate(t, ctx, fixture)
})
t.Run("RefusesASubstrateCarryingOnlyAPrefix", func(t *testing.T) {
conformance.RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix(t, ctx, fixture)
})
t.Run("RefusesASubstrateCarryingOnlyAProjectID", func(t *testing.T) {
conformance.RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID(t, ctx, fixture)
})
t.Run("RefusesAnInvalidRequestWithoutWriting", func(t *testing.T) {
conformance.RunBootstrapperRefusesAnInvalidRequestWithoutWriting(t, ctx, fixture)
})
t.Run("LeavesTheSubstrateUntouchedWhenItCannotComplete", func(t *testing.T) {
conformance.RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete(t, ctx, fixture)
})
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
conformance.RunBootstrapperRecordsAtMostOneHistoryEntry(t, ctx, fixture)
})
t.Run("VerifierAnswersEmptyForAnUnidentifiedSubstrate", func(t *testing.T) {
conformance.RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate(t, ctx, fixture)
})
t.Run("VerifierReportsAPartialIdentityAsItStands", func(t *testing.T) {
conformance.RunInitVerifierReportsAPartialIdentityAsItStands(t, ctx, fixture)
})
t.Run("VerifierReportsAFailedReadAsAnError", func(t *testing.T) {
conformance.RunInitVerifierReportsAFailedReadAsAnError(t, ctx, fixture)
})
t.Run("VerifierWritesNothing", func(t *testing.T) {
conformance.RunInitVerifierWritesNothing(t, ctx, fixture)
})
}
func newDoltBootstrapperFixture(t *testing.T) (conformance.BootstrapperFixture, context.Context, func()) {
t.Helper()
store, storeCleanup := setupTestStore(t)
ctx, cancel := testContext(t)
bootstrapper, err := store.Bootstrapper()
if err != nil {
cancel()
storeCleanup()
t.Fatalf("Bootstrapper(): %v", err)
}
verifier, err := store.InitVerifier()
if err != nil {
cancel()
storeCleanup()
t.Fatalf("InitVerifier(): %v", err)
}
kit := newDoltRoleFixtureKit(store, "boot")
fixture := conformance.BootstrapperFixture{
Bootstrapper: bootstrapper,
InitVerifier: verifier,
// Past both roles, through the store's own config and metadata seams.
// This is the hook the frozen kit cannot supply: it can SET a prefix but
// has no way to unset one, and an unidentified substrate is the state a
// bootstrap needs to be reachable at all on a database setupTestStore
// already initialized.
SeedIdentity: func(ctx context.Context, prefix, projectID string) error {
if err := store.SetConfig(ctx, workapi.ConfigKeyIssuePrefix, prefix); err != nil {
return err
}
return store.SetMetadata(ctx, workapi.MetadataKeyProjectID, projectID)
},
CountHistory: kit.CountHistory,
}
return fixture, ctx, func() {
cancel()
storeCleanup()
}
}

View file

@ -0,0 +1,40 @@
package dolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/issueops"
)
// InitVerifier returns the guarded identity-read surface for this store.
func (s *DoltStore) InitVerifier() (issueops.InitVerifier, error) {
if s == nil {
return nil, &storage.ErrUnsupported{Op: "InitVerifier", Backend: "nil"}
}
return &initVerifier{store: s}, nil
}
// initVerifier reads the substrate's identity inside one READ transaction.
//
// It takes a transaction it could technically do without, because the pair is
// compared as a pair: a prefix read before a concurrent bootstrap beside a
// project id read after one is a torn answer that looks exactly like the
// cross-project mismatch the comparison exists to find.
type initVerifier struct{ store *DoltStore }
var _ issueops.InitVerifier = (*initVerifier)(nil)
func (v *initVerifier) VerifyIdentity(ctx context.Context, _ issueops.VerifyIdentityRequest) (issueops.VerifyIdentityResult, error) {
var result issueops.VerifyIdentityResult
if err := v.store.withReadTx(ctx, func(tx *sql.Tx) error {
var err error
result, err = storeops.VerifyIdentityInTx(ctx, tx)
return err
}); err != nil {
return issueops.VerifyIdentityResult{}, err
}
return result, nil
}

View file

@ -1,107 +0,0 @@
package domain
import (
"context"
"fmt"
"time"
)
type BootstrapUseCase interface {
BootstrapProject(ctx context.Context, params BootstrapProjectParams) (BootstrapProjectResult, error)
}
type BootstrapProjectParams struct {
Prefix string
ProjectID string
BdVersion string
LastImportTime time.Time
RepoID string
CloneID string
RemoteName string
RemoteURL string
}
type BootstrapProjectResult struct {
RemoteConfigured bool
}
func NewBootstrapUseCase(cfgRepo ConfigSQLRepository, remoteUseCase DoltRemoteUseCase) BootstrapUseCase {
return &bootstrapUseCaseImpl{
cfgRepo: cfgRepo,
remoteUseCase: remoteUseCase,
}
}
type bootstrapUseCaseImpl struct {
cfgRepo ConfigSQLRepository
remoteUseCase DoltRemoteUseCase
}
var _ BootstrapUseCase = (*bootstrapUseCaseImpl)(nil)
func (u *bootstrapUseCaseImpl) BootstrapProject(ctx context.Context, params BootstrapProjectParams) (BootstrapProjectResult, error) {
if params.Prefix == "" {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: Prefix must not be empty")
}
if params.ProjectID == "" {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: ProjectID must not be empty")
}
if params.BdVersion == "" {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: BdVersion must not be empty")
}
if params.LastImportTime.IsZero() {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: LastImportTime must not be zero")
}
if err := u.cfgRepo.SetConfig(ctx, "issue_prefix", params.Prefix); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set issue_prefix: %w", err)
}
if err := u.cfgRepo.SetMetadata(ctx, "_project_id", params.ProjectID); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set _project_id: %w", err)
}
if params.RepoID != "" {
if err := u.cfgRepo.SetMetadata(ctx, "repo_id", params.RepoID); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set repo_id: %w", err)
}
}
if params.CloneID != "" {
if err := u.cfgRepo.SetMetadata(ctx, "clone_id", params.CloneID); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set clone_id: %w", err)
}
}
if err := u.cfgRepo.SetMetadata(ctx, "last_import_time", params.LastImportTime.UTC().Format(time.RFC3339)); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set last_import_time: %w", err)
}
if err := u.cfgRepo.SetLocalMetadata(ctx, "bd_version", params.BdVersion); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set bd_version: %w", err)
}
var result BootstrapProjectResult
if params.RemoteURL != "" {
name := params.RemoteName
if name == "" {
name = "origin"
}
remotes, err := u.remoteUseCase.ListRemotes(ctx)
if err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: list remotes: %w", err)
}
exists := false
for _, r := range remotes {
if r.Name == name {
exists = true
break
}
}
if !exists {
if err := u.remoteUseCase.CreateRemote(ctx, name, params.RemoteURL); err != nil {
return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: create remote %s: %w", name, err)
}
result.RemoteConfigured = true
}
}
return result, nil
}

View file

@ -1,90 +0,0 @@
package domain
import (
"context"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
)
type recordingConfigRepo struct {
ConfigSQLRepository
config map[string]string
metadata map[string]string
localMetadata map[string]string
}
func newRecordingConfigRepo() *recordingConfigRepo {
return &recordingConfigRepo{
config: map[string]string{},
metadata: map[string]string{},
localMetadata: map[string]string{},
}
}
func (r *recordingConfigRepo) SetConfig(_ context.Context, key, value string) error {
r.config[key] = value
return nil
}
func (r *recordingConfigRepo) SetMetadata(_ context.Context, key, value string) error {
r.metadata[key] = value
return nil
}
func (r *recordingConfigRepo) SetLocalMetadata(_ context.Context, key, value string) error {
r.localMetadata[key] = value
return nil
}
func TestBootstrapProject_WritesIdentity(t *testing.T) {
repo := newRecordingConfigRepo()
uc := NewBootstrapUseCase(repo, nil)
params := BootstrapProjectParams{
Prefix: "gc",
ProjectID: "proj-bts",
BdVersion: "1.0.0-test",
LastImportTime: time.Date(2026, 7, 29, 0, 0, 0, 0, time.UTC),
RepoID: "repo-1",
CloneID: "clone-1",
}
if _, err := uc.BootstrapProject(context.Background(), params); err != nil {
t.Fatalf("BootstrapProject: %v", err)
}
if got := repo.config["issue_prefix"]; got != "gc" {
t.Errorf("issue_prefix = %q, want %q", got, "gc")
}
if got := repo.metadata["_project_id"]; got != "proj-bts" {
t.Errorf("_project_id = %q, want %q", got, "proj-bts")
}
}
func TestResolveDoltDatabaseName_DerivedFlag(t *testing.T) {
cases := []struct {
name string
cfgDB string
prefix string
dbFlag string
wantName string
wantDerived bool
}{
{"flag pins the name", "meta_db", "pfx", "flag_db", "flag_db", false},
{"metadata pins the name", "meta_db", "pfx", "", "meta_db", false},
{"prefix guess is derived", "", "my-proj", "", "my_proj", true},
{"default fallback is derived", "", "", "", "beads", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var fileCfg *configfile.Config
if tc.cfgDB != "" {
fileCfg = &configfile.Config{DoltDatabase: tc.cfgDB}
}
name, derived := resolveDoltDatabaseName(fileCfg, tc.prefix, tc.dbFlag)
if name != tc.wantName || derived != tc.wantDerived {
t.Errorf("resolveDoltDatabaseName() = (%q, %v), want (%q, %v)", name, derived, tc.wantName, tc.wantDerived)
}
})
}
}

View file

@ -42,6 +42,18 @@ type ConfigUseCase interface {
DeleteConfig(ctx context.Context, key string) error
GetAllConfig(ctx context.Context) (map[string]string, error)
GetMetadata(ctx context.Context, key string) (string, error)
// SetMetadata writes one durable metadata value inside the caller's unit of
// work. It is the write half of the GetMetadata above it, published for the
// same reason SetLocalMetadata was: issueops.Bootstrapper's unit-of-work
// body reads the identity, refuses over an identified substrate and writes
// the new one in ONE transaction, and a refusal decided outside the
// transaction that writes is a refusal two racing inits both pass.
//
// It replaces BootstrapUseCase, which held its own copy of which keys an
// identity is made of — a copy the direct route never used and no test
// compared against it. The keys are named once in internal/workapi now and
// this seam moves bytes.
SetMetadata(ctx context.Context, key, value string) error
GetLocalMetadata(ctx context.Context, key string) (string, error)
// SetLocalMetadata writes one clone-local, dolt-ignored value inside the
// caller's unit of work. It is the write half of GetLocalMetadata, and it
@ -223,6 +235,13 @@ func (u *configUseCaseImpl) GetAllConfig(ctx context.Context) (map[string]string
return out, nil
}
func (u *configUseCaseImpl) SetMetadata(ctx context.Context, key, value string) error {
if err := u.cfgRepo.SetMetadata(ctx, key, value); err != nil {
return fmt.Errorf("SetMetadata: %w", err)
}
return nil
}
func (u *configUseCaseImpl) SetLocalMetadata(ctx context.Context, key, value string) error {
if err := u.cfgRepo.SetLocalMetadata(ctx, key, value); err != nil {
return fmt.Errorf("SetLocalMetadata: %w", err)

View file

@ -0,0 +1,51 @@
//go:build cgo
package embeddeddolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// Bootstrapper returns the guarded identity-seeding surface for this store.
func (s *EmbeddedDoltStore) Bootstrapper() (issueops.Bootstrapper, error) {
if s == nil {
return nil, &storage.ErrUnsupported{Op: "Bootstrapper", Backend: "nil"}
}
return &bootstrapper{store: s}, nil
}
// bootstrapper seeds a substrate's identity inside one connection's
// transaction.
//
// It is a sibling of the server-backed store's body rather than a shared
// package for the reason that one gives: the work needs a TRANSACTION, which
// storage.DoltStorage does not publish, so the sharing happens below both of
// them at issueops.BootstrapInTx. The two stores differ here only in how they
// reach a transaction.
type bootstrapper struct{ store *EmbeddedDoltStore }
var _ issueops.Bootstrapper = (*bootstrapper)(nil)
// Bootstrap seeds the request's identity. Validation happens before the
// connection is opened, so a refused request costs no database work.
func (b *bootstrapper) Bootstrap(ctx context.Context, req issueops.BootstrapRequest) (issueops.BootstrapResult, error) {
req, err := workapi.ValidateBootstrapRequest(req)
if err != nil {
return issueops.BootstrapResult{}, err
}
var result issueops.BootstrapResult
if err := b.store.withConn(ctx, true, func(tx *sql.Tx) error {
var err error
result, err = storeops.BootstrapInTx(ctx, tx, req)
return err
}); err != nil {
return issueops.BootstrapResult{}, err
}
return result, nil
}

View file

@ -0,0 +1,94 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/workapi"
)
// TestBootstrapperContract runs the Bootstrapper and InitVerifier contract
// against the embedded store, which runs the SAME bodies the server-backed
// store does (internal/storage/issueops.BootstrapInTx and VerifyIdentityInTx)
// and differs only in how it reaches a transaction and in the engine
// underneath. That is what this wiring catches; it is not an independent vote
// on the bodies.
//
// One environment for the whole suite, and here that is a correctness
// requirement rather than only a runtime one: the identity is global to a
// workspace, so the subtests run sequentially over one plane, each seeding the
// state it asserts about.
func TestBootstrapperContract(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "boot")
ctx := t.Context()
fixture := newEmbeddedBootstrapperFixture(t, te)
t.Run("IdentifiesAFreshSubstrate", func(t *testing.T) {
conformance.RunBootstrapperIdentifiesAFreshSubstrate(t, ctx, fixture)
})
t.Run("StoresThePrefixWithoutItsTrailingHyphen", func(t *testing.T) {
conformance.RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen(t, ctx, fixture)
})
t.Run("RefusesAnIdentifiedSubstrate", func(t *testing.T) {
conformance.RunBootstrapperRefusesAnIdentifiedSubstrate(t, ctx, fixture)
})
t.Run("RefusesASubstrateCarryingOnlyAPrefix", func(t *testing.T) {
conformance.RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix(t, ctx, fixture)
})
t.Run("RefusesASubstrateCarryingOnlyAProjectID", func(t *testing.T) {
conformance.RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID(t, ctx, fixture)
})
t.Run("RefusesAnInvalidRequestWithoutWriting", func(t *testing.T) {
conformance.RunBootstrapperRefusesAnInvalidRequestWithoutWriting(t, ctx, fixture)
})
t.Run("LeavesTheSubstrateUntouchedWhenItCannotComplete", func(t *testing.T) {
conformance.RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete(t, ctx, fixture)
})
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
conformance.RunBootstrapperRecordsAtMostOneHistoryEntry(t, ctx, fixture)
})
t.Run("VerifierAnswersEmptyForAnUnidentifiedSubstrate", func(t *testing.T) {
conformance.RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate(t, ctx, fixture)
})
t.Run("VerifierReportsAPartialIdentityAsItStands", func(t *testing.T) {
conformance.RunInitVerifierReportsAPartialIdentityAsItStands(t, ctx, fixture)
})
t.Run("VerifierReportsAFailedReadAsAnError", func(t *testing.T) {
conformance.RunInitVerifierReportsAFailedReadAsAnError(t, ctx, fixture)
})
t.Run("VerifierWritesNothing", func(t *testing.T) {
conformance.RunInitVerifierWritesNothing(t, ctx, fixture)
})
}
func newEmbeddedBootstrapperFixture(t *testing.T, te *testEnv) conformance.BootstrapperFixture {
t.Helper()
bootstrapper, err := te.store.Bootstrapper()
if err != nil {
t.Fatalf("Bootstrapper(): %v", err)
}
verifier, err := te.store.InitVerifier()
if err != nil {
t.Fatalf("InitVerifier(): %v", err)
}
kit := newEmbeddedRoleFixtureKit(te, "boot")
return conformance.BootstrapperFixture{
Bootstrapper: bootstrapper,
InitVerifier: verifier,
// Past both roles, through the store's own config and metadata seams:
// the frozen kit can set a prefix but cannot unset one, and an
// unidentified substrate is the state a bootstrap needs to be reachable
// at all on a database newTestEnv already initialized.
SeedIdentity: func(ctx context.Context, prefix, projectID string) error {
if err := te.store.SetConfig(ctx, workapi.ConfigKeyIssuePrefix, prefix); err != nil {
return err
}
return te.store.SetMetadata(ctx, workapi.MetadataKeyProjectID, projectID)
},
CountHistory: kit.CountHistory,
}
}

View file

@ -0,0 +1,41 @@
//go:build cgo
package embeddeddolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/issueops"
)
// InitVerifier returns the guarded identity-read surface for this store.
func (s *EmbeddedDoltStore) InitVerifier() (issueops.InitVerifier, error) {
if s == nil {
return nil, &storage.ErrUnsupported{Op: "InitVerifier", Backend: "nil"}
}
return &initVerifier{store: s}, nil
}
// initVerifier reads the substrate's identity inside one connection's
// transaction, so the pair the caller compares is one snapshot rather than two
// reads a concurrent bootstrap can land between.
type initVerifier struct{ store *EmbeddedDoltStore }
var _ issueops.InitVerifier = (*initVerifier)(nil)
func (v *initVerifier) VerifyIdentity(ctx context.Context, _ issueops.VerifyIdentityRequest) (issueops.VerifyIdentityResult, error) {
var result issueops.VerifyIdentityResult
// commit=false: this role writes nothing, and a committing connection would
// make a read look like a mutation to everything watching the store.
if err := v.store.withConn(ctx, false, func(tx *sql.Tx) error {
var err error
result, err = storeops.VerifyIdentityInTx(ctx, tx)
return err
}); err != nil {
return issueops.VerifyIdentityResult{}, err
}
return result, nil
}

View file

@ -0,0 +1,26 @@
package storage
import (
"github.com/steveyegge/beads/issueops"
)
// Bootstrapper returns the inner store's identity-seeding surface.
//
// IT RECURSES UNWRAPPED even though the role WRITES, which is the same
// statement hook_sweeper.go makes and for the same reason: the decision is about
// the hook VOCABULARY, not about whether the role writes. This decorator
// publishes on_create, on_update and on_close, and every one of those hands a
// hook script an ISSUE. A bootstrap creates no issue — it makes a database into
// a workspace — so there is nothing this layer could fire that a hook script
// could read.
//
// There is a second reason here that the sweep does not have. A bootstrap
// happens on a workspace whose hooks are not installed yet: `bd init` writes
// .beads/hooks/ AFTER the identity lands, so a hook fired from this accessor
// would run whatever the previous project in that directory left behind, or
// nothing at all. The accessor still EXISTS on the decorator rather than being
// inherited, because the accessor set is uniform across the chain and there is a
// reflection test that says so.
func (h *HookFiringStore) Bootstrapper() (issueops.Bootstrapper, error) {
return h.inner.Bootstrapper()
}

View file

@ -0,0 +1,14 @@
package storage
import (
"github.com/steveyegge/beads/issueops"
)
// InitVerifier returns the inner store's identity-read surface.
//
// Reads fire no hooks, so this recurses and hands back the inner surface
// unwrapped, as hook_issue_reader.go and hook_counter.go do: there is no
// completion to report.
func (h *HookFiringStore) InitVerifier() (issueops.InitVerifier, error) {
return h.inner.InitVerifier()
}

View file

@ -0,0 +1,83 @@
package issueops
import (
"context"
"github.com/steveyegge/beads/internal/workapi"
publicops "github.com/steveyegge/beads/issueops"
)
// This file holds the store-backed bodies behind issueops.Bootstrapper and
// issueops.InitVerifier.
//
// They live here rather than in an importable internal/workapi/store<role>
// package for the reason SweepInTx and DetectCycleReportInTx do: the work is a
// read and the write it QUALIFIES, and those two must see one snapshot or the
// refusal is a suggestion. storage.DoltStorage publishes methods, not
// transactions, so a body written against it could only check-then-act. The two
// Dolt-backed stores share these bodies and differ only in how they reach a
// transaction, so they are ONE vote and the unit-of-work provider is the
// second. There is nothing here a front door could construct — both functions
// take a transaction — so no depguard entry is needed to keep them out of
// cmd/bd.
// BootstrapInTx seeds an unidentified substrate's identity, refusing an
// identified one, inside ONE transaction.
//
// It assumes a request already normalized and refused by
// workapi.ValidateBootstrapRequest. The accessors validate BEFORE opening a
// transaction, so a refused request costs no database work.
//
// THE READ AND THE WRITE SHARE THE TRANSACTION, which is the whole reason this
// body is shaped as a function over a *sql.Tx. Two inits racing against one
// shared database is not hypothetical — it is the ordinary case for a
// bts-provisioned server and for two rigs pointed at one Dolt database — and a
// refusal decided outside the transaction that writes is one both racers pass.
//
// The per-clone bookkeeping `bd init` seeds alongside the identity — the
// fingerprints, the synced-at marker, the recorded binary version — is not here
// and not on the role; see issueops.Bootstrapper for why.
func BootstrapInTx(ctx context.Context, tx DBTX, req publicops.BootstrapRequest) (publicops.BootstrapResult, error) {
prefix, projectID, err := verifyIdentityInTx(ctx, tx)
if err != nil {
return publicops.BootstrapResult{}, err
}
if err := workapi.RefuseIdentifiedSubstrate(prefix, projectID); err != nil {
return publicops.BootstrapResult{}, err
}
if err := SetConfigInTx(ctx, tx, workapi.ConfigKeyIssuePrefix, req.Prefix); err != nil {
return publicops.BootstrapResult{}, err
}
if err := SetMetadataInTx(ctx, tx, workapi.MetadataKeyProjectID, req.ProjectID); err != nil {
return publicops.BootstrapResult{}, err
}
return publicops.BootstrapResult{Prefix: req.Prefix, ProjectID: req.ProjectID}, nil
}
// VerifyIdentityInTx reads the substrate's identity inside one transaction.
func VerifyIdentityInTx(ctx context.Context, tx DBTX) (publicops.VerifyIdentityResult, error) {
prefix, projectID, err := verifyIdentityInTx(ctx, tx)
if err != nil {
return publicops.VerifyIdentityResult{}, err
}
return publicops.VerifyIdentityResult{Prefix: prefix, ProjectID: projectID}, nil
}
// verifyIdentityInTx reads the pair the bootstrap refusal and the verifier both
// ask about, so the two cannot come to disagree about what "identified" means.
//
// Both reads happen even when the first already decides the outcome: the
// verifier publishes the pair, and the refusal names both values.
func verifyIdentityInTx(ctx context.Context, tx DBTX) (prefix, projectID string, err error) {
prefix, err = GetConfigInTx(ctx, tx, workapi.ConfigKeyIssuePrefix)
if err != nil {
return "", "", err
}
projectID, err = GetMetadataInTx(ctx, tx, workapi.MetadataKeyProjectID)
if err != nil {
return "", "", err
}
return prefix, projectID, nil
}

View file

@ -11,9 +11,9 @@ import (
"github.com/steveyegge/beads/issueops"
)
// roleAccessorNames is the eighteen-strong capability surface every storage
// roleAccessorNames is the twenty-one-strong capability surface every storage
// decorator has to answer for. It is written out rather than derived so that
// adding a nineteenth role to DoltStorage without deciding what each decorator
// adding a twenty-second role to DoltStorage without deciding what each decorator
// does with it is a compile-or-test failure somewhere, not silence.
var roleAccessorNames = []string{
"IssueLifecycle",
@ -30,6 +30,8 @@ var roleAccessorNames = []string{
"Querier",
"Sweeper",
"Deleter",
"Bootstrapper",
"InitVerifier",
"Commenter",
"ReadyClaimer",
"BatchCloser",
@ -72,7 +74,7 @@ func assertRoleAccessorsAreDeclared(t *testing.T, decorator reflect.Type) {
}
}
// roleAccessorStore is a DoltStorage whose only real methods are the eighteen
// roleAccessorStore is a DoltStorage whose only real methods are the twenty-one
// role accessors, each answering with a distinguishable sentinel so a test can
// tell a decorated surface from a passed-through one.
type roleAccessorStore struct {
@ -96,6 +98,8 @@ type roleAccessorStore struct {
querier issueops.Querier
sweeper issueops.Sweeper
deleter issueops.Deleter
bootstrapper issueops.Bootstrapper
verifier issueops.InitVerifier
err error
}
@ -121,6 +125,8 @@ func newRoleAccessorStore() *roleAccessorStore {
querier: sentinel,
sweeper: sentinel,
deleter: sentinel,
bootstrapper: sentinel,
verifier: sentinel,
}
}
@ -156,6 +162,12 @@ func (s *roleAccessorStore) Sweeper() (issueops.Sweeper, error) {
func (s *roleAccessorStore) Deleter() (issueops.Deleter, error) {
return s.deleter, s.err
}
func (s *roleAccessorStore) Bootstrapper() (issueops.Bootstrapper, error) {
return s.bootstrapper, s.err
}
func (s *roleAccessorStore) InitVerifier() (issueops.InitVerifier, error) {
return s.verifier, s.err
}
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
return s.claimer, s.err
}
@ -167,7 +179,7 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error
return s.editor, s.err
}
// roleAccessorSentinel implements all eighteen roles at once. Nothing calls its
// roleAccessorSentinel implements all twenty-one roles at once. Nothing calls its
// methods; identity is the whole point.
type roleAccessorSentinel struct{}
@ -251,6 +263,12 @@ func (*roleAccessorSentinel) Delete(context.Context, issueops.DeleteRequest) (is
func (*roleAccessorSentinel) Sweep(context.Context, issueops.SweepRequest) (issueops.SweepResult, error) {
return issueops.SweepResult{}, nil
}
func (*roleAccessorSentinel) Bootstrap(context.Context, issueops.BootstrapRequest) (issueops.BootstrapResult, error) {
return issueops.BootstrapResult{}, nil
}
func (*roleAccessorSentinel) VerifyIdentity(context.Context, issueops.VerifyIdentityRequest) (issueops.VerifyIdentityResult, error) {
return issueops.VerifyIdentityResult{}, nil
}
func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
return issueops.AddCommentResult{}, nil
}
@ -281,15 +299,16 @@ func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDe
// ones four wave-2 slices each appended (bd-8ri3m is the same defect in the
// spec's own comments). Reads fire no completion hooks, so IssueReader,
// IssueRelations, Counter, StatsReporter, CycleDetector, EdgeReader,
// BlockingAnnotator, ReadyCounter and Querier deliberately return the inner
// surface unwrapped,
// each in its own hook_*.go. WorkspaceConfig and VersionReconciler do too, and
// those two are the ones that are NOT reads: a settings write changes the
// workspace rather than a bead and a version marker names no bead at all, so
// this decorator's issue-shaped hook vocabulary has nothing to hand a hook
// script (hook_workspace_config.go, hook_version_reconciler.go). This test pins
// every one of them as a decision rather than leaving it indistinguishable from
// the regression above.
// BlockingAnnotator, ReadyCounter, Querier and InitVerifier deliberately return
// the inner surface unwrapped, each in its own hook_*.go. The three in that
// column that are NOT reads are WorkspaceConfig, VersionReconciler and
// Bootstrapper: a settings write changes the workspace rather than a bead, a
// version marker names no bead at all, and a bootstrap makes a database into a
// workspace, so this decorator's issue-shaped hook vocabulary has nothing to
// hand a hook script (hook_workspace_config.go, hook_version_reconciler.go,
// hook_bootstrapper.go). Deleter is the fourth, for the reason its own row
// records. This test pins every one of them as a decision rather than leaving
// it indistinguishable from the regression above.
func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {
inner := newRoleAccessorStore()
store := NewHookFiringStore(inner, nil)
@ -317,15 +336,19 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T)
{"CycleDetector", func() (any, error) { return store.CycleDetector() }, inner.cycles, false},
{"ReadyCounter", func() (any, error) { return store.ReadyCounter() }, inner.readyCounter, false},
{"Querier", func() (any, error) { return store.Querier() }, inner.querier, false},
// The one WRITE role in the unwrapped column, and the reason is the
// hook vocabulary rather than the role: there is no on_delete hook to
// fire and a swept row is gone, so hook_sweeper.go recurses. Asserting
// it here is what keeps that a decision.
// The WRITE roles in the unwrapped column, and the reason is the hook
// vocabulary rather than the role. There is no on_delete hook to fire
// and a swept row is gone, so hook_sweeper.go recurses; a bootstrap
// names no bead and lands on a workspace whose hooks are not installed
// yet, so hook_bootstrapper.go does too. Asserting them here is what
// keeps those decisions.
{"Sweeper", func() (any, error) { return store.Sweeper() }, inner.sweeper, false},
// The other WRITE role in the unwrapped column, for the same reason:
// hook_deleter.go recurses because the hook vocabulary has no name for
// a deletion, not because the role reads.
{"Deleter", func() (any, error) { return store.Deleter() }, inner.deleter, false},
{"Bootstrapper", func() (any, error) { return store.Bootstrapper() }, inner.bootstrapper, false},
{"InitVerifier", func() (any, error) { return store.InitVerifier() }, inner.verifier, false},
} {
t.Run(test.name, func(t *testing.T) {
surface, err := test.got()
@ -375,6 +398,8 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) {
{"Querier", func() (any, error) { return store.Querier() }},
{"Sweeper", func() (any, error) { return store.Sweeper() }},
{"Deleter", func() (any, error) { return store.Deleter() }},
{"Bootstrapper", func() (any, error) { return store.Bootstrapper() }},
{"InitVerifier", func() (any, error) { return store.InitVerifier() }},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := test.got(); !errors.Is(err, want) {

View file

@ -31,6 +31,7 @@ var (
ErrCloseBlocked = issueops.ErrCloseBlocked
ErrCloseOpenChildren = issueops.ErrCloseOpenChildren
ErrAlreadyExists = issueops.ErrAlreadyExists
ErrAlreadyIdentified = issueops.ErrAlreadyIdentified
ErrVersionMismatch = issueops.ErrVersionMismatch
ErrStatusMismatch = issueops.ErrStatusMismatch
)
@ -258,6 +259,30 @@ type Storage interface {
// does: there is no on_delete hook to fire and the rows are gone. See
// hook_deleter.go.
Deleter() (issueops.Deleter, error)
// Bootstrapper returns the guarded identity-seeding surface for this store:
// the one-time write that turns a database bd can connect to into a
// workspace bd can use. It is the only slice of `bd init` that is a role at
// all — the rest of init CREATES the substrate, which an accessor on a
// store cannot do — and it is its own role rather than more keys on
// WorkspaceConfig because it REFUSES an already-identified substrate, which
// is a guard no settings write has anywhere to express.
//
// It is the second WRITE role whose hook decorator recurses unwrapped, and
// for the vocabulary reason Sweeper's does: a bootstrap names no issue, and
// on a workspace this new the hooks are not installed yet. See
// hook_bootstrapper.go.
Bootstrapper() (issueops.Bootstrapper, error)
// InitVerifier returns the guarded identity-read surface for this store: the
// prefix and project id `bd init` adopts, reconciles against, or refuses to
// invent. It is NOT Bootstrapper's read half, the way RecordedVersion is
// VersionReconciler's: bd reads this identity on paths where it is forbidden
// to write one — a bts-provisioned team database, a gateway whose credential
// may be read-only — and a caller that must not write must not be handed the
// writer.
//
// Reads fire no hooks, so the hook decorator's answer is its inner store's
// unchanged, as it is for IssueReader.
InitVerifier() (issueops.InitVerifier, error)
// Issue CRUD
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error

View file

@ -0,0 +1,84 @@
package uow
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/workapi"
publicops "github.com/steveyegge/beads/issueops"
)
// BootstrapperSource is the capability accessor a unit-of-work provider offers
// for identity seeding, the sibling of InitVerifierSource and
// VersionReconcilerSource.
type BootstrapperSource interface {
Bootstrapper() (publicops.Bootstrapper, error)
}
// bootstrapper seeds a substrate's identity through a unit of work.
type bootstrapper struct {
provider UnitOfWorkProvider
}
// Bootstrapper returns the identity-seeding surface for this provider.
func (p *doltSQLProvider) Bootstrapper() (publicops.Bootstrapper, error) {
return NewBootstrapper(p)
}
// NewBootstrapper constructs a public identity-seeding surface backed by
// provider.
func NewBootstrapper(provider UnitOfWorkProvider) (publicops.Bootstrapper, error) {
if isNilUnitOfWorkProvider(provider) {
return nil, fmt.Errorf("new bootstrapper: unit-of-work provider must not be nil")
}
return &bootstrapper{provider: provider}, nil
}
var _ publicops.Bootstrapper = (*bootstrapper)(nil)
// Bootstrap reads the identity, refuses over an identified substrate and
// writes the new one inside ONE unit of work.
//
// THE REFUSAL IS INSIDE THE TRANSACTION on purpose, and this is the backend
// where that matters most: it serves a workspace several clients share, so two
// inits can arrive at one database at the same moment, and a refusal decided
// from a read outside the transaction is one both of them pass.
//
// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED, for the reason
// workspaceConfig.SetSetting gives — a refused bootstrap should cost no
// connection and no transaction.
//
// ONE VERSION-CONTROL ENTRY, which is what the role's "at most one" permits.
// The identity lands on planes that travel, so this backend — the one whose
// unit of work labels its own commit — records the bootstrap as a single entry
// rather than as one per key.
//
// The per-clone bookkeeping `bd init` seeds alongside the identity is not here
// and not on the role; see issueops.Bootstrapper for why.
func (b *bootstrapper) Bootstrap(ctx context.Context, req publicops.BootstrapRequest) (publicops.BootstrapResult, error) {
req, err := workapi.ValidateBootstrapRequest(req)
if err != nil {
return publicops.BootstrapResult{}, err
}
return RunTxResult(ctx, b.provider, func(ctx context.Context, uw UnitOfWork) (publicops.BootstrapResult, string, error) {
cfg := uw.ConfigUseCase()
prefix, projectID, err := readWorkspaceIdentity(ctx, cfg)
if err != nil {
return publicops.BootstrapResult{}, "", err
}
if err := workapi.RefuseIdentifiedSubstrate(prefix, projectID); err != nil {
return publicops.BootstrapResult{}, "", err
}
if err := cfg.SetConfig(ctx, workapi.ConfigKeyIssuePrefix, req.Prefix); err != nil {
return publicops.BootstrapResult{}, "", err
}
if err := cfg.SetMetadata(ctx, workapi.MetadataKeyProjectID, req.ProjectID); err != nil {
return publicops.BootstrapResult{}, "", err
}
result := publicops.BootstrapResult{Prefix: req.Prefix, ProjectID: req.ProjectID}
return result, "bd: bootstrap " + req.Prefix, nil
})
}

View file

@ -0,0 +1,113 @@
package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/workapi"
)
// TestBootstrapperContract runs the Bootstrapper and InitVerifier contract
// against the unit-of-work provider — the one implementation that does not run
// internal/storage/issueops.BootstrapInTx, so this is the wiring where a
// genuine body divergence shows up. The two store backends share those bodies
// between them, which makes this the SECOND of two votes rather than the third.
//
// It is also the only wiring where "the identity is still there afterwards" is
// a question with a hard answer: this body reads, refuses and writes inside ONE
// transaction and every assertion reads back through a NEW one, so a write that
// never committed shows up here and nowhere else.
//
// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real
// Dolt sql-server) and NO t.Parallel: this backend has no per-test
// copy-on-write branch, so the config and metadata planes and dolt_log are
// database-global and a parallel subtest would corrupt another subtest's seeded
// identity and history delta.
func TestBootstrapperContract(t *testing.T) {
ctx := context.Background()
fixture := newUOWBootstrapperFixture(t, ctx)
t.Run("IdentifiesAFreshSubstrate", func(t *testing.T) {
conformance.RunBootstrapperIdentifiesAFreshSubstrate(t, ctx, fixture)
})
t.Run("StoresThePrefixWithoutItsTrailingHyphen", func(t *testing.T) {
conformance.RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen(t, ctx, fixture)
})
t.Run("RefusesAnIdentifiedSubstrate", func(t *testing.T) {
conformance.RunBootstrapperRefusesAnIdentifiedSubstrate(t, ctx, fixture)
})
t.Run("RefusesASubstrateCarryingOnlyAPrefix", func(t *testing.T) {
conformance.RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix(t, ctx, fixture)
})
t.Run("RefusesASubstrateCarryingOnlyAProjectID", func(t *testing.T) {
conformance.RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID(t, ctx, fixture)
})
t.Run("RefusesAnInvalidRequestWithoutWriting", func(t *testing.T) {
conformance.RunBootstrapperRefusesAnInvalidRequestWithoutWriting(t, ctx, fixture)
})
t.Run("LeavesTheSubstrateUntouchedWhenItCannotComplete", func(t *testing.T) {
conformance.RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete(t, ctx, fixture)
})
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
conformance.RunBootstrapperRecordsAtMostOneHistoryEntry(t, ctx, fixture)
})
t.Run("VerifierAnswersEmptyForAnUnidentifiedSubstrate", func(t *testing.T) {
conformance.RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate(t, ctx, fixture)
})
t.Run("VerifierReportsAPartialIdentityAsItStands", func(t *testing.T) {
conformance.RunInitVerifierReportsAPartialIdentityAsItStands(t, ctx, fixture)
})
t.Run("VerifierReportsAFailedReadAsAnError", func(t *testing.T) {
conformance.RunInitVerifierReportsAFailedReadAsAnError(t, ctx, fixture)
})
t.Run("VerifierWritesNothing", func(t *testing.T) {
conformance.RunInitVerifierWritesNothing(t, ctx, fixture)
})
}
func newUOWBootstrapperFixture(t *testing.T, ctx context.Context) conformance.BootstrapperFixture {
t.Helper()
provider := newUOWRoleFixtureProvider(t, ctx, "boot")
// Through the capability accessors, not NewBootstrapper/NewInitVerifier: a
// provider that stopped offering either role is the regression, and a
// constructor call would hide it. The two sources are asserted separately
// because they ARE separate — a caller that may only read must be able to
// hold one without the other.
bootstrapSource, ok := provider.(BootstrapperSource)
if !ok {
t.Fatalf("provider %T does not offer the Bootstrapper accessor", provider)
}
bootstrapper, err := bootstrapSource.Bootstrapper()
if err != nil {
t.Fatalf("Bootstrapper(): %v", err)
}
verifySource, ok := provider.(InitVerifierSource)
if !ok {
t.Fatalf("provider %T does not offer the InitVerifier accessor", provider)
}
verifier, err := verifySource.InitVerifier()
if err != nil {
t.Fatalf("InitVerifier(): %v", err)
}
kit := newUOWRoleFixtureKit(provider, "boot")
return conformance.BootstrapperFixture{
Bootstrapper: bootstrapper,
InitVerifier: verifier,
// Past both roles, through the seams their bodies write through, in
// their own committed transaction: the frozen kit can set a prefix but
// cannot unset one, and an unidentified substrate is the state a
// bootstrap needs to be reachable at all on a provisioned database.
SeedIdentity: func(ctx context.Context, prefix, projectID string) error {
return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) {
cfg := uw.ConfigUseCase()
if err := cfg.SetConfig(ctx, workapi.ConfigKeyIssuePrefix, prefix); err != nil {
return "", err
}
return "bd: seed workspace identity",
cfg.SetMetadata(ctx, workapi.MetadataKeyProjectID, projectID)
})
},
CountHistory: kit.CountHistory,
}
}

View file

@ -0,0 +1,70 @@
package uow
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/workapi"
publicops "github.com/steveyegge/beads/issueops"
)
// InitVerifierSource is the capability accessor a unit-of-work provider offers
// for the identity read, the sibling of BootstrapperSource.
//
// It is a SEPARATE source from BootstrapperSource for the reason the two roles
// are separate: the callers that only read — a bts-provisioned team database, an
// authenticating gateway with a read-only credential — must not be able to
// reach the write.
type InitVerifierSource interface {
InitVerifier() (publicops.InitVerifier, error)
}
// initVerifier reads the substrate's identity through a unit of work.
type initVerifier struct {
provider UnitOfWorkProvider
}
// InitVerifier returns the identity-read surface for this provider.
func (p *doltSQLProvider) InitVerifier() (publicops.InitVerifier, error) {
return NewInitVerifier(p)
}
// NewInitVerifier constructs a public identity-read surface backed by provider.
func NewInitVerifier(provider UnitOfWorkProvider) (publicops.InitVerifier, error) {
if isNilUnitOfWorkProvider(provider) {
return nil, fmt.Errorf("new init verifier: unit-of-work provider must not be nil")
}
return &initVerifier{provider: provider}, nil
}
var _ publicops.InitVerifier = (*initVerifier)(nil)
// VerifyIdentity reads both markers inside ONE read transaction, which is what
// makes the pair a snapshot rather than two reads a concurrent bootstrap can
// land between.
func (v *initVerifier) VerifyIdentity(ctx context.Context, _ publicops.VerifyIdentityRequest) (publicops.VerifyIdentityResult, error) {
return RunTxRead(ctx, v.provider, func(ctx context.Context, uw UnitOfWork) (publicops.VerifyIdentityResult, error) {
prefix, projectID, err := readWorkspaceIdentity(ctx, uw.ConfigUseCase())
if err != nil {
return publicops.VerifyIdentityResult{}, err
}
return publicops.VerifyIdentityResult{Prefix: prefix, ProjectID: projectID}, nil
})
}
// readWorkspaceIdentity reads the pair the bootstrap refusal and the verifier
// both ask about, so the two cannot come to disagree about what "identified"
// means on this backend. It is this package's twin of
// issueops.verifyIdentityInTx, which serves the two store backends.
func readWorkspaceIdentity(ctx context.Context, cfg domain.ConfigUseCase) (prefix, projectID string, err error) {
prefix, err = cfg.GetConfig(ctx, workapi.ConfigKeyIssuePrefix)
if err != nil {
return "", "", err
}
projectID, err = cfg.GetMetadata(ctx, workapi.MetadataKeyProjectID)
if err != nil {
return "", "", err
}
return prefix, projectID, nil
}

View file

@ -43,7 +43,6 @@ func (m *mockUnitOfWork) SwitchDatabase(ctx context.Context, database string) er
func (m *mockUnitOfWork) ConfigUseCase() domain.ConfigUseCase { return m.configUseCase }
func (m *mockUnitOfWork) DoltRemoteUseCase() domain.DoltRemoteUseCase { return nil }
func (m *mockUnitOfWork) BootstrapUseCase() domain.BootstrapUseCase { return nil }
func (m *mockUnitOfWork) IssueUseCase() domain.IssueUseCase { return m.issueUseCase }
func (m *mockUnitOfWork) DependencyUseCase() domain.DependencyUseCase { return m.dependencyUseCase }
func (m *mockUnitOfWork) LabelUseCase() domain.LabelUseCase { return m.labelUseCase }

View file

@ -15,7 +15,6 @@ type UnitOfWork interface {
ConfigUseCase() domain.ConfigUseCase
DoltRemoteUseCase() domain.DoltRemoteUseCase
BootstrapUseCase() domain.BootstrapUseCase
IssueUseCase() domain.IssueUseCase
DependencyUseCase() domain.DependencyUseCase
@ -40,9 +39,8 @@ func NewUOW(ctx context.Context, p TxProvider) (UnitOfWork, error) {
type baseUOW struct {
tx Tx
configUseCase domain.ConfigUseCase
remoteUseCase domain.DoltRemoteUseCase
bootstrapUseCase domain.BootstrapUseCase
configUseCase domain.ConfigUseCase
remoteUseCase domain.DoltRemoteUseCase
issueUseCase domain.IssueUseCase
dependencyUseCase domain.DependencyUseCase
@ -77,16 +75,6 @@ func (u *baseUOW) DoltRemoteUseCase() domain.DoltRemoteUseCase {
return u.remoteUseCase
}
func (u *baseUOW) BootstrapUseCase() domain.BootstrapUseCase {
if u.bootstrapUseCase == nil {
u.bootstrapUseCase = domain.NewBootstrapUseCase(
db.NewConfigSQLRepository(u.tx.Runner()),
u.DoltRemoteUseCase(),
)
}
return u.bootstrapUseCase
}
func (u *baseUOW) IssueUseCase() domain.IssueUseCase {
if u.issueUseCase == nil {
runner := u.tx.Runner()

View file

@ -0,0 +1,36 @@
package telemetry
import (
"context"
"github.com/steveyegge/beads/issueops"
)
// Bootstrapper returns the inner store's identity-seeding surface wrapped in
// this layer's instrumentation. It recurses instead of delegating: a blind
// delegation would return the inner surface unspanned and untimed.
func (s *InstrumentedStorage) Bootstrapper() (issueops.Bootstrapper, error) {
inner, err := s.Unwrap().Bootstrapper()
if err != nil {
return nil, err
}
return s.WrapBootstrapper(inner), nil
}
// WrapBootstrapper instruments guarded identity seeding with this storage
// layer's existing telemetry meter and tracer.
func (s *InstrumentedStorage) WrapBootstrapper(inner issueops.Bootstrapper) issueops.Bootstrapper {
return &instrumentedBootstrapper{storage: s, inner: inner}
}
type instrumentedBootstrapper struct {
storage *InstrumentedStorage
inner issueops.Bootstrapper
}
func (b *instrumentedBootstrapper) Bootstrap(ctx context.Context, request issueops.BootstrapRequest) (result issueops.BootstrapResult, err error) {
ctx, span, started := b.storage.op(ctx, "Bootstrapper.Bootstrap")
result, err = b.inner.Bootstrap(ctx, request)
b.storage.done(ctx, span, started, err)
return result, err
}

View file

@ -0,0 +1,36 @@
package telemetry
import (
"context"
"github.com/steveyegge/beads/issueops"
)
// InitVerifier returns the inner store's identity-read surface wrapped in this
// layer's instrumentation. There is no read/write distinction here — telemetry
// spans reads too.
func (s *InstrumentedStorage) InitVerifier() (issueops.InitVerifier, error) {
inner, err := s.Unwrap().InitVerifier()
if err != nil {
return nil, err
}
return s.WrapInitVerifier(inner), nil
}
// WrapInitVerifier instruments guarded identity reads with this storage layer's
// existing telemetry meter and tracer.
func (s *InstrumentedStorage) WrapInitVerifier(inner issueops.InitVerifier) issueops.InitVerifier {
return &instrumentedInitVerifier{storage: s, inner: inner}
}
type instrumentedInitVerifier struct {
storage *InstrumentedStorage
inner issueops.InitVerifier
}
func (v *instrumentedInitVerifier) VerifyIdentity(ctx context.Context, request issueops.VerifyIdentityRequest) (result issueops.VerifyIdentityResult, err error) {
ctx, span, started := v.storage.op(ctx, "InitVerifier.VerifyIdentity")
result, err = v.inner.VerifyIdentity(ctx, request)
v.storage.done(ctx, span, started, err)
return result, err
}

View file

@ -12,7 +12,7 @@ import (
"github.com/steveyegge/beads/issueops"
)
// roleAccessorNames is the eighteen-strong capability surface every storage
// roleAccessorNames is the twenty-one-strong capability surface every storage
// decorator has to answer for. It is duplicated from the sibling test in
// internal/storage rather than shared because that package cannot import this
// one and this one's test helpers cannot be exported back.
@ -31,6 +31,8 @@ var roleAccessorNames = []string{
"Querier",
"Sweeper",
"Deleter",
"Bootstrapper",
"InitVerifier",
"Commenter",
"ReadyClaimer",
"BatchCloser",
@ -62,7 +64,7 @@ func TestInstrumentedStorageDeclaresEveryRoleAccessor(t *testing.T) {
}
}
// roleAccessorStore is a DoltStorage whose only real methods are the eighteen
// roleAccessorStore is a DoltStorage whose only real methods are the twenty-one
// role accessors, each answering with a distinguishable sentinel so a test can tell
// an instrumented surface from a passed-through one.
type roleAccessorStore struct {
@ -103,6 +105,12 @@ func (s *roleAccessorStore) Sweeper() (issueops.Sweeper, error) {
func (s *roleAccessorStore) Deleter() (issueops.Deleter, error) {
return s.surface, s.err
}
func (s *roleAccessorStore) Bootstrapper() (issueops.Bootstrapper, error) {
return s.surface, s.err
}
func (s *roleAccessorStore) InitVerifier() (issueops.InitVerifier, error) {
return s.surface, s.err
}
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
return s.surface, s.err
}
@ -114,7 +122,7 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error
return s.surface, s.err
}
// roleAccessorSentinel implements all eighteen roles at once. Nothing calls its
// roleAccessorSentinel implements all twenty-one roles at once. Nothing calls its
// methods; identity is the whole point.
type roleAccessorSentinel struct{}
@ -198,6 +206,12 @@ func (*roleAccessorSentinel) Delete(context.Context, issueops.DeleteRequest) (is
func (*roleAccessorSentinel) Sweep(context.Context, issueops.SweepRequest) (issueops.SweepResult, error) {
return issueops.SweepResult{}, nil
}
func (*roleAccessorSentinel) Bootstrap(context.Context, issueops.BootstrapRequest) (issueops.BootstrapResult, error) {
return issueops.BootstrapResult{}, nil
}
func (*roleAccessorSentinel) VerifyIdentity(context.Context, issueops.VerifyIdentityRequest) (issueops.VerifyIdentityResult, error) {
return issueops.VerifyIdentityResult{}, nil
}
func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
return issueops.AddCommentResult{}, nil
}
@ -253,6 +267,8 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
{"Querier", func() (any, error) { return wrapped.Querier() }},
{"Sweeper", func() (any, error) { return wrapped.Sweeper() }},
{"Deleter", func() (any, error) { return wrapped.Deleter() }},
{"Bootstrapper", func() (any, error) { return wrapped.Bootstrapper() }},
{"InitVerifier", func() (any, error) { return wrapped.InitVerifier() }},
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},
@ -300,6 +316,8 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) {
{"Querier", func() (any, error) { return wrapped.Querier() }},
{"Sweeper", func() (any, error) { return wrapped.Sweeper() }},
{"Deleter", func() (any, error) { return wrapped.Deleter() }},
{"Bootstrapper", func() (any, error) { return wrapped.Bootstrapper() }},
{"InitVerifier", func() (any, error) { return wrapped.InitVerifier() }},
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},

View file

@ -0,0 +1,90 @@
package workapi
import (
"fmt"
"strings"
"github.com/steveyegge/beads/issueops"
)
// This file holds the shared, database-free half of issueops.Bootstrapper and
// issueops.InitVerifier: the keys the identity lives under, the request
// validation, and the normalization that makes the prefix a bootstrap stores
// the same string on every backend. It is a pure file for the reason
// PlanVersionReconcile is one — three implementations decide through it, so the
// answer cannot differ by backend, and the refusals are pinned in milliseconds
// without a database.
// The two keys a workspace's IDENTITY lives under.
//
// They are named here rather than spelled at each call site because three
// implementations, two front doors and three conformance wirings read and write
// them, and a key spelled differently in one of those places is an identity
// nothing else can find — which looks exactly like a database nobody ever
// initialized.
//
// These two and no others decide whether a substrate is bootstrapped at all,
// and either one of them present is what Bootstrapper.Bootstrap refuses over.
// The per-clone bookkeeping `bd init` also seeds — the fingerprints, the
// synced-at marker, the recorded binary version — is not identity and is not
// named here; see issueops.Bootstrapper for why it is not on the role either.
const (
// ConfigKeyIssuePrefix lives on the durable settings plane, which is where
// every other reader of the prefix already looks for it.
ConfigKeyIssuePrefix = "issue_prefix"
// MetadataKeyProjectID is the identity cross-project verification compares
// on connection. The leading underscore is historical and load-bearing:
// it is the spelling every existing workspace already carries.
MetadataKeyProjectID = "_project_id"
)
// NormalizeBootstrapPrefix returns the prefix as a bootstrap STORES it.
//
// The settings plane strips a trailing hyphen from this key and has since long
// before these roles existed. Doing it here instead of relying on that means
// BootstrapResult.Prefix, the value a later VerifyIdentity answers with and the
// string the front door goes on to print are one value on every backend,
// including the unit-of-work one whose write does not pass through that plane's
// normalizer at all.
func NormalizeBootstrapPrefix(prefix string) string {
return strings.TrimRight(prefix, "-")
}
// ValidateBootstrapRequest refuses a bootstrap that cannot produce a usable
// workspace and returns the request as it will be WRITTEN.
//
// Every implementation validates through it BEFORE opening a transaction, so a
// refused bootstrap costs no database work — which is what makes
// issueops.Bootstrapper's "a refusal writes nothing" true of the connection as
// well as of the keys.
//
// Both fields are required, and for the same underlying reason stated two ways
// on the request: a substrate carrying one of them and not the other is exactly
// the half-identified state the refusal below cannot tell from a deliberately
// half-provisioned database.
func ValidateBootstrapRequest(req issueops.BootstrapRequest) (issueops.BootstrapRequest, error) {
req.Prefix = NormalizeBootstrapPrefix(req.Prefix)
if req.Prefix == "" {
return issueops.BootstrapRequest{}, fmt.Errorf("%w: bootstrap requires a non-empty issue prefix", issueops.ErrValidation)
}
if req.ProjectID == "" {
return issueops.BootstrapRequest{}, fmt.Errorf("%w: bootstrap requires a project id; this role does not mint one", issueops.ErrValidation)
}
return req, nil
}
// RefuseIdentifiedSubstrate turns the pair a bootstrap read into the refusal
// issueops.Bootstrapper promises, or nil when the substrate is free.
//
// EITHER MARKER IS ENOUGH. A substrate several rigs share carries a prefix one
// of them chose, and a bootstrap that overwrote it would rename every id the
// others are about to mint; a substrate carrying only a project id is either a
// server-provisioned one bd must adopt rather than stamp, or a bootstrap that
// failed partway, and bd cannot tell those apart. The error carries both values
// so its caller can.
func RefuseIdentifiedSubstrate(prefix, projectID string) error {
if prefix == "" && projectID == "" {
return nil
}
return &issueops.AlreadyIdentifiedError{Prefix: prefix, ProjectID: projectID}
}

View file

@ -0,0 +1,87 @@
package workapi
import (
"errors"
"testing"
"github.com/steveyegge/beads/issueops"
)
// The refusals and the normalization are pinned here, without a database,
// because they are the same on every backend by construction: all three
// implementations validate through ValidateBootstrapRequest and decide the
// refusal through RefuseIdentifiedSubstrate. The conformance contract is left
// to assert what only a real backend can show — that a refusal wrote nothing,
// that the identity is there for the next caller, that the two reads are one
// snapshot.
func validBootstrapRequest() issueops.BootstrapRequest {
return issueops.BootstrapRequest{
Prefix: "acme",
ProjectID: "11111111-2222-3333-4444-555555555555",
}
}
func TestValidateBootstrapRequestRefusesEachRequiredField(t *testing.T) {
for _, test := range []struct {
name string
spoil func(*issueops.BootstrapRequest)
}{
{"no prefix", func(r *issueops.BootstrapRequest) { r.Prefix = "" }},
// A prefix that is nothing but the hyphen the plane strips is the
// interesting empty: it arrives non-empty and normalizes to nothing.
{"prefix of hyphens", func(r *issueops.BootstrapRequest) { r.Prefix = "---" }},
{"no project id", func(r *issueops.BootstrapRequest) { r.ProjectID = "" }},
} {
t.Run(test.name, func(t *testing.T) {
req := validBootstrapRequest()
test.spoil(&req)
if _, err := ValidateBootstrapRequest(req); !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("ValidateBootstrapRequest() error = %v, want ErrValidation", err)
}
})
}
}
func TestValidateBootstrapRequestNormalizesOnlyTheTrailingHyphen(t *testing.T) {
req := validBootstrapRequest()
req.Prefix = "my-proj--"
got, err := ValidateBootstrapRequest(req)
if err != nil {
t.Fatalf("ValidateBootstrapRequest(): %v", err)
}
// Interior hyphens survive; only the trailing run goes, which is exactly
// what the settings plane has always done to this key.
if got.Prefix != "my-proj" {
t.Fatalf("normalized prefix = %q, want %q", got.Prefix, "my-proj")
}
if got.ProjectID != req.ProjectID {
t.Fatalf("ValidateBootstrapRequest() changed a field it does not own: %+v", got)
}
}
func TestRefuseIdentifiedSubstrate(t *testing.T) {
if err := RefuseIdentifiedSubstrate("", ""); err != nil {
t.Fatalf("RefuseIdentifiedSubstrate(\"\", \"\") = %v, want nil for a substrate with no identity", err)
}
// EITHER marker refuses, including the half-identified states a bootstrap
// that failed partway leaves on a backend with no transaction to roll back.
for _, test := range []struct{ prefix, projectID string }{
{"acme", "proj-1"},
{"acme", ""},
{"", "proj-1"},
} {
err := RefuseIdentifiedSubstrate(test.prefix, test.projectID)
if !errors.Is(err, issueops.ErrAlreadyIdentified) {
t.Fatalf("RefuseIdentifiedSubstrate(%q, %q) = %v, want ErrAlreadyIdentified", test.prefix, test.projectID, err)
}
var refusal *issueops.AlreadyIdentifiedError
if !errors.As(err, &refusal) {
t.Fatalf("RefuseIdentifiedSubstrate(%q, %q) error is not *AlreadyIdentifiedError", test.prefix, test.projectID)
}
if refusal.Prefix != test.prefix || refusal.ProjectID != test.projectID {
t.Fatalf("refusal = %+v, want it to name what was found (%q, %q)", refusal, test.prefix, test.projectID)
}
}
}

View file

@ -267,6 +267,73 @@ func TestVersionReconcilerKeepsTelemetryOutermost(t *testing.T) {
}
}
// TestBootstrapperKeepsTelemetryOutermost is the identity-seeding role's
// version of the pin, and the third place in this file where the READ answer is
// given for a role that WRITES.
//
// The reason is neither the settings role's nor the version marker's. A
// bootstrap writes, and loudly — it is what turns a database into a workspace —
// but this decorator's hook vocabulary is issue-shaped and a bootstrap names no
// issue; and on a workspace this new, `bd init` has not installed .beads/hooks/
// yet, so a hook fired here would run whatever the previous project in that
// directory left behind. See internal/storage/hook_bootstrapper.go.
func TestBootstrapperKeepsTelemetryOutermost(t *testing.T) {
t.Setenv("BD_OTEL_STDOUT", "true")
instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage)
if !ok {
t.Fatal("WrapStorage() did not create InstrumentedStorage")
}
bootstrapper, err := storage.NewHookFiringStore(instrumented, nil).Bootstrapper()
if err != nil {
t.Fatalf("Bootstrapper() error = %v", err)
}
if got := reflect.TypeOf(bootstrapper).String(); got != "*telemetry.instrumentedBootstrapper" {
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
}
}
// TestInitVerifierKeepsTelemetryOutermost is the ordinary read-role pin: reads
// fire no hooks, so the hook decorator recurses and the telemetry wrapper is
// what a caller holds.
func TestInitVerifierKeepsTelemetryOutermost(t *testing.T) {
t.Setenv("BD_OTEL_STDOUT", "true")
instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage)
if !ok {
t.Fatal("WrapStorage() did not create InstrumentedStorage")
}
verifier, err := storage.NewHookFiringStore(instrumented, nil).InitVerifier()
if err != nil {
t.Fatalf("InitVerifier() error = %v", err)
}
if got := reflect.TypeOf(verifier).String(); got != "*telemetry.instrumentedInitVerifier" {
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
}
}
func TestBootstrapperExposesTypedUnsupportedError(t *testing.T) {
bootstrapper, err := (*dolt.DoltStore)(nil).Bootstrapper()
if bootstrapper != nil {
t.Fatalf("Bootstrapper() bootstrapper = %T, want nil", bootstrapper)
}
var unsupported *beads.ErrUnsupported
if !errors.As(err, &unsupported) {
t.Fatalf("Bootstrapper() error = %v, want *beads.ErrUnsupported", err)
}
}
func TestInitVerifierExposesTypedUnsupportedError(t *testing.T) {
verifier, err := (*dolt.DoltStore)(nil).InitVerifier()
if verifier != nil {
t.Fatalf("InitVerifier() verifier = %T, want nil", verifier)
}
var unsupported *beads.ErrUnsupported
if !errors.As(err, &unsupported) {
t.Fatalf("InitVerifier() error = %v, want *beads.ErrUnsupported", err)
}
}
func TestVersionReconcilerExposesTypedUnsupportedError(t *testing.T) {
reconciler, err := (*dolt.DoltStore)(nil).VersionReconciler()
if reconciler != nil {

141
issueops/bootstrapper.go Normal file
View file

@ -0,0 +1,141 @@
package issueops
import "context"
// BootstrapRequest asks an UNIDENTIFIED substrate to record the identity every
// later open verifies against.
//
// THE REQUEST CARRIES THE IDENTITY RATHER THAN MINTING IT. Choosing a prefix
// from a directory name, generating a project UUID and deciding whether to adopt
// an identity another rig already chose are all decisions made where the
// workspace is — a working directory, a git remote, a metadata.json — and none
// of them is reachable from a substrate. What is reachable from a substrate is
// the write, the refusal that guards it and the read that observes both, which
// is the whole of what this role and InitVerifier are.
type BootstrapRequest struct {
// Prefix is the workspace's issue prefix, the string every id this
// workspace mints begins with. It is REQUIRED: "" is ErrValidation, because
// a substrate with no prefix cannot name an issue and every later open
// reports it as uninitialized.
//
// A TRAILING HYPHEN IS STRIPPED, and nothing else about the value is
// touched. The settings plane has always normalized this key that way, so
// stating it here is what makes Result.Prefix — and the answer a later
// VerifyIdentity gives — the same string on every backend rather than
// whichever one that plane happened to store.
Prefix string
// ProjectID is the workspace's project identity, the value cross-project
// verification compares on every connection to catch a workspace opened
// against another project's database. It is REQUIRED: "" is ErrValidation.
//
// This role does not generate one. A caller that has no identity to record
// yet mints it (configfile.GenerateProjectID); a caller adopting a
// substrate another rig or a provisioning server already identified must
// not be here at all — that is InitVerifier's question, and asking this one
// is the refusal below.
ProjectID string
}
// BootstrapResult reports the identity the substrate now carries.
//
// It echoes rather than adds, deliberately. There is no "created" flag: this
// role writes or refuses, so a nil error IS the flag, and a second statement of
// it is a second thing to keep true.
type BootstrapResult struct {
// Prefix is the prefix as STORED, which is the request's with any trailing
// hyphen removed. A caller that goes on to print the prefix, or to build
// ids with it, uses this rather than what it sent.
Prefix string
// ProjectID is the identity as stored, byte for byte what was requested.
ProjectID string
}
// Bootstrapper describes SEEDING A SUBSTRATE'S IDENTITY: the one-time write
// that turns a database bd can connect to into a workspace bd can use.
//
// WHY ONLY THIS SLICE OF `bd init` IS A ROLE. Everything else init does —
// creating .beads/, writing metadata.json and config.yaml, initializing a git
// repository, installing hooks, rendering agent instructions, starting a Dolt
// server — CREATES the substrate or the workspace around it. A role is reached
// through an accessor ON a store, so it cannot be what makes the store exist;
// and fs/git provisioning has exactly one implementation, so a three-backend
// conformance contract over it would be three names for one body. What is left
// once those are taken out is the part that happens INSIDE the database and
// that all three backends must agree about, and that part is the identity.
//
// THE VERSION-CONTROL REMOTE IS NOT IDENTITY and is not here, even though one
// of the two front doors used to write it in the same call. A remote is where
// this database syncs to; the identity is what this database IS. They have
// different lifetimes, different failure modes and different permissions, and
// putting them in one call is what let a remote that could not be created fail
// a bootstrap that had already succeeded.
//
// A BOOTSTRAP OVER AN ALREADY-IDENTIFIED SUBSTRATE IS REFUSED. See Bootstrap.
//
// There is NO HTTP SURFACE, and that is a decision rather than an omission —
// the same shape VersionReconciler's is, for a different reason. A server can
// only serve a database it is already bound to, and binding it required the
// identity this role writes; so the one caller that could reach such an
// endpoint would be asking a running server to identify a workspace that is by
// construction already identified, which is precisely the refusal below.
// Bootstrapping over an unauthenticated surface is also a different risk class
// from reading one: `bd serve`'s document is reads plus a claim plus one
// destructive sweep, and an operation that stamps a shared database's identity
// belongs to whatever provisions the database, not to a request. The identity a
// remote caller can act on is already published — ContextResponse.project_id on
// GET /v0/beads/context is InitVerifier's answer, on the wire, today.
//
// Deterministic request-validation failures match ErrValidation; result values
// are unspecified when error is non-nil.
type Bootstrapper interface {
// Bootstrap records the request's identity on a substrate that has none.
//
// AN ALREADY-IDENTIFIED SUBSTRATE IS REFUSED, with ErrAlreadyIdentified
// carried by an *AlreadyIdentifiedError naming what was found. "Already
// identified" means EITHER marker is present — a prefix, a project id, or
// both — and the reason it is either rather than both is that a substrate
// several rigs share carries a prefix one of them chose, and overwriting it
// renames every id the others are about to mint. A partial identity is
// refused for the same reason it is reported: bd cannot tell a half-written
// bootstrap from a deliberately half-provisioned database, and guessing
// wrong destroys the one it did not mean.
//
// THE REFUSAL WRITES NOTHING, and on every backend it is decided from the
// same read the write would have followed, in one transaction where the
// substrate has transactions. Re-identifying a workspace is therefore an
// explicit operation somebody has to ask for, rather than something that
// happens because init ran twice.
//
// IT WRITES THE IDENTITY AND NOTHING ELSE — the prefix and the project id,
// the same two markers the refusal reads and VerifyIdentity answers with.
//
// The per-clone bookkeeping `bd init` also seeds is deliberately NOT here.
// The repository and clone fingerprints, the synced-at marker and the
// recorded binary version are rewritten on EVERY init, adopt or not — a
// fresh clone of an already-identified database needs its own fingerprints
// precisely because it bootstrapped nothing — so folding them into a
// one-time, refusable write would mean either a refusal that skips them or
// a write that is no longer one-time. The recorded version has a second
// reason: it is VersionReconciler's key, and two roles writing one key is
// the accretion the governing rule exists to prevent.
//
// A LATER VerifyIdentity IS THE PROMISE. After a successful Bootstrap it
// answers with this result's Prefix and ProjectID, from a fresh connection
// or a fresh unit of work. That is what "bootstrapped" means here, and it
// is why the read is InitVerifier's rather than a second method: the two
// are asked by different callers with different permissions, and the caller
// that may only read must not be handed the writer.
//
// THE TWO MARKERS LAND IN ONE TRANSACTION on every backend, because every
// backend's body takes one — which is also what makes the refusal a refusal
// rather than a suggestion two racing inits both pass. This role therefore
// never leaves a HALF-identified substrate behind; it only FINDS one,
// written by something older or by a hand, and the refusal names what it
// found so its caller can tell that apart from a re-init.
//
// AT MOST ONE VERSION-CONTROL ENTRY is recorded, and a backend that records
// none is conforming. The two markers live on planes that travel, so a
// bootstrap is history-worthy where a backend commits at all; what the role
// forbids is one entry per key.
Bootstrap(ctx context.Context, req BootstrapRequest) (BootstrapResult, error)
}

View file

@ -111,6 +111,44 @@ func (e *CloseOpenChildrenError) Unwrap() error {
// already occupied. The issue and wisp tables share one ID space.
var ErrAlreadyExists = errors.New("issue already exists")
// ErrAlreadyIdentified is returned by Bootstrapper.Bootstrap when the substrate
// already carries a workspace identity. It is its own sentinel rather than
// ErrAlreadyExists because that one is about an occupied ISSUE ID in a shared
// id space, and a caller that classifies the two together would answer a
// re-init with advice about `bd update`.
var ErrAlreadyIdentified = errors.New("workspace already identified")
// AlreadyIdentifiedError reports the identity a substrate was found carrying
// when a bootstrap was refused, read inside the same transaction that would
// have written over it.
//
// It carries the pair rather than formatting it away because the two things a
// caller does next both need the values: adopting the identity needs them, and
// telling a COMPLETE identity apart from a half-written one — the state a
// bootstrap that failed partway leaves on a substrate with no transactions —
// means looking at which of the two is empty.
type AlreadyIdentifiedError struct {
// Prefix is the issue prefix found, or "" when the substrate carried none.
Prefix string
// ProjectID is the project identity found, or "" when the substrate
// carried none.
ProjectID string
}
func (e *AlreadyIdentifiedError) Error() string {
switch {
case e.Prefix != "" && e.ProjectID != "":
return fmt.Sprintf("workspace already identified as prefix %q, project %s", e.Prefix, e.ProjectID)
case e.Prefix != "":
return fmt.Sprintf("workspace already identified as prefix %q with no project id", e.Prefix)
default:
return fmt.Sprintf("workspace already identified as project %s with no issue prefix", e.ProjectID)
}
}
// Unwrap makes AlreadyIdentifiedError match ErrAlreadyIdentified.
func (e *AlreadyIdentifiedError) Unwrap() error { return ErrAlreadyIdentified }
// 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

75
issueops/initverifier.go Normal file
View file

@ -0,0 +1,75 @@
package issueops
import "context"
// VerifyIdentityRequest asks what identity a substrate carries. It has no
// fields today and is spelled as a type so that gaining one is an additive
// change to something callers already name — the reason
// RecordedVersionRequest and ListSettingsRequest are spelled the same way.
type VerifyIdentityRequest struct{}
// VerifyIdentityResult is the identity the substrate carries, as it stands.
//
// BOTH FIELDS ARE "" WHEN ABSENT, and "" IS A NORMAL ANSWER rather than an
// error or a missing row to classify. A substrate nothing has bootstrapped
// answers with two empty strings, and that is the answer a caller deciding
// whether to bootstrap needs; turning it into ErrNotFound would make the
// ordinary case look like a failure and force every caller to unwrap it back
// into the same two strings.
type VerifyIdentityResult struct {
// Prefix is the substrate's issue prefix, or "" when it carries none.
Prefix string
// ProjectID is the substrate's project identity, or "" when it carries
// none.
//
// THE TWO ARE READ AS ONE SNAPSHOT wherever the substrate publishes a
// transaction, so a caller never sees a prefix from before a bootstrap
// beside a project id from after one. That matters because the pair is what
// a caller compares against a local metadata.json, and a torn read there
// looks exactly like the cross-project mismatch the comparison exists to
// find.
ProjectID string
}
// InitVerifier describes READING A SUBSTRATE'S IDENTITY: the prefix and project
// id `bd init` reconciles against, adopts, or refuses to invent.
//
// IT IS A SEPARATE ROLE FROM Bootstrapper, AND NOT ITS READ HALF. The
// precedent that would have made them one — VersionReconciler, whose read and
// write are two shapes of one question — does not reach here, because the
// callers are different and so are their PERMISSIONS. bd reads this identity on
// paths where it is forbidden to write one: against a bts-provisioned team
// database, whose identity the provisioning tool owns and bd adopts; against an
// authenticating gateway, whose credential may be read-only and whose
// server-side identity a client must never overwrite. Handing those callers a
// surface with a write on it is exactly the shape that produced the writes they
// now have to suppress flag by flag. A capability a caller must not have is a
// capability it should not be able to reach.
//
// THE ONE PROMISE EVERYTHING ELSE HERE IS FOR: an ABSENT identity and an
// UNREADABLE one are different answers. Absent is "" with a nil error;
// unreadable is an error. Nothing in this role ever reports a failed read as an
// empty answer, because every caller then decides the same thing from it — an
// unprovisioned database gets bootstrapped or refused as a provisioning-contract
// violation, and a database that merely could not be reached must get neither.
// A flaky connection misread as an empty database is how a workspace acquires a
// second identity.
//
// IT WRITES NOTHING. Not the keys it reads, not a marker that it ran, and no
// version-control entry. A verifier that repaired what it found would be the
// bootstrap this role exists to keep separate.
//
// There is NO HTTP surface, for the reason recorded on Bootstrapper: the
// identity a remote caller can act on is already published as
// ContextResponse.project_id on GET /v0/beads/context, and a second spelling of
// one fact is a second thing to keep true.
//
// Deterministic request-validation failures match ErrValidation; result values
// are unspecified when error is non-nil.
type InitVerifier interface {
// VerifyIdentity returns the substrate's identity as it stands.
//
// It answers "" for each marker the substrate does not carry, reports a
// read failure as an ERROR rather than as absence, and writes nothing.
VerifyIdentity(ctx context.Context, req VerifyIdentityRequest) (VerifyIdentityResult, error)
}