* test(conformance): author R7.1 as-of-read conformance contract Adds a new Phase 0 conformance contract for R7.1 (as-of reads, gastownhall/beads#6136, design doc #5898 rev 9) -- no fixture existed for this anywhere in backend/conformance/, so this is authored from scratch, not un-skipped. AsOfReadFixture supplies three hooks: Resolve (the read under test), MintAt (seeds a version at a controlled accept-time), and MakeUnanswerable (arranges a Gone/Unknown refusal independently of RetentionFixture/EpochFixture's own removal machinery, since R7.1's refusal is a sibling contract to R17/R20, not a dependent of them). Five Run* functions cover the bead's five required-coverage points verbatim: - selector accepts either an instant or a version address, and both name the same answer when they resolve to the same version; - resolution returns the latest version at-or-before T, with a version accepted after T strictly excluded even when close by; - a served result reports the exact address it served; - an unanswerable read refuses as a typed Gone*/Unknown outcome with a reason, and never substitutes a neighboring version, the nearest surviving version, or current state -- asserted directly by requiring Address == "" on every refusal; - local completeness only (TC3): a lineage minted into one of two stores resolves there and refuses Unknown (FR-06) on the store that never received it, asserting nothing about agreement between the two. The file's doc comment states the Memory-plane-consumer-policy non-goal explicitly (closed-before-T boundary, sibling exclusion, supersession exclusion are consumer policy per #5877, not part of this primitive) so the gap reads as deliberate scope, not an oversight. Wired onto all three storage legs (dolt, embeddeddolt, uow) with unconditional "not implemented" stubs rather than partial-real hooks, so every case fails via MintAt on its first fixture call -- deterministic RED with no risk of an accidental pass, per the precedent set by be-x5jqd.1. Sentinel error messages reference be-x5jqd.5, the implementation child this suite is written ahead of. TestEveryLegWiresEveryRoleContract requires zero waivers: all 5 new entrypoints are fully wired (not nil) on all three legs. Branch cut from the rebased be-2h167 head (5fdfb92fe5). Verified via go build ./..., go vet ./..., gofmt -l, and go test -tags cgo across all three legs: all 5 new subtests (8 counting the 4-way Gone/Unknown table) FAIL for the documented reason, TestEveryLegWiresEveryRoleContract passes cleanly on all three legs, and TestVersionedHistoryPhase0RunsInFullSkipMode is unaffected. Bead: be-x5jqd.2 * fix(history): refuse metadata integers binary64 cannot hold exactly (refs be-wdlod, #6358 follow-up) canonicalDurableState canonicalizes numbers per RFC 8785 (JCS), which renders every number as an IEEE-754 binary64 double regardless of magnitude. An integer-valued metadata literal past 2^53-1 therefore rounds to a DIFFERENT VALUE on the way into durable_state -- not a formatting change, a value change -- which can collapse two distinct issue states onto one durable_state and therefore one content token. refuseUnrepresentableIntegers is the fix: an admission gate, one layer above the JCS step, that parses each JSON number literal exactly with math/big (never float64 -- float64 rounding is the exact thing being guarded against) and refuses whenever the literal's VALUE, not its spelling, is an integer whose magnitude exceeds 2^53-1. Value-not-form matters because the first cut of this gate skipped any literal containing '.', 'e', or 'E' outright, reasoning that non-integer forms round-trip losslessly -- true for genuinely fractional literals, but not for an integer VALUE spelled in decimal or exponential form: QA found that 9007199254740993.0 and 9.007199254740993e15 walked straight past that first gate and canonicalized to the same colliding target as the bare literal. The predicate now inspects the value via big.Rat.SetString/.IsInt, so all three spellings are refused alike. 1e300 is refused too, no notation carve-out: it denotes the integer 10^300, and binary64 spacing near that magnitude is roughly 2^248 -- vastly wider than the collision window at the 2^53 boundary this gate exists to close. Admitting that spelling while refusing 9007199254740993 would be the same defect with a bigger window (mayor's ruling, citing this collision-window argument as decisive). Non-integer values stay admissible past the bound (1.5e300 is fine): ES6 shortest-round-trip formatting is a bijection on doubles, so two non-integer literals collide only if they already denoted the same double before this gate ever ran, and a fractional literal never carried a promise of exact decimal storage the way an integer -- an id, a count, a timestamp -- carries a promise of exactness that silent rounding would corrupt. jcsCanonicalize is canonicalDurableState's RFC 8785 step pulled out on its own, below the gate rather than behind it, because refusing 1e300 puts the admission policy at odds with one of this store's own spec- conformance fixtures: testdata/jcs/input/values.json, one of the 10 official RFC 8785 vectors shipped verbatim from the spec's reference suite (not authored here), itself contains 1E30. RFC 8785 conformance is a claim about the canonicalizer, not about this store's admission policy, so TestCanonicalDurableStateIsJCS now runs all 10 shipped vectors -- values.json included, still asserting 1E30 folds to 1e+30 per spec -- through the ungated jcsCanonicalize, while its two local ad hoc cases keep exercising the full gated canonicalDurableState, since neither conflicts and both are more faithful to production traffic that way. The gate's own refusal of that magnitude is pinned separately, on its own terms, in version_history_integer_admission_test.go. Severity is MINOR, not MAJOR: Dolt's JSON column type already renormalizes metadata to float64 on every read regardless of this gate (measured on dolt 2.2.3: 9007199254740993 reads back as 9007199254740992, 1e300 as 1e+300), which converges two distinct in-memory states to one stored state before any version row is minted. The collision this gate closes is therefore unreachable through normal bd update traffic on this backend; it stays real for off-path writes -- bd sql, a hand-written JSONL import, or a TEXT-column backend -- which is why this landed as a follow-up rather than gating Phase 2 itself. Verified clean: a full module compile; static analysis over the storage tree; the complete issueops package suite (260 subtests); the schema package suite; and the broader storage tree, apart from one dolt-package test that fails identically against the pre-this-diff baseline (a Dolt server port collision with a concurrent session's process on this host) -- confirmed pre-existing and environmental, not caused by this change. * feat(issueops): implement R7.1 as-of read's store-layer primitive (be-x5jqd.5) Turns backend/conformance/versioned_read_contract.go (authored RED in 6aefdce60, gastownhall/beads#5898 rev 9, #6136) towards GREEN. This commit lands the shared production seam; wiring the three per-leg fixtures (dolt, embeddeddolt, uow) onto it is a follow-up commit. asof_read.go (new): AsOfReadInTx resolves an AsOfSelector (an instant or a previously-served version address) to one issue_versions row -- the latest version accepted at or before T, everything later strictly excluded -- and reports either its state and address, or a typed refusal (gone-retention/gone-erasure/gone-reorganization/unknown) with a reason. storeID is accepted only for signature parity with the fixture hook shape (Design D: the conformance suite's own ad hoc dispatch string selects among per-leg isolated test stores; issue_versions carries no store_id column, matching CurrentEpochInTx's precedent). AsOfRestriction is string-backed, unlike R20's int-backed EpochRestriction, because it round-trips directly through the new removed_restriction column with a plain cast. Migration 0069 adds issue_versions.removed_restriction VARCHAR(30), nullable (NULL = live, never a stored value). Sits alongside removed_at/ removed_reason (migration 0067, virgin until this slice); AsOfReadInTx only READS all three -- a future R17 is the real writer via hold/remove/ erase primitives, no collision. Guarded PREPARE + CLI direct-DDL override + schema_test.go hygiene entries, all modeled on 0068's pattern; TestLatestVersionIncludesMigration0068 is superseded per the one-pin-at-a-time convention. version_history.go: splits RecordVersionInTx into a versionedHistoryEnabled- gated wrapper and a new exported RecordVersionAtInTx, both delegating to a shared recordVersionAtInTx(..., at time.Time) body. RecordVersionAtInTx is test-support only -- ungated, caller-chosen timestamp -- so an as-of- read fixture's MintAt hook can mint version rows dated in the past without flipping a store's history-enabled flag. No behavior change for existing RecordVersionInTx callers. The new/moved code shifted which function each completeness guard sees as the enclosing write site, so all three needed updating, not bypassing: - row_lock_guard_test.go's funcNameExemptions key moves from RecordVersionInTx to recordVersionAtInTx (the write's new actual enclosing function), reasoning extended to cover both callers. - journal_completeness_test.go's beadDMLExemptions and version_completeness_test.go's versionExemptions each gain a RecordVersionAtInTx entry mirroring RecordVersionInTx's own (test- support twin, no production caller, no mutation of its own to journal/mint beyond the seam itself). Also fixed a latent test-helper gotcha found while writing the 0069 Dolt-CLI test: queryDoltCSV trims the whole `dolt sql -r csv` output before parsing, so a row whose ONLY selected column is NULL renders as a bare blank line that strings.TrimSpace silently swallows when it's the trailing line, collapsing "one row, NULL value" into "zero rows". Fixed by selecting a non-NULL anchor column (issue_id) alongside the column under test. Verification performed: full module compile and static analysis, gofmt clean; the complete internal/storage/schema suite with the real-Dolt-CLI lane enabled; and the complete internal/storage/issueops suite, including every completeness/row-lock structural guard -- all clean. * feat(issueops): wire dolt, embeddeddolt, and uow onto R7.1 as-of read (be-x5jqd.5) Turns backend/conformance/versioned_read_contract.go fully GREEN (authored RED in 6aefdce60, gastownhall/beads#5898 rev 9, #6136): this follows up on 4da98a9a8's shared production seam by wiring all three storage legs' AsOfReadFixture (Resolve/MintAt/MakeUnanswerable) onto issueops.AsOfReadInTx, per that commit's own stated plan. Each leg's asOfReadHarness is Design D's dispatch table: the conformance suite invents storeID strings to select among N isolated stores, and isolating them is entirely the harness's job -- AsOfReadInTx itself stays storeID-oblivious. The three legs differ only in how they get that isolation cheaply: - dolt: one shared testcontainer, N randomly-named databases - embeddeddolt: N fully independent on-disk databases - uow: one shared dolt sql-server subprocess (NewDoltServerUOWProvider's adoption semantics collapse repeat calls against the same root dir onto the same process), N randomly-named databases All three harnesses are Fatalf/Skip-free below their own TestAsOfReadContract body: AsOfReadFixture's hooks carry no *testing.T of their own and run from inside t.Run subtest closures (sometimes nested two deep), where FailNow/SkipNow would panic with "subtest may have called FailNow on a parent test". Failures instead flow back as a plain error into conformance.RunAsOfReadXXX, which Fatalfs correctly on the subtest's own goroutine. Two small companion fixes surfaced while wiring the legs on: - issueops.asOfVersionAddress -> AsOfVersionAddress (exported): each leg's MintAt needs to build the exact token its own RecordVersionAtInTx write will resolve against, from a different package than issueops. - recordVersionAtInTx now truncates `at` to whole seconds before writing it to issue_versions.change_at (DATETIME, migration 0067). Measured on dolt 2.2.3: the column ROUNDS a sub-second value rather than truncating it, so a change_at of 13:32:04.77 lands at 13:32:05 -- strictly later than the instant it was meant to record. That breaks resolveAsOfRevisionInTx's "at or before T" comparison (asof_read.go) for any T between the true instant and the rounded- up one. This is a production correctness fix, not test-only: RecordVersionInTx hits the identical hazard on every real time.Now().UTC() call whose nanosecond component rounds up. Verification performed: - uow: TestAsOfReadContract green standalone (5 subtests, 4 nested restriction variants) and the full uow package green in isolation (673s, includes pre-existing TestReleaserContract and everything else). A `go test ./internal/storage/...` full-tree sweep flagged uow FAIL via a 600s hang inside TestReleaserContract's migration lock -- traced to cross-package parallel resource contention from running the whole storage tree's dolt-sql-server-spinning suites concurrently, not a regression: the same test is clean when the package runs alone. - embeddeddolt: TestAsOfReadContract green (22.89s, all subtests and all 4 restriction variants). - dolt: skipped on this host -- no Docker for the leg's testcontainer, the same pre-existing skipIfNoDolt gate the whole dolt package already runs under, unrelated to this change. - TestEveryLegWiresEveryRoleContract and TestEveryContractImporterInTheStorageTreeIsRegistered both pass for all three legs. - gofmt clean; whole-module build and vet clean. Bead: be-x5jqd.5 * feat(versions): bd versions + a config switch for versioned history (refs be-hs42e.6.2) Versioned history has been buildable but not usable: migrations 0067+ create issue_versions, and the Phase 2 writer fills it, but SetVersionedHistoryEnabled was a Go method nothing in cmd/bd ever called. There was no supported way for a person to turn the feature on, and no way at all to read it back without raw Dolt SQL. This adds the switch and a reader. - versioned-history.enabled (env BD_VERSIONED_HISTORY_ENABLED), default off, applied at the top of wireStorageDecorators. It MUST run on the raw store: the capability is a type assertion and no decorator forwards it, so applying it after a wrap would silently leave history off while the config said it was on. TestVersionedHistoryConfigAppliesToTheRawStore pins the ordering, and fails rather than skips if a decorator ever starts forwarding. - storage.VersionLister + issueops.ListVersionsInTx over issue_versions, on the dolt and embeddeddolt legs. A narrow capability rather than a Storage method, following ExternalRefHistoryQuerier: a backend that cannot know must be able to say so instead of answering "none". - bd versions <id>, with three distinguishable outcomes rather than two. Off, unsupported, and empty are different answers with different fixes; an empty list is a claim about the bead, and returning it for the other two would be a wrong answer rather than an empty one. The four removal restrictions render as four sentences, and unknown (no lineage knowledge here) is not gone. - REV is printed as a local ordinal with a footer saying so. It is deliberately NOT presented as a citable address: AsOfVersionAddress mints over the ordinal, two clones can both hold revision 8 of the same bead, and the durable version_id primary key has not landed. An address printed now would break every citation once it does. - bd version <id> now points at bd versions <id> instead of printing bd's own build and looking like the bead has no history. Bare bd version is unchanged. No migration: 0067/0068/0069 already carry every column this reads. Verified on a scratch store: create + 2 updates + close with the flag on lists 4 attributed versions; with the flag off, 0 rows in issue_versions and the command refuses naming the key. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(versions): emit local_revision, not revision, in --json (bee's #5898 consumer read) types.Issue already ships `json:"revision"` (types.go:1206) and it is the row-lock CAS token — an unrelated value, and a string where this one is an int64. Emitting "revision" from the versions payload would put two meanings and two types on one key in the place machines read: the `bd version` collision again, with worse consequences, since a script that learned one shape gets the other and cannot tell. local_revision also carries the non-citability with the value rather than only in a footer no script parses, and needs no rename when version_id lands beside it. Raised by @bee-ghosttrack's consumer read on #5898, who reported a couple of hundred script files parsing `bd … --json` — this is the part of the surface they would actually touch. Pinned by TestVersionsJSONDoesNotCollideWithIssueRevision. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(versions): make the advertised switch actually switch it on (#6661 review) @bee-ghosttrack's blocking finding: the help text and the off-refusal both told the user to run `bd config set versioned-history.enabled true`, and that command did not turn the feature on. The key is not yaml-only, so `bd config set` routed it to the workspace DATABASE; both readers called config.GetBool, which is viper (yaml + env) only. The user ran exactly what they were told, was told it was set, and recording stayed off — configured on, actually off, one layer up from the decorator-ordering hazard this command already guards. Takes bee's option (b): read the switch from the store's own config, where `bd config set` already writes it. That also makes recording a property of the STORE rather than of whoever is calling, which is what closes finding 2 — two clients of one sql-server can no longer disagree about whether a write is recorded. The two planes are OR'd rather than ranked. The hazard is a write that fails to record, never one that records when it needn't, so either saying yes is enough and neither can silently switch the other off. BD_VERSIONED_HISTORY_ENABLED still works for a one-off run. A store with no settings plane (proxied, no-db) falls back to viper instead of failing the command. Also from that review: - finding 3: the read no longer refuses just because recording is off. A store that recorded for a month and was switched off HAS versions; refusing made a claim about the store from a fact about this invocation's config, which VersionLister's own doc says are independent. Rows are listed either way, with a note when recording is currently off; refuse-with-remedy only when off AND empty. - finding 4: an unresolved id with no versions is "no such bead", not "none yet". Falling through on an unresolved id stays right — a deleted bead can still have versions — but only until the answer is empty. - finding 5: the ordering test's escape hatch is t.Fatal, not t.Skip; a skip returned before the assertion that actually guards the ordering. The storage_chain.go doc cited a test name that never existed. version_lister.go promised a list of compile-time assertions that was not there; the assertions now exist in each leg's own package, where they can compile. - `versioned-history.` is a recognized config prefix, so the set no longer prints "not a recognized config key" immediately before confirming the set. Test: TestVersionedHistorySwitchRoundTrip_Embedded drives the real `bd config set` through to a real `bd versions` against a real store, with BD_VERSIONED_HISTORY_ENABLED cleared so a pass proves the store setting carried it alone. This is the round trip bee asked for, and it is the only shape that could have caught the original defect — a fake-backed unit test cannot see a disagreement between two real planes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs(versions): name what the OR'd switch planes cost (#6661 review) @bee-ghosttrack, round 2: with the two planes OR'd rather than ranked, the consequence worth naming is that once the store setting says on, BD_VERSIONED_HISTORY_ENABLED=0 cannot countermand it for a single run. The help now says so, and says where to turn it off instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(versions): gate the wiring store read on the capability, not a recover (#6661 review) @bee-ghosttrack's round-3 blocking finding. wireStorageDecorators reads the versioned-history switch off the raw store on every bd invocation, and did so before anything established that the store could use the answer. cmd/bd's own fakeProbingDoltStore embeds a nil storage.DoltStorage, so the promoted WorkspaceConfig SIGSEGV'd at wiring time -- and a panic takes the whole test binary down, which is why one unguarded read showed up as two red CI steps (Test (macos-latest), PR Core (wrapper timing)) rather than one failed test. Takes the fix bee prescribed: assert storage.VersionedHistoryConfigurer first and read the store plane only when the store could act on the answer. The previous round fixed this with a recover plus a WorkspaceConfig on the fake, and left a comment arguing that no capability assertion could work. That argument was wrong, and wrong in a specific way worth recording: it reasoned about asserting WorkspaceConfig, which IS declared on storage.DoltStorage and so matches every store including the nil-embedding fake. bee proposed asserting VersionedHistoryConfigurer, which is a different interface -- SetVersionedHistoryEnabled is NOT part of DoltStorage, so the fake does not promote it and does not satisfy it. The comment rebutted a fix that had not been proposed. It now states what is actually true. So the fake goes back to byte-identical with the pushed head: the wiring fix fixes that test without touching it, as bee said it would, and the fake keeps the "only the methods below may be called" constraint its own doc asserts. The recover stays, as a backstop rather than the guard. It covers what the assertion does not: versionedHistoryEnabled is also called from `bd versions`, where the read is the point and no capability gate precedes it, and a store that DOES implement the capability can still have a half-built settings plane. The viper plane is still read first and unconditionally, so a set-but-unsupported store still reaches applyVersionedHistoryConfig and still gets its warning. Only the store-plane read is gated. The one case that loses a warning is a store whose own settings plane says true but which lacks the capability -- and `bd config set` could not have written that plane on such a store to begin with. Tests, split so each layer fails for its own reason: - TestWireStorageDecoratorsSkipsTheStoreReadForANonConfigurer asserts calls == 0, not merely that it survived. "It survived" is what the recover delivers too, which is how this regressed the first time. - TestWireStorageDecoratorsSurvivesAStoreThatCannotAnswer keeps the recover's case, now on a store that IS a configurer so the guard lets it through. - TestVersionedHistoryEnabledForWiringReadsTheStoreWhenItCanRecord pins that the guard did not stop reading the plane finding 1 existed to start reading. Mutation-verified both ways: removing the guard fails the first test on calls=1/want=0 while everything still "passes" by surviving; removing the recover leaves the first test green and fails only the second. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(versions): name the embedded round-trip so CI selects it (#6661 review) @bee-ghosttrack's round-3 finding 2. The round-trip test that proves the two config planes agree ran only on the author's machine. .github/scripts/embedded-test-shard.sh discovers what to run with `grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go` and validates manifest entries against ^TestEmbedded[A-Za-z0-9_]+$. TestVersionedHistorySwitchRoundTrip_Embedded matched neither, so the only lane that sets BEADS_TEST_EMBEDDED_DOLT=1 for cmd/bd never selected it; the generic Test jobs run without that env, where the test's own guard skipped it. Skipped and passed look alike from outside, which is what made it invisible. Renaming is the whole fix -- a test absent from the shard manifest still gets a shard from the fallback distribution. Verified by running the script's own selector over the tree and confirming the new name is discovered. The rationale is now a comment on the test, because the old name reads more naturally and nothing else in the file explains why the prefix is load-bearing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(versions): drop the dead fixture, name the empty arm (#6661 review) @bee-ghosttrack's round-3 finding 3. TestVersionsRefusesWhenFlagOff built a backend holding one recorded version, handed it to nothing, and ended in `_ = backend`. The fixture was load-bearing for the assertion the test was named after -- that the read was refused BEFORE the backend was consulted. Finding 3 removed that behaviour on purpose, so the assertion went with it; the fixture stayed behind, unused, under a name still promising the old contract. Renamed to TestVersionsOffAndEmptyRefusesWithRemedy for what it actually pins, moved beside TestVersionsOffButRecordedStillLists so the two read as the pair they are -- recording off decides the FOOTER, never whether to read; off with rows lists them, off and empty is the one case that refuses -- and the dead fixture is gone. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(proxy): give bd versions a capability row, a typed refusal (#6661) main's proxied-server capability registry (#6582) requires every command path to carry a row, and TestProxyCapabilityRegistryCoversCommandTree fails for `bd versions`, which this PR adds. It is refused, reason unimplemented, rather than permitted. It is a pure read (issueops.ListVersionsInTx in one read transaction), so nothing about it is unsafe on a shared backend and "design" would be wrong. But it reaches the backend only through the optional storage.VersionLister, which the dolt and embedded stores implement and the uow provider does not. Permitting it would open the proxied provider in the root pre-run (starting the proxy and dolt) and then fail untyped at errVersionsUnsupported. The row refuses with proxy.versions.unsupported before any side effect, and its tracking names the missing piece: a VersionLister over the proxied uow provider (tracker #6132). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(uow): register verified shutdown cleanup in TestAsOfReadContract (#6661) main's TestEveryServerFixtureRegistersVerifiedCleanup (#6441) requires every server fixture to use verifiedShutdownCleanup(t, storeRootDir) instead of calling proxy.Shutdown directly, so a shutdown that refuses cannot leave a live dolt sql-server behind a green run. TestAsOfReadContract still had its own proxy.Shutdown cleanup that only logged the error. The cleanup is registered at the same point, so the LIFO ordering the harness relies on (every provider closed before the shared server stops) is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * style(schema): gofmt cli_migrations.go after the 0070 renumber The rebase onto upstream's 0069_widen_issue_versions_datetime_precision (#6675) joined its const and the renumbered 0070 comment without the separating blank line, which make fmt-check rejects. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(history): stop flooring change_at now that 0069 widened it (refs be-hs42e.10) recordVersionAtInTx carried `at = at.Truncate(time.Second)`. That was correct while 0067's plain DATETIME was in force: Dolt's datetime(0) does not truncate sub-second input, it ROUNDS half-up, so a change_at could be stored strictly LATER than the instant it recorded and break AsOfReadInTx's "latest version accepted at or before T". Flooring first left nothing to round. Migration 0069 widened change_at and removed_at to DATETIME(6), which removes the rounding entirely and makes the floor actively harmful — it threw away the microseconds the widening exists to keep. Two versions minted in the same second collapsed onto one stored value and stopped being distinguishable by change_at, which defeats --at, the only PORTABLE selector the read surface offers while revision stays a per-store ordinal and no durable version address has shipped. This was measured, not inferred. On a store carrying both the widening and the floor, four versions minted inside one second all read back 15:40:38.000000: the column could hold microseconds and the writer refused to supply them. Two correct fixes cancelling each other, and only the second one was visible. removed_at needs no matching change: MarkLatestVersionRemovedInTx already passes time.Now().UTC() straight through and was never floored. Audited rather than assumed. Pinned by TestRecordVersionKeepsSubSecondChangeAt (embeddeddolt), which mints two versions 500ms apart inside one second and asserts both that the fractional part survives and that the two differ. Verified it FAILS with the floor restored — reporting exactly the 11:04:07.000000 collapse — and passes without it, so it is a real guard rather than a test that passes either way. The column's own half of the contract stays pinned by TestMigration0069ChangeAtSurvivesSubSecondPrecisionThroughDoltCLI. Also drops this branch's own tx-minting guard commit, which upstream landed independently as #6833. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(feat): red — Activate versioned history in every store and provider factory, each store reading its own #6661 switch (stacked on #6661) (refs be-qxq70) Tests first, all failing on the right reasons at fb6e219d6a (#6661's head): - D1: on real embedded stores a routed update, a routed close and `bd create --repo` into a rig whose OWN row is on each gain 0 issue_versions rows, want 1; the control (a write inside the rig) gains 1. - D3: BD_VERSIONED_HISTORY_ENABLED=1 records into no routed store, and =0 is shown not to switch off a store whose row is on. - D4: TestEveryStoreConstructionActivatesVersionedHistory flags all 9 store and provider factories, and its mutation probe reports "probed 0 of 9". - wiring: wireStorageDecorators still reads the store's row (1 read) and switches it on; activation belongs to the factories. - internal/versionedhistory (does not exist yet) and the doctor repair opener: the resolver, the provider read (K1), the error-vs-absent diagnostics and the shared-activation requirement. * feat: green — Activate versioned history in every store and provider factory, each store reading its own #6661 switch (stacked on #6661) (refs be-qxq70) Stacked on #6661 (fb6e219d6a). #6661's plane and approved commits are unchanged: the switch stays a row of the store's own config table, OR'd with viper, and `bd config set versioned-history.enabled true` still writes that row and not config.yaml. The defect: applyVersionedHistoryConfig ran only from wireStorageDecorators, so the one store a command opens for its own workspace was activated and every store built by newDoltStoreFromConfig (prefix-routed update/close, `bd create --repo`, the direct-mode open) was not. With the switch on they recorded no issue_versions row while the command reported success. - Activation moves to where a store or unit-of-work provider is constructed (the store_factory.go/_nocgo.go twins, uow_factory.go's two provider constructors, the personal-migration planning store, and bd doctor's repair opener), on the raw store, before anything can wrap it. wireStorageDecorators no longer activates, so each store's row is read once per open. - One resolver, in internal/versionedhistory, reachable from doctor/fix which cannot import package main. #6661's semantics are preserved: one key spelling, viper first, then the capability check, then the row read, with the recover backstop. The behavior-preserving refactor of #6661's versioned_history_switch.go / storage_chain.go is the only edit to files #6661 introduced; the resolver tests moved with the code, assertions unchanged. - K1: a provider has no DoltStorage, so its row is read through a unit of work (NewUOW + ConfigUseCase().GetConfig) at construction: a pooled connection, one SELECT, rolled back. The constructors have already run initSchema, so this starts no server and creates nothing. It does not fall back to viper alone. - A row read that errors resolves to off but is reported under BD_DEBUG; an absent row stays silent. - Docs (configuration.md), a CHANGELOG entry, and a hint at `bd config set ... true` time that the setting replicates and is single-writer only. The bazel-sync run also wanted unrelated BUILD entries for files that already exist at #6661's head (versions.go, versioned_read_contract.go, ...); they are not part of this change and are left out. * test(feat): green — a served mutation records from the provider's own row, on a real server (refs be-qxq70) K1 is the one place the resolver cannot ask a DoltStorage: `bd serve` against a server-mode workspace writes through a unit-of-work provider, so its flag is read through NewUOW + ConfigUseCase().GetConfig at construction. The fakes in internal/versionedhistory prove the read; this proves it WORKS against a real Dolt server at that moment (pool open, database selected, schema migrated). Two server-mode workspaces on the shared test container: the one whose own row says on records a served HTTP mutation (+1 issue_versions row), the one with no row records none. Measured both ways: passes with the provider activation in place, and fails ("added 0 issue_versions row(s), want 1") with it deleted from both provider constructors in uow_factory.go. Proxied lane only (BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_ENV_RUN_DOLT=1 TESTCONTAINERS_RYUK_DISABLED=true), like TestServeActivatesTheEventsJournal, so it skips in a plain make test. * test(feat): red — #6661 review round, small items: findings 2, 4, 5, 6 and 8 Tests for the small findings in the second review round on #6661. - 2: `bd versions` must decide "recording" from the store's own setting. BD_VERSIONED_HISTORY_ENABLED=1 with the store's row unset and nothing recorded must refuse, not answer "none yet"; the help text must not offer the variable as a per-run switch for a read. - 4: `bd versions --json` is one object, {"versions": [...], "recording": bool}, with [] rather than null when nothing is recorded. - 5: AsOfReadInTx reports any stored removed_restriction outside its four values, "live" included, as unknown. - 6: the 0070 header spells the restriction vocabulary with the underscore spellings the code stores and compares. - 8: `bd version <arg>` exits 1 and points at `bd versions <arg>`. This one pins behaviour the branch already has, so it passes at red; it was shown to fail with the guard removed. Item 7 is a comment-only fix and has no test. * feat: green — #6661 review round, small items: findings 2, 4, 5, 6 and 7 - 2: `bd versions` reports the store's own setting. It read the environment and config.yaml as well, so BD_VERSIONED_HISTORY_ENABLED=1 made a store that never recorded answer "No versions recorded yet" instead of refusing with the remedy. It only reads, so those planes cannot make the store record. The "for one run" hint is dropped from the help and the refusal, since it could only ever produce the wrong answer. - 4: `bd versions --json` is always {"versions": [...], "recording": bool}, with [] rather than null when nothing is recorded. Previously a bare array, or null, and no recording flag. - 5: AsOfReadInTx reports a stored removed_restriction outside its four values, "live" included, as unknown instead of passing it through. - 6: the 0070 header and its test use the underscore spellings the code stores and compares. 0070 is unreleased, and this changes its content hash. - 7: comment only. DATETIME(6) still rounds to the microsecond; the comment said 0069 removed the rounding entirely. * test(fix): red — #6661 number admission: fractions past the bound, exponent cost, pre-enable scan Tests for the review round on the number-admission gate, written before the change: - a fraction whose nearest double is at or past 2^53 is refused (9007199254740993.5, 9007199254740994.5, 9007199254740991.5), and the gate is closed under its own canonicalization, checked as a property over a corpus - classification depends on magnitude, not on the size of an exponent: 1e100000000 and -1e400 are refusals, 1e-100000000 and 1e-400 are admitted, and allocation does not grow with the exponent - the sentinel's text names the I-JSON exact-integer range - CheckMetadataVersionable agrees with the mint, and FindUnversionableMetadata finds what the mint would refuse and skips what it never versions - bd config set versioned-history.enabled true refuses, writing nothing, over rows the mint would refuse, and false never scans Guards that pass before and after by design: the verdict on every literal as the store returns it, the mint's refusal writing nothing, and, on the server and embedded legs, the store-level property that no two literals reading back as different numbers share a canonical form. Those store tests also log what each Dolt holds for a number outside the range when history is off, and pin that a later write to such a row is refused once history is on. * fix: green — #6661 number admission: the nearest-double rule, ParseFloat classification, a pre-enable scan at the switch The admission gate now refuses a JSON number literal if and only if the binary64 nearest to it has magnitude above 2^53-1, or it overflows, whatever the literal's spelling: - a fraction that rounds to or past 2^53 (9007199254740993.5, 9007199254740994.5, 9007199254740991.5) is refused, so the gate is closed under its own canonicalization - literals are classified with strconv.ParseFloat, linear in their length, so 1e1000000 no longer builds a million-digit integer inside the writer's transaction; an overflow is the sentinel and a magnitude too small for binary64 is admitted; math/big is gone - the sentinel reads "number is outside the I-JSON exact-integer range (magnitude above 2^53-1)"; ErrIntegerNotRepresentable keeps its name, with a comment saying why - ordinary fractions such as 0.1 stay admitted; no verdict on a value the store hands back changes The header now says what the mint's refusal is: an integrity backstop inside the writer's transaction, not an admission policy for metadata. bd config set versioned-history.enabled true now checks the store first. It reads every issue the mint would version, runs the mint's own function over each one's metadata (issueops.CheckMetadataVersionable, through issueops.FindUnversionableMetadata), and refuses, writing nothing, while any is refused, printing the count, the ids and the fix. There is no override; setting it false never scans. The environment and config.yaml planes do not pass through the command and rely on the refusal at write time. Also: docs and a CHANGELOG entry, and comments in the existing admission tests that described the old rule. * test(fix): keep the exponent-cost allocation test stable under the race detector TestNumberAdmissionAllocationsDoNotGrowWithTheExponent compared two independently averaged allocation counts with a strict >. Under -race sync.Pool drops one Put in four at random, and the refusal's fmt.Errorf takes its printer from a pool, so a call now and then allocates one more than it would. The test failed on most runs of `go test -race -short`, the flag set of the required lane, and never without -race. That noise only ever adds allocations, so compare the fewest allocations over many single-call samples instead. The comparison stays strict, and it still fails on the exact big.Rat gate this test exists to keep out (49 allocations for 1e1000000 against 36 for 1e400). The doc comment no longer claims the count is deterministic under -race. * test(fix): red — set-many skips the pre-enable scan; pin what the scan reads bd config set-many versioned-history.enabled=true switches versioned history on with no pre-enable scan: only bd config set makes it. With a row holding a number outside the I-JSON exact-integer range the setting is turned on and the next write to that row fails. The new embedded test drives the real verb over such a row and expects the whole batch to be refused, writing nothing. The scan's own embedded test only used open issues, so deleting AllFlag or IncludeAllTypes, or replacing the unlimited Limit, left it green. It now adds a closed, a pinned and a gate offender, and a second test imports more rows than one default page and expects every one of them counted. * fix: green — bd config set-many runs the pre-enable scan for versioned-history.enabled bd config set refuses to turn versioned history on while an issue holds metadata a version could not record. bd config set-many writes the same setting through a validation loop of its own and made no such check, so it switched history on over a row whose next write then failed. It now runs the same check for that one key inside its validation loop, before any pair of the batch is written, so a refusal stores nothing. The check reads through the accessor it already used on both routes: the store the command has opened on the direct route, the provider on the proxied one. * chore: strip internal tracker ids from the comments and tests across #6661's range Comment and test-text changes only; no behaviour changes. Across every commit from the merge-base with upstream main to here, the comments and tests named internal tracker ids (one bead id in eleven comments and in one test failure message, an example id in the `bd version` guard's comment, and an internal decision's attribution in the huge-exponent admission test). They now cite gastownhall/beads#5898 and #6136 only, which is what a reader of the public branch can follow. The 0070 migration's header comment is one of the edits. That migration is new on this branch (it does not exist on upstream main), so the change is not an edit to a shipped migration, but it does change the file's content hash; the schema tests that compute hashes are self-consistent. Text that already exists on upstream main is left as it is, even where it mentions an id: this commit does not rewrite lines the range did not add. * chore(bazel): bazel-sync (gazelle) for the #6661 range * fix(bazel): give fix_test the store.go its activation guard parses TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation parses store.go from its working directory. `go test` runs in the package directory, so the file is there. A Bazel test only sees its declared runfiles, so the test failed with parse store.go: open store.go: no such file or directory in //cmd/bd/doctor/fix:fix_test (--config=ci) and in shard 1 of //cmd/bd/doctor/fix:fix_dolt_test (--config=doltserver), which runs the same binary through data = [":fix_test"]. Declare store.go as data on fix_test. * test(fix): red — the pre-enable scan must check the whole issue, as the mint does bd config set versioned-history.enabled true runs a check over every issue before it turns history on. The check looked at each issue's metadata alone, while the mint canonicalizes the whole issue. A gate's timeout is a time.Duration that a version holds as nanoseconds, so a gate whose timeout is past 2^53-1 ns (about 104.25 days) holds a number outside the I-JSON exact-integer range: the mint refuses every write to it, the scan never looked, and the switch could be turned on over it. - The agreement test's domain widens from metadata documents to whole issues: the metadata corpus, plus timeouts at 2500h (admitted), 2600h, 8760h and -2600h (refused), exactly 2^53-1 ns (admitted) and 2^53 ns (refused). - The scan test covers a gate over 105 days and expects the verdict to name the field, "timeout". - The mint-level refusal test covers the same gate and expects the refusal to name the field as well as the literal, for a number in metadata too. - An end-to-end test on the direct route and one on the proxied route create gates with bd gate create --timeout, expect the enable to refuse and name them, and expect the issues the scan names to be exactly the issues whose next write the mint refuses. - Three guards keep the scan's lite read from hiding a number: every column it leaves out is a string or a list of strings, nothing the mint adds and the scan does not load can hold a number, and no exported check over part of an issue exists beside the one the mint runs. Each guard is also run against shapes it must refuse, so it cannot pass by finding nothing. The new symbols (CheckIssueVersionable, FindUnversionable and the Field of UnversionableIssue) do not exist yet, so the issueops tests do not build. * fix: green — the pre-enable scan runs the mint's own check over the whole issue The check behind bd config set versioned-history.enabled true looked at each issue's metadata alone. The mint canonicalizes the whole issue, and a gate's timeout, a time.Duration held as nanoseconds, is a number outside the I-JSON exact-integer range once it is past 2^53-1 ns (about 104.25 days). The mint refuses every write to such a gate, the scan cleared the switch over it, and the first write after that failed. CheckIssueVersionable is now exactly canonicalDurableState's refusal over the whole issue, and FindUnversionable runs it over every issue the mint would version. It replaces FindUnversionableMetadata, and CheckMetadataVersionable is gone, so no check over part of an issue is exported beside the one the mint runs. A refusal names the top-level field it found the value in ("metadata", "timeout") as well as the literal, on the mint and on the scan; the field is located only after a refusal, so a write that is admitted still reads the document once. A gate timeout above 2^53-1 ns is unrecordable by policy: it is refused at the write, named by field and documented, not re-encoded. The refusal at the switch gives the fix for each field. For a number in metadata that is bd update --metadata or --unset-metadata, which works with history on or off because a version is recorded from the state after the write. For a gate timeout, which bd update cannot change, it is removing the gate with bd delete, or setting the timeout_ns column with bd sql while history is off; bd sql needs a server-backed store, and the text says so. It also says the check runs once, now: a writer that does not record (an older bd, bd sql, a pull from a clone that had history off) can add such a row afterwards, and the first write to it then fails with the same refusal. Making the check and the write of the setting one transaction would narrow that window, not close it. Corrected in the comments, the docs and the changelog as well: an import is not a path that skips the mint, since it goes through the same batch create; and Dolt's JSON column collapses duplicate keys when it stores a document, so on a Dolt store neither the scan nor the mint can see one, and the duplicate-key refusal is a defence for a backend that keeps them. * test(fix): red — the listing must answer as the as-of read does; the SDK opens must be accounted for Three review findings on the versioned-history change and one wording fix, tests first. - A removed version's restriction. AsOfReadInTx answers a stored value outside the four-value vocabulary (a NULL or empty column, "live", a hyphenated or arbitrary string) as unknown, but ListVersionsInTx hands the column back as stored, for every row, and the label bd versions prints passes such a string through. A table test runs the listing and the as-of read on the same stored value, for a version that was removed and one that was not, and expects the same answer, and none for a version that was never removed. The label gets the same out-of-vocabulary values and is expected to render what unknown renders. - The SDK's store opens. The shared construction guard now scans the repository root as well, so the Go SDK's five opens (Open, OpenFromConfig and OpenGated, and OpenBestAvailable in each build-tag twin) are noticed. Nothing accounts for them yet, so both guards fail on exactly those five sites. - A bytes bound beside the allocation-count bound on the number admission gate. A classifier that builds the number it is asked about makes one allocation whatever the exponent, so the count bound passes it, and the bytes grow. The fewest bytes one call allocates for a literal with a huge exponent must be no more than for a small one plus a margin. It passes today, because the gate never builds the number; it fails for a gate that does. - The refusal at the switch names the gate remedy as bd delete <id> --force, says that without --force bd only previews, and says that removing the gate unblocks anything it was blocking. The embedded and proxied end-to-end tests expect all three. * fix: green — the listing answers as the as-of read does; the SDK opens are accounted for Three review findings on the versioned-history change and one wording fix. A removed version's restriction. A stored removed_restriction is a free string, and only the four values of the vocabulary are answers. The as-of read already reported anything else (a NULL or empty column, "live", a hyphenated or arbitrary string) as unknown, but the listing handed the column back as stored, for every row, and the label bd versions prints passed it through. NormalizeRemovedRestriction is now the one place that decision is made. AsOfReadInTx calls it; ListVersionsInTx calls it for a version that was removed and gives a version that was not removed no restriction; and restrictionLabel renders through it. The listing, its JSON and the label now say what the as-of read says for the same row. The SDK's store opens. The Go SDK's five opens (Open, OpenFromConfig and OpenGated, and OpenBestAvailable in each build-tag twin) apply neither per-store switch, the events journal's or versioned history's, and they still do not. Applying them would change the library's behavior for every embedder, so that is a separate change; this one declares the boundary. The shared construction guard now accounts for the five with one exemption reason that is true of both switches, so a new SDK open is noticed rather than missed, and its staleness check keeps the exemptions honest. The docs gain one bullet saying that writers built on the SDK do not apply the switch. The bytes bound on the number admission gate needs no production change: the gate never builds the number, which is what the bound pins. The refusal at the switch now names the gate remedy as bd delete <id> --force, says that without --force bd only previews, and says that removing the gate also unblocks anything it was blocking. The docs line says the same. For a gate that blocks an issue, bd delete without --force prints a preview and exits 1, and with --force the gate is removed and what it blocked is ready again. * test(bazel): declare the root package's Go source as data for //cmd/bd:bd_test The shared store-construction scan now reads the repository root, where the Go SDK's opens live, but //cmd/bd:bd_test declared none of the root package's source. Under bazel test the scan therefore saw an empty directory, reported the five SDK exemptions as no longer matching a store construction site, and failed the events-journal guard, while go test, which sees the whole checkout, passed. List the root in tools/bazel/go_srcs.py so the generator emits its managed go_srcs filegroup there, and add that filegroup to bd_test's data. The new block is the generator's own output and nothing else changes. * ci: list the switch scan's proxied gate-timeout test in the 30-shard manifest Upstream main (#7129) moved the proxied-server tier to 30 duration-balanced shards, and TestProxiedShardManifestGeneratorNotStale requires every TestProxiedServer*/TestServerMode* test exactly once in that block. This branch adds TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout (cmd/bd/versioned_history_switch_scan_proxied_integration_test.go), so the block needs its line. Written by the generator itself: python3 scripts/ci/gen_proxied_shard_manifest.py 30 --weights=duration --write (one line, shard 8); --check exits 0 afterwards. Rebase note (maintainer): regenerated on current main, whose proxied-server tier uses 34 shards; the generator's incremental output (gen_proxied_shard_manifest.py 34 --weights=duration --write) placed this test at shard 6 of the 34-shard block. * ci: list the PR's embedded versioned-history tests in the embedded shard manifests #7156 made the embedded-Dolt tier's shard manifests exact-once (50 cmd shards, 15 storage shards), so every embedded test must be listed. This PR adds five embedded cmd tests and three embedded storage tests; this commit is exactly what the generators write for them: python3 scripts/ci/gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write Incremental: 8 lines added, none moved. Rebase note (maintainer): regenerated on current main, whose embedded manifests use 100 cmd shards and 40 storage shards; the generator's incremental output placed these tests at cmd shards 55 (TestEmbeddedVersionedHistorySwitchScansEveryRowNotOnePage), 56 (...SwitchRoundTrip), 57 (...SwitchRefusesUnversionableMetadata), 58 (...SwitchRefusesAnUnrecordableGateTimeout) and 59 (...SetManyRefusesUnversionableMetadata) of the 100-shard block, and at storage shards 5 (TestRecordVersionKeepsSubSecondChangeAt), 6 (TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart) and 23 (TestAsOfReadContract) of the 40-shard block. * test: exempt OpenBestAvailableWith, where #7188 moved the SDK's store construction Upstream #7188 split beads.OpenBestAvailable: it now delegates to the new OpenBestAvailableWith, which builds the store. This PR's two construction guards (TestEveryStoreConstructionActivatesTheEventsJournal and TestEveryStoreConstructionActivatesVersionedHistory) share one exemption list keyed by function, so after merging main they flagged OpenBestAvailableWith as an unexempted construction site and reported the OpenBestAvailable entries as stale. The two build-tag twins' keys now name OpenBestAvailableWith. The reason is unchanged: it is the SDK's library surface for embedders, and no code in the bd binary calls it. gofmt realigned the three neighbouring entries. * chore(schema): renumber removed_restriction to 0071 after #6943's 0070 Migrations are numbered by landing order. #6943 (participation_generation, the versioned-history write fence) lands first and owns main-plane 0070 and ignored/0028, so this PR's removed_restriction migration moves to the next free slot, 0071. The rename is done here, as one maintainer commit, rather than inside the replayed commits, so the history shows exactly what changed relative to the PR as reviewed; the intermediate commits of the rebase carry a duplicate 0070 and are not expected to build. - migrations/0070_add_removed_restriction.{up,down}.sql become 0071_*, with their header comments updated (the SQL itself is unchanged). Neither file exists on main or on #6943, so this is not an edit to a shipped migration. - cli_migrations.go: the CLI-bundle override is keyed to the new file name and renamed cliMigration0071AddRemovedRestriction, and its const now sits after 0070's. - migration_0070_add_removed_restriction_test.go becomes migration_0071_add_removed_restriction_test.go; its tests and messages say 0071, and it now owns the one LatestVersion pin (71). TestLatestVersionIncludesMigration0070 in #6943's participation_generation test is superseded by it and replaced by the usual pointer comment, and 0069's pointer comment now names the 0070 file that superseded it. - schema_test.go hygiene comments, BUILD.bazel embedsrcs/srcs, and the asof_read.go comment that cited the migration number. Checked: go test ./internal/storage/schema/... (with the dolt CLI lane, including TestAllMigrationsSQLAppliesThroughDoltCLIAndRecordsLatestVersion) and scripts/check-migration-hygiene.sh against origin/main and against #6943's tip. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(versions): reconcile #6661's tests and docs with #6943's write fence #6943's write fence (design §16.2b) makes an update-shaped write to a legacy record -- one whose participation_generation is NULL because it was created while versioned history was off -- a skip, not a refusal: the fence returns before the snapshot is canonicalized, so nothing is versioned and the mint's admission gate never runs. Several of #6661's tests seed rows with history off and then expect a later write to them to be versioned or refused, and several comments say every later write to an offending row fails. On a tree that carries both PRs those tests fail and those comments are wrong. This ports, without changing their substance, the fence-integration commits Jim Wordelman wrote for the donnabox integration fork, where both PRs were already folded together: - eff898db80 / 5d2e5a2ac4 (issueops, dolt, embeddeddolt): the mocked mint sequence scripts the fence's participation_generation read; the number fidelity test splits phase 2 into 2a (a legacy row is written, not versioned, not refused, stays NULL) and 2b (a participating row is refused and left untouched); TestRecordVersionInTxSkipsALegacyRowBefore- TheAdmissionGate pins the fence's order against the gate. - e0ad9d1e3c / 1528022dfa (cmd/bd): the switch round trip and the routing/env end-to-end tests build the rows they expect a version for after the setting is on, and assert that the pre-setting seeds gain nothing. - 18b9015bf5 (cmd/bd): the embedded and proxied gate-timeout scan tests assert the whole scan-vs-mint truth table (legacy offenders are named by the scan but not refused by the mint; participating offenders are both). - 5929ebd50c / 8ce872be03 (comments, CHANGELOG, configuration reference): the mint's refusal binds rows that participate in history; the pre-enable scan cannot see participation, so it over-approximates in the safe direction. Left out on purpose: the fork's mintSkipsRow helper and defer-wake sweep change, and its bd doctor "Versionable Issues" check and the docs that point at it; none of those are part of #6661 or #6943. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Jim Wordelman <jim@wordelman.name> * test(versions): adapt #6661's guards to what main changed under it Three test-side adjustments for code that landed on main after #6661's last merge of it; no production code changes. - internal/storage/leg_contract_wiring_test.go: main gained an HTTP storage leg, and TestEveryLegWiresEveryRoleContract requires every leg to name or waive every role contract. The five R7.1 as-of read contracts this PR adds are a storage capability the HTTP client does not serve (internal/httpclient answers AsOf with an explicit unsupported error, and the wire has no instant/address selector or gone/unknown refusal), so they are waived on the http leg with that reason, as the donnabox integration fork does. - cmd/bd/versioned_history_construction_test.go: main split newDoltStoreFromConfig into two thin wrappers over openDoltStoreFromConfig, which is where the activation defer now lives (this rebase's resolution of the activation commit), so the factory guard keys on that body. - cmd/bd/versioned_history_serve_e2e_test.go: main's TestProxiedGatedTestsRunInTheProxiedLane requires a test that skips unless BEADS_TEST_PROXIED_SERVER=1 to be one the proxied lane selects, so TestVersionedHistoryServeActivatesTheProviderFromItsOwnRow becomes TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow, and the 34-shard proxied manifest gains its line (written by gen_proxied_shard_manifest.py 34 --weights=duration --write, incremental; --check passes). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(bazel): emit go_srcs.py's managed blocks for internal/versionedhistory Main's tools/bazel/go_srcs.py now manages a repo_files filegroup block in every package BUILD file, lists those filegroups in the root BUILD.bazel's aggregates, and lists every go_library in tools/bazel's release_cross_build target. internal/versionedhistory is a package this PR adds, so after the rebase those managed blocks were stale and TestBazelGoSrcsBlocksCurrent (go test ./scripts/...) failed. This is the generator's own output (python3 tools/bazel/go_srcs.py) and nothing else; --check passes afterwards. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(versions): don't publish change_agent in bd versions --json `bd versions <id> --json` prints storage.IssueVersion as-is, so every JSON tag on that struct is part of a public contract. Provenance V2 (gastownhall/beads#7510, as ruled by the maintainer) removes the ad hoc agent field in favour of an actor chain; shipping a "change_agent" key now would make a public contract out of a field that is on its way out. IssueVersion.ChangeAgent is now tagged json:"-". Nothing else changes: the issue_versions.change_agent column (migration 0067) stays, ListVersionsInTx still reads it, change_actor and change_message are still published, and the human listing never showed the agent. No doc or golden named the key. TestVersionsJSONDoesNotPublishChangeAgent pins the absence with a non-empty value, so an omitempty-style regression would still fail, and pins that change_actor and change_message are still there. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(issueops): pin what the unfenced test-support mint does on #6943's new paths #6943's two fixes to the shared mint body -- (a) no issues row means no mint and no error, and (b) a create-shaped call on a new issues-table row flagged no-history stamps participation_generation without minting -- were written for its two kinds. This PR's shared body has a third, mintUnfenced, behind RecordVersionAtInTx (the R7.1 as-of fixtures' controlled-timestamp mint). The rebase resolution decided what (a) and (b) mean for it; this pins that decision: - (a) applies. It is the plane rule (FR-8: the table that holds the row decides its plane), not the fence, and the unfenced kind already honoured the flag-based form of the same rule (IsWisp). Without it, an unfenced mint for an unflagged wisps-table row would insert a version row that no issues row points at. The shared body's issues-table read now runs for all three kinds; only the update kind acts on the value it reads. - (b) does not apply. The unfenced mint never declares participation, so a flagged row returns right after the snapshot, as before: no read, no stamp. - The fence still does not apply: a legacy row is minted, and the closing UPDATE advances current_revision alone. TestRecordVersionAtInTxKeepsThePlaneRuleButNotTheFence scripts each of those three sequences exactly with sqlmock. TestTestSupportMintsStayOutsideTheShapeSplit places RecordVersionAtInTx outside #6943's create / dual-shape / update classification explicitly (it is the seam's exempt twin, not a mutation entry point or mint site): it must be in none of the shape lists, stay in versionExemptions, and reach neither RecordVersionForCreateInTx (it never stamps) nor RecordVersionInTx (whose gate and fence would stop the as-of fixtures minting history-off rows). The row-lock guard's exemption comment for recordVersionAtInTx already names the stamp-only UPDATE: #6943's own wording of it (all three UPDATE issues statements) was carried into that exemption when the as-of read commit was replayed. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(storage): say exactly why the as-of read contracts stay waived on http #6943 now runs most of its participation-generation contracts over the served wire (internal/httpclient/served_participation_generation_test.go): their subject is a create or an update, which the client can send, and the fixture reads the reference store's raw columns. This checked whether the five R7.1 as-of read contracts can be wired the same way. They cannot, cheaply or otherwise, without a new wire operation: - their subject is the read itself (AsOfReadFixture.Resolve), and R7.1's read, issueops.AsOfReadInTx, is reached by no publicops role and served by no wire operation; - the wire carries neither selector (an instant or a served version address) nor the gone/unknown refusal the read answers with; - the client's only point-in-time read, DoltStorage.AsOf, is a Dolt commit-ref read, not R7.1, and is on the client's D8 unsupported allowlist. Binding Resolve to the reference store behind the served env would pass, but as a property of that store, which the store legs already pin, never of the client. So the waiver stays; its comment and reason string now say the above instead of the earlier shorthand ("HTTP AsOf is explicitly unsupported"), which conflated the client's commit-ref AsOf with R7.1. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(versions): describe what the write fence does to beads that predate recording With #6943's write fence (design §16.2b) a bead that existed before versioned history was turned on (participation_generation NULL) is legacy: an update-shaped write to it is skipped, so it is never versioned however often it is edited. Several user-facing strings from #6661 still described the behaviour before the fence, and an independent review reproduced each with a built bd (a legacy bead edited twice after enabling still lists no versions; a legacy bead the switch refuses over is written without refusal under BD_VERSIONED_HISTORY_ENABLED=1). Text only; no behaviour changes. - bd versions help: only beads created while recording is on are versioned; a bead that already existed is legacy and editing it records nothing; no backfill. (Was: "a bead edited yesterday shows nothing until it is edited again".) - bd versions empty listing: drops "yet" and says why the list is empty -- a bead created while recording is on always has its create version, so an empty list means the bead predates recording (or was made by a writer that was not recording), or is no-history or a wisp. The line still starts "No versions recorded for <id>", which the switch round-trip test pins. - bd versions with recording off: only beads created after it is turned on are versioned. - bd config set versioned-history.enabled true refusal: Jim's scan stays as conservative as he made it -- it cannot see participation, and a legacy row can still be minted create-shaped if it re-enters the issues plane -- but the text now says a listed issue's writes are refused only if it participates (created while history was on, or entered the issues plane while it was on), and that legacy issues are listed because the check cannot tell. The closing line says the same of a value a non-recording writer adds later. - docs/reference/configuration.md: the section opener says every accepted change to an issue created while history is on is snapshotted, and that a pre-existing issue is legacy; the "participates" parenthetical drops "or written" (a write never stamps participation; only a create-shaped mint does) and names entering the issues plane, matching the refusal text. CHANGELOG already says "if it participates in history" and is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(versions): keep updated_at across update-shaped version mints The update-shaped mint ended with UPDATE issues SET current_revision = ? WHERE id = ?. current_revision always changes there, so the column's ON UPDATE CURRENT_TIMESTAMP clause fired: with versioned history on, every label, dependency or import write moved issues.updated_at to the session's wall clock (local time, read back as UTC). An import with RejectStaleUpserts then stored the wall clock instead of the source's updated_at, and the source's next genuine edit was rejected as stale. The statement now assigns updated_at to itself, the rule #4298, blocked_state.go's mark/unmark templates and the create-shaped mint statements already follow, so history on leaves updated_at exactly where history off does. It is the one statement every production update-shaped mint ends with. Tests: - TestEmbeddedMintLeavesUpdatedAtWhereHistoryOffDoes (embeddeddolt) ages a bead, adds and removes a label and a dependency, and runs two RejectStaleUpserts imports, with history off first as the control. With the fix reverted, history on fails all six arms (updated_at reads the wall clock, and the later source edit is rejected as stale); history off passes either way. - RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord, wired on the dolt, embeddeddolt, uow and http legs: a record created with the flag on and updated with it off mints nothing and keeps its current_revision. Every other flag-off case uses a legacy record, which the fence stops first, so with RecordVersionInTx's gate removed this is the only case that fails, on all four legs. That gate is the single entry for every production update-shaped mint, so the one update arm covers label and close writes too. - The sqlmock pin of the statement (version_history_preenable_scan_test.go) and the journal-completeness exemption comment follow the new SQL. - The createbatchequiv issues_updated_at goldens of small, depadd, import458 and import458-reject-stale are re-recorded. They pinned the wall-clock bump, so each row minted a second time (eq-n2; eq-db1 and eq-dl; eq-b3 and eq-b250) had dropped out of the compared set; CI's embedded and server legs both printed the new digests. Recorded on embedded Dolt, the fix-reverted tree reproduces every committed golden byte for byte, HEAD moves only these four digests, and its rows equal the history-off rows in every scenario. GoldenDirEnv's comment lists it as the goldens' third deliberate change. - The new embedded test has its line in the storage shard manifest (gen_embedded_storage_shard_manifest.py 40 --weights=duration --write), so TestStorageEmbeddedShardManifestGeneratorNotStale stays green. It sits after TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion rather than at the end of the file, where #7646 appends its own test, so the two PRs still merge without a conflict in that file. Docs: - CHANGELOG: the feature's two entries under ### Fixed described fixes to a switch no released bd has. One ### Added entry replaces them, covering bd versions, the versioned-history.enabled switch and its per-store semantics, the pre-enable check, the single-writer caveat, migration 0071 and the bd version <arg> refusal. - The bd versions help, its recording-off refusal and empty-listing note, and the opening paragraph of the configuration doc's Versioned Issue History section now state the rule the pre-enable refusal prints: a bead participates if it was created, or entered the issues plane (a wisp promoted or made persistent), while recording was on. bd version: the "did you mean bd versions" refusal now runs after the command's metrics event is created, like the other in-RunE argument refusals, so a mistyped bd version <id> is counted as a version invocation instead of going uncounted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen --------- Co-authored-by: Jim Wordelman <mayor@quad341.uk> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com> Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
1536 lines
56 KiB
Go
1536 lines
56 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/spf13/viper"
|
|
"github.com/steveyegge/beads/cmd/bd/doctor"
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/ceiling"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/git"
|
|
"github.com/steveyegge/beads/internal/gitenv"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/remotecache"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/tracker"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
var configCmd = &cobra.Command{
|
|
Use: "config",
|
|
GroupID: "setup",
|
|
Short: "Manage configuration settings",
|
|
Long: `Manage configuration settings for external integrations and preferences.
|
|
|
|
Configuration is stored per-project in the beads database and is version-control-friendly.
|
|
|
|
Common namespaces:
|
|
- export.* Auto-export settings (stored in config.yaml)
|
|
- import.* JSONL import settings (stored in config.yaml)
|
|
- jira.* Jira integration settings
|
|
- linear.* Linear integration settings
|
|
- github.* GitHub integration settings
|
|
- gitlab.* GitLab integration settings
|
|
- ado.* Azure DevOps integration settings
|
|
- notion.* Notion integration settings
|
|
- custom.* Custom integration settings
|
|
- status.* Issue status configuration
|
|
- claim.* Claim arbitration settings (pool-aware claiming)
|
|
- doctor.suppress.* Suppress specific bd doctor warnings (GH#1095)
|
|
- lint.* Additional per-type lint sections (stored in config.yaml)
|
|
|
|
Auto-Export (config.yaml):
|
|
Optional JSONL export to .beads/issues.jsonl after write commands (throttled).
|
|
Useful for viewers (bv), interchange, and issue-level migration; not a backup.
|
|
It is not cross-machine sync; use bd dolt push/pull with a Dolt remote.
|
|
Disabled by default. Enable only for integrations that need fresh JSONL.
|
|
Auto-staging is separate and disabled by default.
|
|
|
|
Keys:
|
|
export.auto Enable/disable auto-export (default: false)
|
|
export.path Output filename relative to .beads/ (default: issues.jsonl)
|
|
export.interval Minimum time between exports (default: 60s)
|
|
export.git-add Auto-stage the export file (default: false)
|
|
|
|
Auto-Import (config.yaml):
|
|
Reads .beads/issues.jsonl by default when a JSONL import path is implied.
|
|
Use a relative filename/path so the import stays within the project .beads/
|
|
directory and remains portable across machines.
|
|
|
|
Keys:
|
|
import.path Input filename relative to .beads/ (default: issues.jsonl)
|
|
|
|
Custom Status States:
|
|
You can define custom status states for multi-step pipelines using the
|
|
status.custom config key. Statuses should be comma-separated.
|
|
|
|
Example:
|
|
bd config set status.custom "awaiting_review,awaiting_testing,awaiting_docs"
|
|
|
|
This enables issues to use statuses like 'awaiting_review' in addition to
|
|
the built-in statuses (open, in_progress, blocked, deferred, closed).
|
|
|
|
Claim Pools:
|
|
A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g.
|
|
"fable-crew") and let any actor take them with --claim. List the pool
|
|
aliases in the claim.pools config key, comma-separated:
|
|
|
|
bd config set claim.pools "fable-crew,night-crew"
|
|
|
|
Issues assigned to a real actor (or to an alias not in the list) keep
|
|
their anti-steal protection. Pool takes carry the normal lease; note
|
|
that if a taker's lease expires, bd reclaim returns the issue to the
|
|
unassigned pool, not to the pool alias it was dispatched to.
|
|
|
|
Suppressing Doctor Warnings:
|
|
Suppress specific bd doctor warnings by check name slug:
|
|
bd config set doctor.suppress.pending-migrations true
|
|
bd config set doctor.suppress.git-hooks true
|
|
Check names are converted to slugs: "Git Hooks" → "git-hooks".
|
|
Only warnings are suppressed (errors and passing checks always show).
|
|
To unsuppress: bd config unset doctor.suppress.<slug>
|
|
|
|
Examples:
|
|
bd config set export.auto true # Enable auto-export for viewer integrations
|
|
bd config set export.path "beads.jsonl" # Custom export filename
|
|
bd config set import.path "beads.jsonl" # Custom import filename
|
|
bd config set export.git-add true # Also stage the export file
|
|
bd config set jira.url "https://company.atlassian.net"
|
|
bd config set jira.project "PROJ"
|
|
bd config set status.custom "awaiting_review,awaiting_testing"
|
|
bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor
|
|
bd config set doctor.suppress.pending-migrations true
|
|
bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu)
|
|
bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init
|
|
bd config set lint.sections.epic "Standards scorecard, Cost" # Extra sections bd lint requires for epics
|
|
bd config get export.auto
|
|
bd config list
|
|
bd config unset jira.url`,
|
|
}
|
|
|
|
var forceGitTracked bool
|
|
|
|
// newRoleConfigWriter captures fresh cwd and scrubbed routing once per write
|
|
// operation. The process-wide Git cache and Beads storage do not select it.
|
|
// Routing is scrubbed along with the suppression ScrubRouting deliberately
|
|
// keeps: beads.role is an authority value, and the reader it feeds treats a
|
|
// missing value as maintainer, so a suppressed config file would fail open.
|
|
func newRoleConfigWriter() (func(...string) error, error) {
|
|
dir, err := os.Getwd()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
env := gitenv.ScrubRoutingAndSuppression(os.Environ())
|
|
probe := exec.Command("git", "rev-parse", "--git-common-dir")
|
|
probe.Dir, probe.Env = dir, env
|
|
out, err := probe.Output()
|
|
if err != nil {
|
|
if exit, ok := err.(*exec.ExitError); ok && len(exit.Stderr) > 0 {
|
|
err = fmt.Errorf("%w: %s", err, strings.TrimSpace(string(exit.Stderr)))
|
|
}
|
|
return nil, fmt.Errorf("resolving common Git config: %w", err)
|
|
}
|
|
commonDir := git.NormalizePath(strings.TrimSpace(string(out)))
|
|
if commonDir == "" {
|
|
return nil, fmt.Errorf("Git returned an empty common directory")
|
|
}
|
|
if !filepath.IsAbs(commonDir) {
|
|
commonDir = filepath.Join(dir, commonDir)
|
|
}
|
|
return func(args ...string) error {
|
|
// Callers supply only the fixed role key, validated values and unset flag.
|
|
cmd := exec.Command("git", append([]string{"--git-dir", commonDir, "config", "--local"}, args...)...) //nolint:gosec // private validated config operations
|
|
cmd.Dir, cmd.Env = dir, env
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(output)))
|
|
}
|
|
return nil
|
|
}, nil
|
|
}
|
|
|
|
var configSetCmd = &cobra.Command{
|
|
Use: "set <key> <value>",
|
|
Short: "Set a configuration value",
|
|
Args: cobra.ExactArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(_ *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("config-set")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
key := args[0]
|
|
value := args[1]
|
|
|
|
if msg, rejected := rejectProtectedConfigKey(key); rejected {
|
|
fmt.Fprintln(os.Stderr, msg)
|
|
return SilentExit()
|
|
}
|
|
|
|
if key == "dolt.debug" && !usesSQLServer() {
|
|
fmt.Fprintln(os.Stderr, "Error: dolt.debug requires a sql-server-backed project (embedded mode has no managed server).")
|
|
fmt.Fprintln(os.Stderr, " To migrate: re-init with 'bd init --server' or 'bd init --shared-server'.")
|
|
return SilentExit()
|
|
}
|
|
|
|
if strings.HasPrefix(key, "storage-class.") {
|
|
if err := validateStorageClassConfig(key, value); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
|
|
if !isRecognizedConfigKey(key) {
|
|
suggestion := suggestConfigKey(key)
|
|
if suggestion != "" {
|
|
fmt.Fprintf(os.Stderr, "Warning: %q is not a recognized config key. Did you mean %q?\n", key, suggestion)
|
|
} else {
|
|
fmt.Fprintf(os.Stderr, "Warning: %q is not a recognized config key. Use 'custom.*' for user-defined keys.\n", key)
|
|
}
|
|
fmt.Fprintf(os.Stderr, "Run 'bd config --help' for valid namespaces.\n")
|
|
}
|
|
|
|
if !forceGitTracked {
|
|
if err := config.CheckSecretKeyGitSafety(key); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
|
|
if config.IsYamlOnlyKey(key) {
|
|
var setErr error
|
|
location := "config.yaml"
|
|
if config.IsUserGlobalKey(key) {
|
|
setErr = config.SetUserYamlConfig(key, value)
|
|
location = config.UserConfigYamlDisplayPath()
|
|
} else {
|
|
setErr = config.SetYamlConfig(key, value)
|
|
}
|
|
if setErr != nil {
|
|
return HandleError("setting config: %v", setErr)
|
|
}
|
|
|
|
if jsonOutput {
|
|
if err := outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"value": value,
|
|
"location": location,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("Set %s = %s (in %s)\n", key, value, location)
|
|
}
|
|
printConfigSideEffects(checkConfigSetSideEffects(key, value))
|
|
return nil
|
|
}
|
|
|
|
if key == "beads.role" {
|
|
validRoles := map[string]bool{"maintainer": true, "contributor": true}
|
|
if !validRoles[value] {
|
|
return HandleError("invalid role %q (valid values: maintainer, contributor)", value)
|
|
}
|
|
// bd config get/set/unset/set-many beads.role ignore inherited Git
|
|
// routing, including GIT_CONFIG_GLOBAL, so the value lands in the
|
|
// repository this command selected. beads.role is an authority
|
|
// value and the reader it feeds treats a missing value as
|
|
// maintainer, so these planes also discard the explicit suppression
|
|
// ScrubRouting deliberately keeps -- otherwise a blinded read fails
|
|
// open instead of erroring. That boundary is uniform across
|
|
// routing.DetectUserRole, `bd config show`, `bd doctor`,
|
|
// `bd hooks uninstall` and beads.RepoContext.Role, which re-pins
|
|
// GIT_DIR/GIT_WORK_TREE last-wins on top of it.
|
|
write, err := newRoleConfigWriter()
|
|
if err != nil {
|
|
return HandleError("setting beads.role in git config: %v", err)
|
|
}
|
|
if err := write("beads.role", value); err != nil {
|
|
return HandleError("setting beads.role in git config: %v", err)
|
|
}
|
|
if jsonOutput {
|
|
if err := outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"value": value,
|
|
"location": "git config",
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("Set %s = %s (in git config)\n", key, value)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Everything above this line is FRONT-DOOR routing: which source owns
|
|
// the key, and whether writing it to a file on this machine would leak
|
|
// a secret into git. From here the key is known to belong to the
|
|
// workspace database, and the write is the role's.
|
|
settings, err := openWorkspaceConfig("config set requires direct database access")
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
// Per-key validation that needs the store rather than the key alone: turning
|
|
// versioned history on refuses, writing nothing, while any issue holds a value a
|
|
// version could not record. The store is open here, on whichever route this is.
|
|
if err := checkVersionedHistoryCanBeEnabled(rootCtx, key, value); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := settings.SetSetting(rootCtx, issueops.SetSettingRequest{Key: key, Value: value})
|
|
if err != nil {
|
|
return HandleError("setting config: %v", err)
|
|
}
|
|
noteDirectConfigWrite()
|
|
if err := commitConfigWrite(rootCtx, store, "config set"); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
if err := outputJSON(map[string]string{
|
|
"key": result.Key,
|
|
"value": result.Value,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("Set %s = %s\n", result.Key, result.Value)
|
|
}
|
|
printConfigSideEffects(checkConfigSetSideEffects(result.Key, result.Value))
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// openWorkspaceConfig hands back the workspace-settings role for whichever
|
|
// route this invocation is on, each through its OWN capability accessor — the
|
|
// store's for the direct route and the provider's for the proxied one.
|
|
//
|
|
// directRequirement is the message `ensureDirectMode` reports when a workspace
|
|
// is reachable by neither route. It is per-verb because the shipped text names
|
|
// the verb.
|
|
func openWorkspaceConfig(directRequirement string) (issueops.WorkspaceConfig, error) {
|
|
if usesProxiedServer() {
|
|
return proxiedWorkspaceConfig()
|
|
}
|
|
if err := ensureDirectMode(directRequirement); err != nil {
|
|
return nil, err
|
|
}
|
|
return store.WorkspaceConfig()
|
|
}
|
|
|
|
// secretRowCleanup is what the best-effort database half of `bd config unset`
|
|
// achieved, kept apart from the config.yaml half because the two removals are
|
|
// independent. The YAML edit is the command's contract; the row is a credential
|
|
// the database replicated to every remote it was pushed to, so "I deleted it",
|
|
// "it is still there and I could not delete it" and "I could not look" are
|
|
// three different things to tell the user, and only the middle one is certain.
|
|
type secretRowCleanup struct {
|
|
present bool // a row was there when we read it
|
|
removed bool
|
|
err error
|
|
// commitErr is a failed Dolt commit of a delete that did land. It is a
|
|
// fourth thing to tell the user, not a failed removal: the row is gone from
|
|
// the working set, but HEAD, which is what `bd dolt push` publishes, still
|
|
// carries it until something commits the delete (GH#4078). After
|
|
// storage.ErrCommitIndeterminate the commit may have landed after all, so
|
|
// the report says the removal may not be committed rather than that it is
|
|
// not (see commitIndeterminate).
|
|
commitErr error
|
|
}
|
|
|
|
// commitIndeterminate reports whether commitErr leaves the delete's commit
|
|
// unknown rather than failed: the store marks an error whose outcome may be
|
|
// unknown, such as a connection lost during DOLT_COMMIT, with
|
|
// storage.ErrCommitIndeterminate. `bd dolt commit` is the remedy either way.
|
|
func (c secretRowCleanup) commitIndeterminate() bool {
|
|
return errors.Is(c.commitErr, storage.ErrCommitIndeterminate)
|
|
}
|
|
|
|
// describe writes the database half of the report. It says nothing at all for
|
|
// the overwhelmingly common workspace that never leaked: `config unset` is
|
|
// otherwise a one-line command and this is a footnote about a key's history.
|
|
func (c secretRowCleanup) describe(key, location string) {
|
|
switch {
|
|
case c.removed:
|
|
fmt.Printf("Also removed a stored %s row from the database, left by a bd that predates the key moving to %s.\n", key, location)
|
|
fmt.Printf("⚠ Rotate this credential: the row was replicated to every Dolt remote this workspace pushed to, and deleting it here does not unpublish it.\n")
|
|
switch {
|
|
case c.commitIndeterminate():
|
|
fmt.Fprintf(os.Stderr, "⚠ The removal may not be committed (%v): if it is not, HEAD still carries the row and `bd dolt push` keeps publishing it. Run `bd dolt commit` to be sure.\n", c.commitErr)
|
|
case c.commitErr != nil:
|
|
fmt.Fprintf(os.Stderr, "⚠ The removal is not committed (%v): HEAD still carries the row and `bd dolt push` keeps publishing it until `bd dolt commit` records the delete.\n", c.commitErr)
|
|
}
|
|
case c.err != nil && c.present:
|
|
// The one case that is not a maybe: the read found the row and the
|
|
// delete failed, so bd knows a live credential is still in the table.
|
|
fmt.Fprintf(os.Stderr, "⚠ A stored %s row is still in the database: removing it failed (%v).\n", key, c.err)
|
|
fmt.Fprintf(os.Stderr, "⚠ Rotate this credential: the row was replicated to every Dolt remote this workspace pushed to.\n")
|
|
case c.err != nil:
|
|
fmt.Fprintf(os.Stderr, "⚠ Could not check the database for a leaked %s row (%v). An older bd may have stored one there; re-run this command with the database reachable.\n", key, c.err)
|
|
}
|
|
}
|
|
|
|
// jsonFields carries the same three-way distinction to machine consumers.
|
|
// database_row_removed is always present for a secret key so a script can tell
|
|
// "nothing leaked" from "the field is missing because bd is older".
|
|
// database_commit_indeterminate qualifies database_commit_failed rather than
|
|
// replacing it, so a script that checks only database_commit_failed never takes
|
|
// a delete that may be uncommitted, and a credential HEAD may still publish,
|
|
// for a committed one.
|
|
func (c secretRowCleanup) jsonFields(payload map[string]interface{}) {
|
|
payload["database_row_removed"] = c.removed
|
|
if c.commitErr != nil {
|
|
payload["database_commit_failed"] = c.commitErr.Error()
|
|
if c.commitIndeterminate() {
|
|
payload["database_commit_indeterminate"] = true
|
|
}
|
|
}
|
|
switch {
|
|
case c.err != nil && c.present:
|
|
payload["database_row_present"] = true
|
|
payload["database_delete_failed"] = c.err.Error()
|
|
case c.err != nil:
|
|
payload["database_unreachable"] = c.err.Error()
|
|
}
|
|
}
|
|
|
|
// rowNote is the database half folded into the error the YAML half returns, so
|
|
// a failed `config unset` still tells the user where the credential stands. It
|
|
// goes on stderr with that error rather than to stdout, which `--json` owns.
|
|
func (c secretRowCleanup) rowNote(key string) string {
|
|
switch {
|
|
case c.removed && c.commitIndeterminate():
|
|
return fmt.Sprintf("\nA stored %s row WAS removed from the database, but the removal may not be committed (%v); run `bd dolt commit` to be sure, and rotate that credential — it was replicated to every Dolt remote this workspace pushed to.", key, c.commitErr)
|
|
case c.removed && c.commitErr != nil:
|
|
return fmt.Sprintf("\nA stored %s row WAS removed from the database, but the removal is not committed (%v); run `bd dolt commit`, and rotate that credential — it was replicated to every Dolt remote this workspace pushed to.", key, c.commitErr)
|
|
case c.removed:
|
|
return fmt.Sprintf("\nA stored %s row WAS removed from the database; rotate that credential — it was replicated to every Dolt remote this workspace pushed to.", key)
|
|
case c.err != nil && c.present:
|
|
return fmt.Sprintf("\nA stored %s row is still in the database: removing it failed (%v).", key, c.err)
|
|
case c.err != nil:
|
|
return fmt.Sprintf("\nThe database could not be checked for a leaked %s row (%v).", key, c.err)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// mayProvisionDatabase reports whether reaching the store from here could have
|
|
// to CREATE a database, which is the only thing unsetLeakedSecretRow's skip
|
|
// exists to avoid. Each arm that returns false is a route on which the database
|
|
// is already there, so consulting it provisions nothing:
|
|
//
|
|
// - the proxied route opens no local storage at all — proxiedWorkspaceConfig
|
|
// reaches an already-connected provider;
|
|
// - a store that is already open and tracked is ensureStoreActive's own
|
|
// no-op arm: it returns before newDoltStoreFromConfig ever runs. This is
|
|
// the state PersistentPreRun leaves a connected server-mode workspace in,
|
|
// and it is the only thing that tells the metadata-less server shape —
|
|
// `dolt.mode: server` or BEADS_DOLT_SERVER_HOST with no local database
|
|
// directory, routed deliberately at main.go, GH#3545 — apart from a
|
|
// workspace that genuinely has no database. beads.FindDatabasePath answers
|
|
// on metadata.json plus embeddeddolt/ and dolt/, so for that shape it
|
|
// reports "" while the row itself sits on the shared server, replicated to
|
|
// every remote the workspace ever pushed to. Skipping there would strand
|
|
// the leaked credential in the population that holds the most copies of it.
|
|
//
|
|
// Only when neither of those holds does the on-disk answer decide, and there
|
|
// the open really is open-OR-CREATE.
|
|
func mayProvisionDatabase() bool {
|
|
if usesProxiedServer() {
|
|
return false
|
|
}
|
|
lockStore()
|
|
active := isStoreActive() && getStore() != nil
|
|
unlockStore()
|
|
if active {
|
|
return false
|
|
}
|
|
return beads.FindDatabasePath() == ""
|
|
}
|
|
|
|
// unsetLeakedSecretRow deletes a yaml-only SECRET key's leftover row from the
|
|
// config table, reporting what it found and what it removed.
|
|
//
|
|
// WHY THE YAML UNSET IS NOT THE WHOLE JOB. A key becomes yaml-only at some
|
|
// point in bd's history, not at the beginning: `notion.token` moved in GH#6676,
|
|
// and every workspace configured before the move still has the value in the
|
|
// config table — a table whose contents `bd dolt push` replicates to every
|
|
// remote. `config unset`'s yaml-only branch returns before the store, so
|
|
// without this the only bd-side remover of that row would be gone for embedded
|
|
// workspaces, which are exactly the population the move protects. The row would
|
|
// keep authenticating (ResolveAuth reads it as the upgrade path) while the user
|
|
// who just ran `bd config unset` believes they are clean.
|
|
//
|
|
// IT IS BEST EFFORT, AND ONLY FOR SECRETS. The caller has already removed the
|
|
// value from config.yaml, which is the command's contract; a workspace with no
|
|
// reachable store must not be told that succeeded work failed. Non-secret
|
|
// yaml-only keys are skipped rather than merely unreported, so the ordinary
|
|
// `bd config unset routing.mode` keeps costing no database open at all — this
|
|
// pays the store-open only where a leaked credential could be sitting.
|
|
//
|
|
// The predicates, not a list of key names: `IsYamlOnlyKey` matches whole
|
|
// prefixes (`ai.`, `sync.`, `federation.`, ...), so the affected set is
|
|
// open-ended and grows whenever a tracker adds a credential. Measured at the
|
|
// time of writing, YamlOnlyKeys alone contributes seven — ado.pat,
|
|
// github.token, gitlab.token, jira.api_token, linear.api_key,
|
|
// linear.oauth_client_secret, notion.token — plus whatever the prefixes cover.
|
|
//
|
|
// IT NEVER PROVISIONS ONE. `config unset <yaml-only key>` is deliberately
|
|
// classified as runnable with no store (configCommandCanRunWithoutStore in
|
|
// main.go, GH#536 / bd-934 / bd-3rw), and the direct open below is
|
|
// open-OR-CREATE (ensureDirectMode → ensureStoreActive →
|
|
// newDoltStoreFromConfig), so without a gate editing a YAML file would
|
|
// materialize a database in a workspace that never had one and flip it out of
|
|
// its db-less mode for every later command. mayProvisionDatabase is that gate,
|
|
// and it asks about the store before the disk: "no local database directory" is
|
|
// not the same question as "no database", and the workspaces where the two
|
|
// answers differ are the ones whose row traveled furthest.
|
|
func unsetLeakedSecretRow(key string) secretRowCleanup {
|
|
// Gate BEFORE opening the store, not inside removeStoredSecretRow: this is
|
|
// what keeps `bd config unset routing.mode` from paying a database open it
|
|
// has no use for.
|
|
if !config.IsSecretKey(key) {
|
|
return secretRowCleanup{}
|
|
}
|
|
if mayProvisionDatabase() {
|
|
return secretRowCleanup{}
|
|
}
|
|
settings, err := openWorkspaceConfig("config unset requires direct database access")
|
|
if err != nil {
|
|
return secretRowCleanup{err: err}
|
|
}
|
|
present, removed, err := removeStoredSecretRow(rootCtx, settings, key)
|
|
cleanup := secretRowCleanup{present: present, removed: removed, err: err}
|
|
if removed {
|
|
noteDirectConfigWrite()
|
|
// Commit the delete like any other config write (GH#4078): until it is
|
|
// committed, HEAD still holds the credential and every `bd dolt push`
|
|
// keeps publishing it. A failure is reported, not returned — the delete
|
|
// itself landed, and the YAML unset is the command's contract.
|
|
cleanup.commitErr = commitConfigWrite(rootCtx, store, "config unset")
|
|
}
|
|
return cleanup
|
|
}
|
|
|
|
// removeStoredSecretRow deletes key's row, reporting whether one was there and
|
|
// whether it is gone. Those are two bits, not one: a failed delete on a row the
|
|
// read found is the single outcome that means "a live credential is still in
|
|
// the table bd pushes", and collapsing it into the error alone renders it as an
|
|
// unreachable database — the one case that needs no hedging.
|
|
//
|
|
// It READS BEFORE DELETING because UnsetSetting deliberately has no "removed"
|
|
// flag and deleting an absent key is a success — so a blind delete could not
|
|
// tell the caller whether anything had leaked, and the overwhelmingly common
|
|
// case (a workspace that never stored the key) has to stay silent rather than
|
|
// announce a removal that did not happen.
|
|
func removeStoredSecretRow(ctx context.Context, settings issueops.WorkspaceConfig, key string) (present bool, removed bool, err error) {
|
|
stored, err := settings.GetSetting(ctx, issueops.GetSettingRequest{Key: key})
|
|
if err != nil {
|
|
return false, false, err
|
|
}
|
|
if strings.TrimSpace(stored.Value) == "" {
|
|
return false, false, nil
|
|
}
|
|
if _, err := settings.UnsetSetting(ctx, issueops.UnsetSettingRequest{Key: key}); err != nil {
|
|
return true, false, err
|
|
}
|
|
return true, true, nil
|
|
}
|
|
|
|
// noteDirectConfigWrite marks the invocation as having written, which is what
|
|
// the auto-commit epilogue in main.go keys on.
|
|
//
|
|
// It is DIRECT-ROUTE ONLY: a proxied write already committed inside the role's
|
|
// own unit of work, so flagging it here would ask the epilogue to commit a
|
|
// second time on a route that has nothing outstanding.
|
|
func noteDirectConfigWrite() {
|
|
if !usesProxiedServer() {
|
|
commandDidWrite.Store(true)
|
|
}
|
|
}
|
|
|
|
var configGetCmd = &cobra.Command{
|
|
Use: "get <key>",
|
|
Short: "Get a configuration value",
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("config-get")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
key := args[0]
|
|
|
|
if key == "backup.enabled" {
|
|
// backup.enabled has an auto-detected effective value that
|
|
// differs from the stored value: when unset it auto-enables
|
|
// in embedded mode with a git remote, and is forced OFF in
|
|
// sql-server mode (see isBackupAutoEnabled). Reporting the raw
|
|
// stored "false"/"not set" here misled operators during the
|
|
// 2026-07 shared-dolt incident, so show the EFFECTIVE value
|
|
// and its source.
|
|
return runConfigGetBackupEnabled()
|
|
}
|
|
|
|
if config.IsYamlOnlyKey(key) {
|
|
// User-global keys (e.g. metrics.*) must be read from the user-global
|
|
// config.yaml only — the same source the runtime uses for metrics
|
|
// consent and endpoint. Reading the merged value here would let a
|
|
// project's .beads/config.yaml shadow the effective value and report the
|
|
// opposite of what `bd metrics` actually honors.
|
|
if config.IsUserGlobalKey(key) {
|
|
value := config.GetUserYamlConfig(key)
|
|
location := config.UserConfigYamlDisplayPath()
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"value": value,
|
|
"location": location,
|
|
})
|
|
}
|
|
if value == "" {
|
|
fmt.Printf("%s (not set in %s)\n", key, location)
|
|
} else {
|
|
fmt.Printf("%s\n", value)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
value := config.GetYamlConfig(key)
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"value": value,
|
|
"location": "config.yaml",
|
|
})
|
|
}
|
|
if value == "" {
|
|
fmt.Printf("%s (not set in config.yaml)\n", key)
|
|
} else {
|
|
fmt.Printf("%s\n", value)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
if key == "beads.role" {
|
|
// Same role-authority boundary as `bd config set` above.
|
|
cmd := exec.Command("git", "config", "--get", "beads.role")
|
|
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
|
|
output, err := cmd.Output()
|
|
value := strings.TrimSpace(string(output))
|
|
if err != nil {
|
|
value = ""
|
|
}
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"value": value,
|
|
"location": "git config",
|
|
})
|
|
}
|
|
if value == "" {
|
|
fmt.Printf("%s (not set in git config)\n", key)
|
|
} else {
|
|
fmt.Printf("%s\n", value)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
settings, err := openWorkspaceConfig("config get requires direct database access")
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := settings.GetSetting(rootCtx, issueops.GetSettingRequest{Key: key})
|
|
if err != nil {
|
|
return HandleError("getting config: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]string{
|
|
"key": result.Key,
|
|
"value": result.Value,
|
|
})
|
|
}
|
|
// "(not set)" also prints for a key stored as the empty string: the
|
|
// role answers "" for both, and issueops.SettingResult.Value says why.
|
|
if result.Value == "" {
|
|
fmt.Printf("%s (not set)\n", result.Key)
|
|
} else {
|
|
fmt.Printf("%s\n", result.Value)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// runConfigGetBackupEnabled reports the EFFECTIVE value of
|
|
// backup.enabled together with its source, rather than the raw stored
|
|
// value. The stored value is misleading because isBackupAutoEnabled()
|
|
// derives the runtime value: unset → auto-enabled in embedded mode
|
|
// when a git remote exists, and forced OFF in sql-server mode.
|
|
func runConfigGetBackupEnabled() error {
|
|
const key = "backup.enabled"
|
|
source := config.GetValueSource(key)
|
|
effective := isBackupAutoEnabled()
|
|
|
|
var sourceDesc string
|
|
switch source {
|
|
case config.SourceEnvVar:
|
|
sourceDesc = "env var"
|
|
case config.SourceConfigFile:
|
|
sourceDesc = "config.yaml"
|
|
default: // SourceDefault — value came from auto-detection
|
|
switch {
|
|
case usesSQLServer():
|
|
sourceDesc = "default (auto: off in sql-server mode)"
|
|
case effective:
|
|
sourceDesc = "default (auto: on — git remote detected)"
|
|
default:
|
|
sourceDesc = "default (auto: off — no git remote)"
|
|
}
|
|
}
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"value": effective,
|
|
"effective": effective,
|
|
"source": string(source),
|
|
})
|
|
}
|
|
fmt.Printf("%t (%s)\n", effective, sourceDesc)
|
|
return nil
|
|
}
|
|
|
|
var configListCmd = &cobra.Command{
|
|
Use: "list",
|
|
Short: "List all configuration",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("config-list")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
settings, err := openWorkspaceConfig("config list requires direct database access")
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := settings.ListSettings(rootCtx, issueops.ListSettingsRequest{})
|
|
if err != nil {
|
|
return HandleError("listing config: %v", err)
|
|
}
|
|
stored := result.Settings
|
|
|
|
if jsonOutput {
|
|
return outputJSON(stored)
|
|
}
|
|
|
|
if len(stored) == 0 {
|
|
fmt.Println("No configuration set")
|
|
return nil
|
|
}
|
|
|
|
keys := make([]string, 0, len(stored))
|
|
for k := range stored {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
|
|
fmt.Println("\nConfiguration:")
|
|
for _, k := range keys {
|
|
fmt.Printf(" %s = %s\n", k, stored[k])
|
|
}
|
|
|
|
// The OTHER sources, reported beside the stored ones rather than merged
|
|
// into them: the role answers for the database, and config.yaml and the
|
|
// environment are files and variables of THIS process.
|
|
showConfigYAMLOverrides(stored)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// showConfigYAMLOverrides warns when config.yaml or env vars override database settings.
|
|
// This addresses the confusion when `bd config list` shows one value but the effective
|
|
// value used by commands is different due to higher-priority config sources.
|
|
func showConfigYAMLOverrides(dbConfig map[string]string) {
|
|
var envWarnings []string
|
|
|
|
// Check each DB config key for env var overrides using config.EnvVarName
|
|
// which handles both BD_* and legacy BEADS_* prefixes with LookupEnv.
|
|
for key, dbValue := range dbConfig {
|
|
if envName := config.EnvVarName(key); envName != "" {
|
|
envValue := os.Getenv(envName)
|
|
if envValue != dbValue {
|
|
envWarnings = append(envWarnings, fmt.Sprintf(" %s: DB has %q, but env %s=%q takes precedence", key, dbValue, envName, envValue))
|
|
}
|
|
}
|
|
}
|
|
|
|
// Discover yaml-only keys dynamically via AllKeys() instead of a hardcoded list.
|
|
// This stays in sync as new yaml-only keys are added to the config system.
|
|
allKeys := config.AllKeys()
|
|
sort.Strings(allKeys)
|
|
|
|
var yamlOverrides []string
|
|
for _, key := range allKeys {
|
|
// Skip keys already shown in the DB config section
|
|
if _, inDB := dbConfig[key]; inDB {
|
|
continue
|
|
}
|
|
// Only show yaml-only keys that are explicitly set in config.yaml
|
|
if !config.IsYamlOnlyKey(key) {
|
|
continue
|
|
}
|
|
if config.GetValueSource(key) != config.SourceConfigFile {
|
|
continue
|
|
}
|
|
val := config.GetString(key)
|
|
if val != "" {
|
|
yamlOverrides = append(yamlOverrides, fmt.Sprintf(" %s = %s", key, val))
|
|
}
|
|
}
|
|
|
|
// Also check yaml-only keys for env var overrides
|
|
for _, key := range allKeys {
|
|
if _, inDB := dbConfig[key]; inDB {
|
|
continue // already checked above
|
|
}
|
|
if envName := config.EnvVarName(key); envName != "" {
|
|
src := config.GetValueSource(key)
|
|
if src == config.SourceEnvVar {
|
|
envWarnings = append(envWarnings, fmt.Sprintf(" %s: env %s=%q overrides config", key, envName, os.Getenv(envName)))
|
|
}
|
|
}
|
|
}
|
|
|
|
if len(yamlOverrides) > 0 {
|
|
fmt.Println("\nAlso set in config.yaml (not shown above):")
|
|
for _, line := range yamlOverrides {
|
|
fmt.Println(line)
|
|
}
|
|
}
|
|
|
|
if len(envWarnings) > 0 {
|
|
sort.Strings(envWarnings)
|
|
fmt.Println("\n⚠ Environment variable overrides detected:")
|
|
for _, w := range envWarnings {
|
|
fmt.Println(w)
|
|
}
|
|
}
|
|
|
|
fmt.Println("\nTip: Run 'bd config show' for all effective config with provenance.")
|
|
}
|
|
|
|
// runConfigUnsetYamlOnly removes a yaml-only key from config.yaml and, for a
|
|
// secret key, the row a bd that predates the key's move to YAML may have left
|
|
// in the config table.
|
|
//
|
|
// THE TWO REMOVALS ARE INDEPENDENT, AND SO IS THEIR REPORTING. Running the row
|
|
// cleanup only after a successful YAML edit would skip it for exactly the
|
|
// workspaces the cleanup exists for: one whose config.yaml is missing, or whose
|
|
// notion.token sits in a shape the unset refuses, gets an error about
|
|
// config.yaml and keeps the credential in the table `bd dolt push` replicates —
|
|
// while `bd notion status` names this very command as the remover. So the
|
|
// cleanup runs either way, and a failed YAML unset carries the row's fate in
|
|
// its error rather than dropping it.
|
|
func runConfigUnsetYamlOnly(key string) error {
|
|
file := "config.yaml"
|
|
var changed bool
|
|
var unsetErr error
|
|
if config.IsUserGlobalKey(key) {
|
|
changed, unsetErr = config.UnsetUserYamlConfig(key)
|
|
file = config.UserConfigYamlDisplayPath()
|
|
} else {
|
|
changed, unsetErr = config.UnsetYamlConfig(key)
|
|
}
|
|
|
|
cleanup := unsetLeakedSecretRow(key)
|
|
|
|
if unsetErr != nil {
|
|
return HandleError("unsetting config: %v%s", unsetErr, cleanup.rowNote(key))
|
|
}
|
|
|
|
// The location is a report of the write, not a guess made before it: an
|
|
// absent file or a key that was never written there is a no-op, and saying
|
|
// "Unset <key> (in config.yaml)" over a file that never held it is the
|
|
// untrustworthy message this command's fix set out to remove.
|
|
location := ""
|
|
if changed {
|
|
location = file
|
|
}
|
|
|
|
if jsonOutput {
|
|
payload := map[string]interface{}{
|
|
"key": key,
|
|
"location": location,
|
|
// The human branch gets an explicit "was not set" sentence; without
|
|
// this the machine branch cannot tell that no-op apart from an
|
|
// unpopulated field, since both render location as "".
|
|
"changed": changed,
|
|
}
|
|
if config.IsSecretKey(key) {
|
|
cleanup.jsonFields(payload)
|
|
}
|
|
if err := outputJSON(payload); err != nil {
|
|
return err
|
|
}
|
|
} else if changed {
|
|
fmt.Printf("Unset %s (in %s)\n", key, location)
|
|
cleanup.describe(key, location)
|
|
} else {
|
|
fmt.Printf("%s was not set in %s\n", key, file)
|
|
cleanup.describe(key, file)
|
|
}
|
|
// Gate the hint on the write, uniformly across all three arms above. Every
|
|
// key in checkConfigUnsetSideEffects is phrased in the completed past tense
|
|
// ("Backup config removed...") and three of the four hand the operator a
|
|
// follow-up command, so on the no-op branch the command contradicted the
|
|
// line it had just printed. This covers the jsonOutput arm too: the hint
|
|
// goes to stderr, so --json never suppressed it.
|
|
if changed {
|
|
printConfigSideEffects(checkConfigUnsetSideEffects(key))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var configUnsetCmd = &cobra.Command{
|
|
Use: "unset <key>",
|
|
Short: "Delete a configuration value",
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("config-unset")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
key := args[0]
|
|
|
|
if config.IsYamlOnlyKey(key) {
|
|
return runConfigUnsetYamlOnly(key)
|
|
}
|
|
|
|
if key == "beads.role" {
|
|
// Same role-authority boundary as `bd config set`/`get` above: every
|
|
// spelling of a beads.role mutation resolves the repository the same
|
|
// way, so the next reader has one boundary to reason about.
|
|
write, err := newRoleConfigWriter()
|
|
if err != nil {
|
|
return HandleError("unsetting beads.role in git config: %v", err)
|
|
}
|
|
if err := write("--unset", "beads.role"); err != nil {
|
|
return HandleError("unsetting beads.role in git config: %v", err)
|
|
}
|
|
if jsonOutput {
|
|
if err := outputJSON(map[string]interface{}{
|
|
"key": key,
|
|
"location": "git config",
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("Unset %s (in git config)\n", key)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
settings, err := openWorkspaceConfig("config unset requires direct database access")
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
result, err := settings.UnsetSetting(rootCtx, issueops.UnsetSettingRequest{Key: key})
|
|
if err != nil {
|
|
return HandleError("deleting config: %v", err)
|
|
}
|
|
noteDirectConfigWrite()
|
|
if err := commitConfigWrite(rootCtx, store, "config unset"); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
// Clear the config.yaml layer unconditionally and report what the
|
|
// write actually did. Pre-checking with GetYamlConfig would read
|
|
// viper's *merged* value - SetDefault values and AutomaticEnv
|
|
// included - so a key with a non-empty default (no-hooks, json,
|
|
// events-journal-retain-days, ...) looked present in config.yaml even
|
|
// in a workspace with no config.yaml at all. That produced a more
|
|
// specific false claim than the message this fix removed, and, with no
|
|
// project config.yaml, failed the command after the database row was
|
|
// already gone.
|
|
//
|
|
// A config.yaml the unset refuses to edit (a flow-style mapping, a
|
|
// block value) is reported as exactly that: any database row is
|
|
// already gone, but the key is still effective from the file, so this
|
|
// still fails. "Any": UnsetSettingResult cannot say whether a row
|
|
// existed, since the storage seam discards the affected-row count.
|
|
location := "database"
|
|
yamlCleared, err := config.UnsetYamlConfig(result.Key)
|
|
// A workspace with no project config.yaml has no YAML layer to clear, so
|
|
// the database write above is the whole unset and this succeeds - that is
|
|
// the case that used to fail the command after the row was already gone.
|
|
// A config.yaml that exists and refused the edit is the opposite: the key
|
|
// is still effective from the file, so that still fails.
|
|
if err != nil && !errors.Is(err, config.ErrNoProjectConfigYaml) {
|
|
return HandleError("%s is still set in config.yaml (any database row was removed): %v", result.Key, err)
|
|
}
|
|
if yamlCleared {
|
|
location = "database, config.yaml"
|
|
}
|
|
|
|
if jsonOutput {
|
|
if err := outputJSON(map[string]string{
|
|
"key": result.Key,
|
|
"location": location,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
fmt.Printf("Unset %s (in %s)\n", result.Key, location)
|
|
}
|
|
printConfigSideEffects(checkConfigUnsetSideEffects(result.Key))
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var configValidateCmd = &cobra.Command{
|
|
Use: "validate",
|
|
Short: "Validate sync-related configuration",
|
|
Long: `Validate sync-related configuration settings.
|
|
|
|
Checks:
|
|
- federation.sovereignty is valid (T1, T2, T3, T4, or empty)
|
|
- federation.remote is set for Dolt sync
|
|
- Remote URL format is valid (dolthub://, gs://, s3://, az://, file://)
|
|
- routing.mode is valid (auto, maintainer, contributor, explicit)
|
|
|
|
Examples:
|
|
bd config validate
|
|
bd config validate --json`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("config-validate")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
repoPath, err := resolvedConfigRepoRoot()
|
|
if err != nil {
|
|
return HandleErrorWithHintRespectJSON(activeWorkspaceNotFoundError(), diagHint())
|
|
}
|
|
|
|
doctorCheck := doctor.CheckConfigValues(repoPath)
|
|
|
|
syncIssues := validateSyncConfig(repoPath)
|
|
|
|
allIssues := []string{}
|
|
if doctorCheck.Detail != "" {
|
|
allIssues = append(allIssues, strings.Split(doctorCheck.Detail, "\n")...)
|
|
}
|
|
allIssues = append(allIssues, syncIssues...)
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"valid": len(allIssues) == 0,
|
|
"issues": allIssues,
|
|
})
|
|
}
|
|
|
|
if len(allIssues) == 0 {
|
|
fmt.Println("✓ All sync-related configuration is valid")
|
|
return nil
|
|
}
|
|
|
|
fmt.Println("Configuration validation found issues:")
|
|
for _, issue := range allIssues {
|
|
if issue != "" {
|
|
fmt.Printf(" • %s\n", issue)
|
|
}
|
|
}
|
|
fmt.Println("\nRun 'bd config set <key> <value>' to fix configuration issues.")
|
|
return SilentExit()
|
|
},
|
|
}
|
|
|
|
// validateSyncConfig performs additional sync-related config validation
|
|
// beyond what doctor.CheckConfigValues covers.
|
|
func validateSyncConfig(repoPath string) []string {
|
|
var issues []string
|
|
|
|
// Load config.yaml from the resolved workspace so shared worktrees validate
|
|
// the same config file they actually run with.
|
|
configPath := filepath.Join(doctor.ResolveBeadsDirForRepo(repoPath), "config.yaml")
|
|
v := viper.New()
|
|
v.SetConfigType("yaml")
|
|
v.SetConfigFile(configPath)
|
|
|
|
// Try to read config, but don't error if it doesn't exist
|
|
if err := v.ReadInConfig(); err != nil {
|
|
// Config file doesn't exist or is unreadable - nothing to validate
|
|
return issues
|
|
}
|
|
|
|
// Get config from yaml
|
|
federationSov := v.GetString("federation.sovereignty")
|
|
federationRemote := v.GetString("federation.remote")
|
|
|
|
// Validate federation.sovereignty
|
|
if federationSov != "" && !config.IsValidSovereignty(federationSov) {
|
|
issues = append(issues, fmt.Sprintf("federation.sovereignty: %q is invalid (valid values: %s, or empty for no restriction)", federationSov, strings.Join(config.ValidSovereigntyTiers(), ", ")))
|
|
}
|
|
|
|
// Validate federation.remote is set (required for Dolt sync)
|
|
if federationRemote == "" {
|
|
issues = append(issues, "federation.remote: required for Dolt sync")
|
|
}
|
|
|
|
// Strict security validation of remote URL
|
|
if federationRemote != "" {
|
|
if err := remotecache.ValidateRemoteURL(federationRemote); err != nil {
|
|
issues = append(issues, fmt.Sprintf("federation.remote: %s", err))
|
|
}
|
|
}
|
|
|
|
// Validate against allowed-remote-patterns if configured
|
|
if federationRemote != "" {
|
|
patterns := v.GetStringSlice("federation.allowed-remote-patterns")
|
|
if len(patterns) > 0 {
|
|
if err := remotecache.ValidateRemoteURLWithPatterns(federationRemote, patterns); err != nil {
|
|
issues = append(issues, fmt.Sprintf("federation.remote: %s", err))
|
|
}
|
|
}
|
|
}
|
|
|
|
return issues
|
|
}
|
|
|
|
// isValidRemoteURL validates remote URL formats for sync configuration.
|
|
// Uses strict security validation that checks structural correctness,
|
|
// rejects control characters, and validates per-scheme requirements.
|
|
func isValidRemoteURL(rawURL string) bool {
|
|
return remotecache.ValidateRemoteURL(rawURL) == nil
|
|
}
|
|
|
|
// findBeadsRepoRoot walks up from the given path to find the repo root (containing .beads)
|
|
func findBeadsRepoRoot(startPath string) string {
|
|
path := startPath
|
|
bound := ceiling.For(startPath)
|
|
for !bound.Excludes(path) {
|
|
beadsDir := filepath.Join(path, ".beads")
|
|
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
|
|
return path
|
|
}
|
|
parent := filepath.Dir(path)
|
|
if parent == path {
|
|
break
|
|
}
|
|
path = parent
|
|
}
|
|
|
|
if isGitRepo() && git.IsWorktree() {
|
|
if fallbackDir := beads.GetWorktreeFallbackBeadsDir(); fallbackDir != "" {
|
|
return filepath.Dir(fallbackDir)
|
|
}
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
// resolvedConfigRepoRoot returns the repository root for the active beads
|
|
// workspace. It follows FindBeadsDir semantics, including BEADS_DIR and
|
|
// worktree/shared fallback resolution.
|
|
func resolvedConfigRepoRoot() (string, error) {
|
|
beadsDir := beads.FindBeadsDir()
|
|
if beadsDir == "" {
|
|
return "", fmt.Errorf("%s", activeWorkspaceNotFoundError())
|
|
}
|
|
return filepath.Dir(beadsDir), nil
|
|
}
|
|
|
|
var configSetManyCmd = &cobra.Command{
|
|
Use: "set-many <key=value>...",
|
|
Short: "Set multiple configuration values in one operation",
|
|
Long: `Set multiple configuration values at once with a single auto-commit and auto-push.
|
|
|
|
Each argument must be in key=value format. All values are validated before
|
|
any writes occur. This is faster and less noisy than separate 'bd config set'
|
|
calls, especially in CI.
|
|
|
|
Examples:
|
|
bd config set-many ado.state_map.open=New ado.state_map.closed=Closed
|
|
bd config set-many jira.url=https://example.atlassian.net jira.project=PROJ`,
|
|
Args: cobra.MinimumNArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(_ *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("config-set-many")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
type kvPair struct {
|
|
key, value string
|
|
}
|
|
pairs := make([]kvPair, 0, len(args))
|
|
for _, arg := range args {
|
|
idx := strings.Index(arg, "=")
|
|
if idx <= 0 {
|
|
return HandleError("invalid argument %q (expected key=value format)", arg)
|
|
}
|
|
pairs = append(pairs, kvPair{key: arg[:idx], value: arg[idx+1:]})
|
|
}
|
|
|
|
for _, p := range pairs {
|
|
// The same refusal `bd config set` makes, and it was MISSING here:
|
|
// `bd config set-many issue_prefix=x` re-prefixed the workspace
|
|
// behind the guard the single-key verb enforces. This verb does not
|
|
// go through issueops.WorkspaceConfig (see the write below), so it
|
|
// makes the refusal itself, before any pair is written.
|
|
if msg, rejected := rejectProtectedConfigKey(p.key); rejected {
|
|
fmt.Fprintln(os.Stderr, msg)
|
|
return SilentExit()
|
|
}
|
|
if p.key == "beads.role" {
|
|
validRoles := map[string]bool{"maintainer": true, "contributor": true}
|
|
if !validRoles[p.value] {
|
|
return HandleError("invalid role %q (valid values: maintainer, contributor)", p.value)
|
|
}
|
|
}
|
|
if p.key == "status.custom" && p.value != "" {
|
|
if _, err := types.ParseCustomStatusConfig(p.value); err != nil {
|
|
return HandleError("invalid status.custom value: %v", err)
|
|
}
|
|
}
|
|
if strings.HasPrefix(p.key, "storage-class.") {
|
|
if err := validateStorageClassConfig(p.key, p.value); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
// The pre-enable check `bd config set` makes: turning versioned history
|
|
// on refuses while any issue holds a value a version could not record.
|
|
// This verb writes the same setting through a loop of its own, so it
|
|
// makes the check itself, here and before any pair is written: a refusal
|
|
// stores nothing from the batch.
|
|
if err := checkVersionedHistoryCanBeEnabled(rootCtx, p.key, p.value); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
|
|
var yamlPairs, gitPairs, dbPairs []kvPair
|
|
for _, p := range pairs {
|
|
if config.IsYamlOnlyKey(p.key) {
|
|
yamlPairs = append(yamlPairs, p)
|
|
} else if p.key == "beads.role" {
|
|
gitPairs = append(gitPairs, p)
|
|
} else {
|
|
dbPairs = append(dbPairs, p)
|
|
}
|
|
}
|
|
|
|
if !forceGitTracked {
|
|
for _, p := range yamlPairs {
|
|
if err := config.CheckSecretKeyGitSafety(p.key); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
for _, p := range yamlPairs {
|
|
var setErr error
|
|
if config.IsUserGlobalKey(p.key) {
|
|
setErr = config.SetUserYamlConfig(p.key, p.value)
|
|
} else {
|
|
setErr = config.SetYamlConfig(p.key, p.value)
|
|
}
|
|
if setErr != nil {
|
|
return HandleError("setting config %s: %v", p.key, setErr)
|
|
}
|
|
}
|
|
|
|
if len(gitPairs) > 0 {
|
|
// set-many is the batch alias for `bd config set`, so it runs on the
|
|
// same role-authority boundary that verb does.
|
|
write, err := newRoleConfigWriter()
|
|
if err != nil {
|
|
return HandleError("setting beads.role in git config: %v", err)
|
|
}
|
|
for _, p := range gitPairs {
|
|
if err := write("beads.role", p.value); err != nil {
|
|
return HandleError("setting %s in git config: %v", p.key, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// SET-MANY IS NOT ON issueops.WorkspaceConfig, and the reason is the
|
|
// property TestProxiedServerConfigSetMany pins: the whole batch is ONE
|
|
// Dolt commit, which is the entire point of the verb ("faster and less
|
|
// noisy than separate calls, especially in CI"). The role writes one
|
|
// setting per call and commits each, so routing this through it would
|
|
// turn a three-key batch into three commits.
|
|
if len(dbPairs) > 0 {
|
|
if usesProxiedServer() {
|
|
keys := make([]string, len(dbPairs))
|
|
values := make([]string, len(dbPairs))
|
|
for i, p := range dbPairs {
|
|
keys[i] = p.key
|
|
values[i] = p.value
|
|
}
|
|
if err := runConfigSetManyProxiedServer(rootCtx, keys, values); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
if err := ensureDirectMode("config set-many requires direct database access"); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
for _, p := range dbPairs {
|
|
if err := store.SetConfig(rootCtx, p.key, p.value); err != nil {
|
|
return HandleError("setting config %s: %v", p.key, err)
|
|
}
|
|
}
|
|
commandDidWrite.Store(true)
|
|
// One scoped commit for the whole batch, not one per key.
|
|
if err := commitConfigWrite(rootCtx, store, "config set-many"); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if jsonOutput {
|
|
results := make([]map[string]string, 0, len(pairs))
|
|
for _, p := range pairs {
|
|
location := "database"
|
|
if config.IsUserGlobalKey(p.key) {
|
|
location = config.UserConfigYamlDisplayPath()
|
|
} else if config.IsYamlOnlyKey(p.key) {
|
|
location = "config.yaml"
|
|
} else if p.key == "beads.role" {
|
|
location = "git config"
|
|
}
|
|
results = append(results, map[string]string{
|
|
"key": p.key,
|
|
"value": p.value,
|
|
"location": location,
|
|
})
|
|
}
|
|
if err := outputJSON(results); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
for _, p := range pairs {
|
|
location := ""
|
|
if config.IsUserGlobalKey(p.key) {
|
|
location = fmt.Sprintf(" (in %s)", config.UserConfigYamlDisplayPath())
|
|
} else if config.IsYamlOnlyKey(p.key) {
|
|
location = " (in config.yaml)"
|
|
} else if p.key == "beads.role" {
|
|
location = " (in git config)"
|
|
}
|
|
fmt.Printf("Set %s = %s%s\n", p.key, p.value, location)
|
|
}
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// recognizedConfigPrefixes lists valid top-level config namespaces.
|
|
// Keys under custom.* are always accepted (user-extensible).
|
|
//
|
|
// Tracker namespaces (jira., linear., github., ado., ...) are NOT listed here:
|
|
// they are derived from the tracker registry at runtime via
|
|
// allRecognizedConfigPrefixes, so the recognizer cannot drift out of sync when
|
|
// a new tracker is added (GH#4427).
|
|
var recognizedConfigPrefixes = []string{
|
|
"export.", "import.", "dolt.", "custom.",
|
|
"status.", "types.", "doctor.suppress.", "routing.", "sync.", "git.",
|
|
"directory.", "repos.", "external_projects.", "validation.",
|
|
"lint.", "hierarchy.", "ai.", "backup.", "federation.", "metrics.",
|
|
"agent.", "claim.", "storage-class.", "versioned-history.",
|
|
}
|
|
|
|
// validateStorageClassConfig validates a storage-class.<type> per-type
|
|
// default at config-set time (Protocol v0.1 C-OQ1: values are validated when
|
|
// set, not discovered broken at create time). The key suffix must name an
|
|
// issue type and the value must be a storage class.
|
|
func validateStorageClassConfig(key, value string) error {
|
|
suffix := strings.TrimPrefix(key, "storage-class.")
|
|
if suffix == "" || strings.Contains(suffix, ".") {
|
|
return fmt.Errorf("invalid key %q: expected storage-class.<issue-type> (e.g. storage-class.event)", key)
|
|
}
|
|
// The key suffix must be a canonical, known issue type: create-time lookup
|
|
// keys on the Normalize()d type (resolveStorageClass), so an alias like
|
|
// storage-class.feat or a typo like storage-class.taks would pass set-time
|
|
// validation and then silently never match — the C-OQ1 failure mode this
|
|
// validator exists to prevent.
|
|
issueType := types.IssueType(suffix)
|
|
if canonical := issueType.Normalize(); canonical != issueType {
|
|
return fmt.Errorf("invalid key %q: %q is an alias of %q, and create-time lookup uses the canonical type; set storage-class.%s instead", key, suffix, canonical, canonical)
|
|
}
|
|
customTypes, err := resolveWorkspaceCustomTypes(rootCtx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !issueType.IsValidWithCustom(customTypes) {
|
|
return fmt.Errorf("invalid key %q: unknown issue type %q (use a built-in type, or add it to types.custom first)", key, suffix)
|
|
}
|
|
if _, err := types.ParseStorageClass(value); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// allRecognizedConfigPrefixes returns the static namespaces plus the prefix of
|
|
// every registered tracker ("ado.", "jira.", ...). Deriving tracker prefixes
|
|
// from the registry keeps config-key recognition in sync with the set of
|
|
// trackers compiled into bd instead of a hand-maintained allowlist (GH#4427).
|
|
func allRecognizedConfigPrefixes() []string {
|
|
names := tracker.List()
|
|
prefixes := make([]string, 0, len(recognizedConfigPrefixes)+len(names))
|
|
prefixes = append(prefixes, recognizedConfigPrefixes...)
|
|
for _, name := range names {
|
|
prefixes = append(prefixes, name+".")
|
|
}
|
|
return prefixes
|
|
}
|
|
|
|
// recognizedConfigKeys lists valid non-namespaced config keys.
|
|
var recognizedConfigKeys = map[string]bool{
|
|
"no-db": true, "json": true, "db": true, "actor": true,
|
|
"identity": true, "no-push": true, "no-git-ops": true,
|
|
"node_id": true, // replica identity for the lease guard (read from yaml/env, never the DB)
|
|
"create.require-description": true, "beads.role": true,
|
|
"auto_compact_enabled": true, "schema_version": true,
|
|
"output.title-length": true,
|
|
"prime.max-memories": true, "prime.max-memory-chars": true,
|
|
"prime.disabled": true,
|
|
// Opt-in ceiling on the persistent-memory corpus, enforced by `bd
|
|
// remember` (0 = off). Yaml-only for the same reason the prime caps are:
|
|
// it is read through viper, so a DB-backed write would never be seen.
|
|
"memories.budget-chars": true,
|
|
// The events-journal family. All four are startup settings that land in
|
|
// config.yaml (config.YamlOnlyKeys), and every one of them is documented as
|
|
// a `bd config set` invocation — including the auto-prune opt-out, where an
|
|
// unrecognized-key warning next to a command that DID take effect reads as
|
|
// "that did not work" on the one setting whose whole purpose is to stop bd
|
|
// deleting records.
|
|
"events-journal": true, "events-journal-auto-prune": true,
|
|
"events-journal-retain-days": true, "events-journal-retain-rows": true,
|
|
}
|
|
|
|
func isRecognizedConfigKey(key string) bool {
|
|
if recognizedConfigKeys[key] {
|
|
return true
|
|
}
|
|
for _, prefix := range allRecognizedConfigPrefixes() {
|
|
if strings.HasPrefix(key, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// rejectProtectedConfigKey rejects keys that are owned by a dedicated
|
|
// lifecycle command (init/rename) rather than 'bd config set'. The canonical
|
|
// example is issue_prefix: 'bd create' reads YAML "issue-prefix"
|
|
// then DB "issue_prefix", while 'bd config set' would land in DB
|
|
// "issue-prefix" — a third key no reader consults. Accepting either the
|
|
// dash or underscore form silently produces a write that looks like it
|
|
// succeeded but is never visible to 'bd create'. Reject both and point the
|
|
// user at the right command.
|
|
func rejectProtectedConfigKey(key string) (string, bool) {
|
|
switch key {
|
|
case "issue_prefix", "issue-prefix":
|
|
return "Error: issue_prefix cannot be set via 'bd config set'.\n" +
|
|
" - New project: bd init --prefix <prefix>\n" +
|
|
" - Fresh clone: bd bootstrap\n" +
|
|
" - Rename existing: bd rename-prefix <new-prefix>", true
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// suggestConfigKey tries to find a close match for a mistyped key by checking
|
|
// if the key's prefix is a known prefix with a typo. Returns empty string if
|
|
// no suggestion can be made.
|
|
func suggestConfigKey(key string) string {
|
|
parts := strings.SplitN(key, ".", 2)
|
|
if len(parts) < 2 {
|
|
return ""
|
|
}
|
|
prefix := parts[0] + "."
|
|
|
|
bestMatch := ""
|
|
bestDist := 3 // max edit distance to suggest
|
|
for _, known := range allRecognizedConfigPrefixes() {
|
|
knownPrefix := strings.TrimSuffix(known, ".")
|
|
d := levenshteinDistance(parts[0], knownPrefix)
|
|
if d > 0 && d < bestDist {
|
|
bestDist = d
|
|
bestMatch = known + parts[1]
|
|
}
|
|
}
|
|
_ = prefix
|
|
return bestMatch
|
|
}
|
|
|
|
func levenshteinDistance(a, b string) int {
|
|
la, lb := len(a), len(b)
|
|
if la == 0 {
|
|
return lb
|
|
}
|
|
if lb == 0 {
|
|
return la
|
|
}
|
|
|
|
prev := make([]int, lb+1)
|
|
curr := make([]int, lb+1)
|
|
for j := range prev {
|
|
prev[j] = j
|
|
}
|
|
|
|
for i := 1; i <= la; i++ {
|
|
curr[0] = i
|
|
for j := 1; j <= lb; j++ {
|
|
cost := 1
|
|
if a[i-1] == b[j-1] {
|
|
cost = 0
|
|
}
|
|
curr[j] = min(curr[j-1]+1, min(prev[j]+1, prev[j-1]+cost))
|
|
}
|
|
prev, curr = curr, prev
|
|
}
|
|
return prev[lb]
|
|
}
|
|
|
|
func init() {
|
|
configSetCmd.Flags().BoolVar(&forceGitTracked, "force-git-tracked", false, "Allow writing secret keys to git-tracked config files (use with caution)")
|
|
configSetManyCmd.Flags().BoolVar(&forceGitTracked, "force-git-tracked", false, "Allow writing secret keys to git-tracked config files (use with caution)")
|
|
|
|
configCmd.AddCommand(configSetCmd)
|
|
configCmd.AddCommand(configSetManyCmd)
|
|
configCmd.AddCommand(configGetCmd)
|
|
configCmd.AddCommand(configListCmd)
|
|
configCmd.AddCommand(configUnsetCmd)
|
|
configCmd.AddCommand(configValidateCmd)
|
|
rootCmd.AddCommand(configCmd)
|
|
}
|