Commit graph

4,719 commits

Author SHA1 Message Date
ecuthiell
6899813df6
fix(preflight): share checkout lint authority (#5780)
* fix(preflight): share checkout lint authority

Move the Beads repository's native and Windows non-CGO lint policy into a checkout-owned Go driver. The supported Make/Bash wrapper and bd preflight now execute that same authority, while generic Go repositories retain their direct lint contract and formatting is rooted at the detected project.

Fixes #5300.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* docs(lint): clarify shared driver scope and timeout limits

Address PR #5780 review 5191123668. Document existing inherited-tag semantics and distinguish the wrapper/preflight driver from standalone workflow and pre-commit callers.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(lint): prefer the selected Windows Go toolchain (#6865)

Keep per-pass toolchain requests and deadlines while avoiding the extra auto-selection launcher under the linter. Nonstandard SDKs retain their original PATH.

Agent-Signature: codex-tui-gpt-6-astra-max on behalf of Ewen Cuthiell

* fix(lint): retain PATH for SDK directories containing separators (#6865)

Agent-Signature: codex-tui-gpt-6-astra-max on behalf of Ewen Cuthiell

* test(preflight): declare lint fixture executable for Bazel (#5300)

Agent-Signature: codex-tui-gpt-6-astra-max on behalf of Ewen Cuthiell

* fix(bazel): keep cmd/bd/testdata out of gazelle's package scan

PR #5780 adds the compilable fixture cmd/bd/testdata/preflight-go.go. Left to
itself gazelle generates a BUILD.bazel for cmd/bd/testdata, which makes it its
own package and then (a) empties cmd/bd's data = glob(["testdata/**"]) under the
default allow_empty = False and (b) puts testdata/preflight-go.go across a
package boundary from the preflight_go_fixture target that lists it.

bazel.yml's "BUILD files in sync" step runs `make bazel-sync` and fails on any
resulting drift, and fork PRs always run that job, so this was a live red whose
prescribed remedy ("commit the result") would have broken the build further.
Exclude the directory instead, and take gazelle's ordering for the data list.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(preflight): bound the lint deadline and report each check's scope

Review iteration 1 for PR #5780. Synthesis and scorecard both approve (975/1000,
no blocker or major), so this addresses non-gating findings only.

Finding 4 (Resource Lifecycle) - the 13-minute deadline could not bound the call
it guards. CombinedOutput collects through a pipe every descendant inherits, so
Wait kept blocking on a surviving golangci-lint after the context killed the
direct `go run` child. Measured on the same process shape (direct child killed at
1s, descendant holding the pipe for 8s): without WaitDelay the call returned in
8.00s, with WaitDelay in 1.50s. Sets cmd.WaitDelay so the deadline is a real
bound and the "lint check exceeded" line can actually print.

Also gates that line on err != nil, which retires the claude lane's nit (a): a
child that exits cleanly as the deadline fires is a pass, not a timeout. Measured
at the crossover, 68 of 300 passing runs would have carried a false "exceeded"
line; 0 after the gate.

Finding 1 (Change Impact) and nit 7 (Debuggability), one remedy - the PR re-roots
lint and fmt at preflightProjectRoot() but leaves runTestCheck in the caller's
cwd, so a --check run from a subdirectory mixes a repo-wide verdict with a
subtree-only one "with nothing in the output distinguishing them", and the
reported command is only reproducible from the root. CheckResult now carries the
directory each check resolved to, and the report prints it.

Took the synthesis's second arm (state the scope split) rather than re-rooting
runTestCheck, because re-rooting is a behaviour change neither lane priced: it
widens a subdirectory user's test run from 5 packages to 128, including every
Dolt-dependent package, on a repo whose full test gate the PR body already
discloses as red. The stated hazard is that the scopes are indistinguishable,
which reporting the directory discharges directly.

Finding 2 (Architectural Consistency), second clause - adds
TestBuildFlagsContractMatchesShellSource, which parses .buildflags and pins the
driver constants to it. The existing mirror test asserts today's values from the
Go side only, so the files could drift silently; buildEnvironment overrides
rather than merges -tags, so a tag added to .buildflags alone would be dropped
with every test still green. Each of the three legs was mutation-proved to red.

Declined, with the measurements that decided it:

- Finding 2's first clause (route the key comparisons through
  internal/execenv.KeyEqualForOS). The two are provably equivalent today -
  execenv's keyIdentityForWindows is strings.ToLower for the same documented
  reason - so this is de-duplication, not a defect, and the hazard it closes
  (os/exec key-identity semantics changing) is far less live than the
  .buildflags drift the second clause pins. The faithful swap means threading
  goos through five driver functions and ~27 test call sites in this PR's
  centerpiece file, and it would put a non-stdlib dependency into pr-lint_lib,
  which the binary currently does not have. Worth doing on its own footing, not
  inside a non-gating cleanup.

- Nit 6 (parse GOFLAGS into fields instead of a substring test). .buildflags:22
  guards its own append with `!= *gms_pure_go*`, a substring test, and the Go
  code is a deliberate mirror of it. Making only the Go side stricter would
  manufacture exactly the drift finding 2 warns about: on
  GOFLAGS=-tags=gms_pure_go_x the shell would skip its append while the driver
  performed one. The fix belongs to .buildflags and the driver together, and
  .buildflags is outside this PR. The new mirror test now pins that agreement.

- Nit 5 (probe golangci-lint as well as `go`). The claude lane examined the
  LookPath target change and recorded it as deliberate, with the driver's own
  missing-linter error as the mitigation. The suggested alternative - have the
  driver emit preflight's `--skip-lint` hint - puts a bd-specific flag into a
  driver that CI also invokes, where that advice is wrong.

- Finding 3 (two false PR-body claims). Correcting the body is outward-facing
  and belongs to finalize; stamped for it. Swept the in-tree copies: the PR's own
  LINTING.md sentence "Toolchain requests, formatting, and lint deadlines are
  unchanged" is scoped to the Windows SDK-preference paragraph it sits in and is
  true there, so it is graded rather than repaired. CHANGELOG.md contains no
  pr-lint entry, so the remedy's CHANGELOG half has no target in this PR.

Validation: go build, go vet and gofmt clean on the changed packages;
./scripts/pr-lint/ 12 pass / 2 Windows-only skip; ./scripts/prlintmake/ pass;
cmd/bd preflight selector pass; scripts/check-doc-freshness.sh PASSED;
make bazel-sync idempotent and bazel test //scripts/pr-lint:pr-lint_test PASSED.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(prlintmake): inject the pr-lint wrapper's gofmt shim through GOFMT

The merge with #6294 (be-gx8) left runPRLintWrapper relying on a
code path #6294 made deliberately loud. The helper put its gofmt shim
on PATH. Since #6294, fmt-check.sh resolves gofmt through
scripts/ci/gofmt-bin.sh, which ignores a PATH gofmt by design.

Both TestPRLintWrapper* tests still passed, but only via the
resolver's fallback. The go shim answers `go env GOVERSION` and
`go env GOROOT` with nothing, so gofmt-bin.sh warns "could not resolve
a gofmt from go.mod's go1.26.7 toolchain" and falls back to whatever
gofmt is first on PATH, which happened to be the shim. With GOFMT set
in the environment, which is #6294's documented override, the
resolver uses that value instead. Both tests then fail: exit status
127 from fmt-check.sh, and a missing aggregate failure diagnostic
because pr-lint.sh stops before `go run`. At the pre-merge head
(7f37ba5165) the same ambient GOFMT=/nonexistent run passed all 5
tests.

Pass the shim through GOFMT, as main's runFmtCheck does, and keep it
off PATH so only the go shim is found there. gofmt-bin.sh now returns
the override immediately, and the go shim sees only `version <shim>`
and `run ... ./scripts/pr-lint`. Both wrapper assertions, on the
driver arguments and on the failure diagnostic, are unchanged.

go test ./scripts/prlintmake/: 9/9 pass by default and 9/9 pass with
GOFMT=/nonexistent in the environment. Before this change the second
run was 7/9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 22:41:55 -07:00
JennyMink
2704d8a954
fix(list): union repeated --status/--state/--id; refuse repeated --type/--assignee (#5739)
* fix(list): union repeated --status/--state/--id; refuse repeated --type/--assignee

bd list's filter flags were plain pflag strings, so a repeated flag silently
kept only the last value: `--status open --status closed --status pinned`
filtered to pinned alone. A 477-issue census answered over 3 rows and nothing
in the output distinguished the narrowed answer from a correct one — worse for
scripts than humans, since a script pipes the clean-looking count onward. The
--status help text already warned about this, but a doc note does not reach a
script that already ran.

The fix follows what each filter's downstream shape permits:

- --status, --state, --id feed comma-separated OR sets, so repeats now union
  into exactly the comma form: `--status open --status closed` builds
  "open,closed". Single values and the comma form parse byte-identically to
  before.
- --type and --assignee are single-valued all the way down. Joining --type
  would surface as "invalid issue type: bug,epic" (loud but misdirected);
  joining --assignee would exact-match nobody and return an empty result that
  reads as a clean answer — the same defect in a new spelling. A repeat of
  either now refuses at parse time, naming the flag.

Two invariants shape the value types. Setting the empty string fully resets
them, because `bd children` borrows listCmd's status flag with Set("all") and
a deferred Set(""). And gatherListInput clears them after copying values out,
because pflag values persist across in-process Execute() calls (the cmd/bd
test binary, library embedders) and an accumulating value would otherwise
leak one command's filter into the next.

Tests cover the union, the refusal (long and shorthand spellings), the
unchanged single/comma forms, the empty-string reset, and the cross-parse
isolation. All four repeated-flag tests fail against the previous flag
registrations.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(list): dedupe repeated filter values; lower Changed on reset (review follow-ups for #5739)

Two nits from review, both on cmd/bd/list_filter_flags.go:

- unionStringFlag.Set now dedupes per token, so `--status open --status open`
  and `--status open --status open,closed --status closed` both build
  "open,closed" instead of "open,open,closed,closed". Harmless inside the
  IN (...) either way, but the joined value is what --json callers and error
  messages echo back.

- resetListFilterFlags now lowers pflag's Changed bit on the five flags as
  well as clearing the values, so it is a full reset rather than a half one;
  the test helper that cleared Changed by hand is gone. The reset takes the
  flag set as an argument instead of reading listCmd, because listCmd's
  initializer reaches it via runListCore -> gatherListInput and referring
  back would be an initialization cycle.

Tests: TestListRepeatedStatusDedupes and TestResetListFilterFlagsLowersChanged
cover the two changes; the existing eight are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BDokjpuq569c49NYTwcBPY

* fix(bazel): enumerate list_filter_flags{,_test}.go in cmd/bd srcs

This PR adds cmd/bd/list_filter_flags.go and cmd/bd/list_filter_flags_test.go,
but cmd/bd/BUILD.bazel carries explicit go_library/go_test srcs lists rather
than globs. That file is absent at this branch's merge base and was added on
main during the 177-commit advance, so the contributor's history never had it
to update.

Without the two entries, `bazel build --config=pure //cmd/bd:bd
//cmd/bd:bd_test` fails to compile bd_for_tests.a with six undefined symbols:
list.go:409,410,413,414,422 for the five list*Flag vars and list_input.go:48
for resetListFilterFlags.

Regenerated with `make bazel-sync` (gazelle): +2 srcs lines, no deps churn, and
a second sync is a no-op. `make bazel-sync-check` cannot see this class --
tools/bazel/go_srcs.py --check validates only the go_srcs filegroup globs --
but bazel.yml's sync step diffs the full `make bazel-sync` output and would
report the tree out of sync.

Validated: `bazel build --config=pure //cmd/bd:bd //cmd/bd:bd_test` exits 0
(exits 1 without this change), and //cmd/bd:bd_test runs the PR's 10 new tests
green (test.xml: 10 testcases, 0 failures, 0 errors).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* review: pin the three unpinned flag arms; correct the CHANGELOG claims

Maintainer review fixes for #5739 (review-loop iteration 1). The synthesis was
`approve` with zero blockers and zero majors, so every item here is non-gating;
applied because each is confined to this PR's own files, cheap, and carries no
behaviour change. A new commit rather than an amend: the existing maintainer
commit `21d287f4df` is the pre-review lane's BUILD.bazel drift repair, not a
review fixup.

Test Evidence Quality (minor): three reachable arms of the new registration had
no coverage. Added `TestListStateAndStatusArms` with a subtest each for the
hidden `--state` alias unioning like `--status`; a union containing `all` being
refused downstream rather than narrowed; and `--status` outranking `--state`
when both are given, which is `gatherListInput`'s documented fallback order.
Mutation-proved by making `unionStringFlag.Set` last-wins (the pre-PR
behaviour): the existing `TestListRepeatedStatusUnions` control and the first
two new subtests all red, while `--status outranks --state` stays green because
it pins the fallback order rather than the union - orthogonal, not vacuous.
The `all` arm is the interesting one: under last-wins the repeat kept only
`open`, so the `status "all" cannot be combined` guard was never reachable.

Release Safety (nit): the CHANGELOG's equivalence claim was one-directional and
omitted that third arm. Softened to "accumulate (duplicates collapse) instead of
overwriting" and added the clause that `--status all --status open` is refused
rather than narrowed.

Debuggability (nit), CHANGELOG arm: the quoted refusal was the inner error only.
pflag wraps it, so users actually see `invalid argument "epic" for "-t, --type"
flag: --type given more than once (already "bug"); pass a single value`, which is
now what the entry quotes - probed from a real `ParseFlags` call, not inferred.
Took this arm rather than dropping the `--%s` prefix from the inner error, since
that one changes a user-visible message and the reviewer offered it as the
alternative.

Architectural Consistency (nit): replaced the hand-rolled `slicesContains` with
stdlib `slices.Contains` and deleted the helper; `slices` is already used
elsewhere in this package.

Deliberately not done: the Change Impact minor's sibling-surface sweep, which
the finding itself scopes as "no change in this PR" plus a follow-up bead.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: jwe <otaciaproject@gmail.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 21:32:42 -07:00
Julian Knutsen
dba70de281
fix(federation): actionable error when peer credentials cannot be decrypted (#6995)
* fix(embeddeddolt): use stored peer credentials for federation sync

bd federation add-peer promises stored credentials are used automatically
when syncing, but the embedded Fetch/PushTo/PullFrom paths read only the
DOLT_REMOTE_USER environment variable, so first sync against any
authenticated Dolt server presented the wrong identity. This is the
peer-path remainder of the class fixed for default remotes in #2543.

withPeerAuth mirrors server mode's withPeerCredentials: peer-store lookup
first, environment fallback for unknown remotes and credential-free peers
(federation sync iterates every dolt remote, so non-peer remotes must
keep their behavior). Stored credentials override the process-wide
DOLT_REMOTE_USER/DOLT_REMOTE_PASSWORD pair as a unit under a
federationEnvMutex, mirroring package dolt: the in-process Dolt engine
reads them from the process environment, so the override is serialized
and both variables are restored (or re-unset) afterward, including on
callback failure. A stored empty field unsets its variable rather than
inheriting an ambient value.

Fixes #5080

Agent-Signature: claude-code-claude-fable-5-unknown-reasoning on behalf of Michael Pursifull

* docs(embeddeddolt): clarify federationEnvMutex is separate from package dolt's lock

Review nit on #5085: the 'mirroring' phrasing read as if the two
packages shared one mutex. State explicitly that they are separate
locks and why per-package serialization suffices.

* fix(federation): actionable error when peer credentials cannot be decrypted

A database pulled to a second machine carries federation_peers rows
its local .beads-credential-key cannot decrypt, and every peer
operation died with a raw cipher error while bd federation status
blamed the network (Unreachable:). The failure semantics were right
(fail closed, matching server mode); the message said nothing about
the machine-local key or the fix.

Add storage.ErrCredentialKeyMismatch plus a shared wording helper
CredentialKeyMismatchError naming the key file as context and the
remediation (re-run bd federation add-peer on this machine). Both
backends wrap their decrypt failures with it: embeddeddolt at its
single decrypt funnel, dolt at its two read paths. GetFederationPeer
wraps now name the peer. bd federation status classifies the sentinel
with errors.Is and prints Local credential error instead of
Unreachable; the --json shape is unchanged and now pinned by test.

When the error fires is unchanged: same call sites, same fail-closed
semantics, no fallback to ambient credentials.

Tests pin the decrypt-failure branch in both backends (embeddeddolt
against a real store with a rotated key, dolt via sqlmock) and the
status classification end to end in the gated CLI harness.

Refs #5080

* fix(embeddeddolt): classify short ciphertext as credential-key mismatch

A stored peer password blob shorter than the GCM nonce returned a bare
'ciphertext too short' error, bypassing CredentialKeyMismatchError, so
federation status read that local corruption as an unreachable peer.
Route the branch through the same sentinel as a failed GCM open; the
remediation (re-add the peer on this machine) is identical.

Adds a short-ciphertext regression at the decrypt funnel.

Refs: gastownhall/beads#5214 (review, gap 1)

* fix(embeddeddolt): bind stored credentials to the remote URL; serialize env fallbacks

Two fixes to the shared withPeerAuth seam from the consolidation review:

- Stored peer credentials are now bound to the peer's canonical remote
  URL, not only to a matching remote name. AddRemoteIfNotExists keeps
  an existing same-name remote regardless of its URL, so a redirected
  remote could receive the stored password. withPeerAuth now verifies
  the live dolt_remotes URL against the peer row before any credential
  is installed, failing closed on divergence and on a missing remote.

- The plain-remote and empty-credential fallback callbacks now run
  under federationEnvMutex too. They previously called remoteAuthUser()
  and the operation itself outside the lock, so a fallback operation
  could observe a concurrent stored-peer operation's temporarily
  installed DOLT_REMOTE_USER/DOLT_REMOTE_PASSWORD pair.

Adds three regressions: diverged-URL fail-closed, missing-remote
fail-closed, and env-fallback-does-not-observe-peer-credentials.

Refs: gastownhall/beads#5085 (review)

* style(dolt): use US spelling in the decrypt-funnel comments

The repo's misspell linter rejects 'Labelling' and 'labelled'. Comment
text only; no behavior change.

Refs: gastownhall/beads#5214 (CI)

* review: name the resolved credential-key path in the mismatch error

Maintainer review fixup for PR #5214 (adopt-pr iteration 1). Addresses the one
minor and the one nit from the review synthesis; both reviewers found 0 blockers
and 0 majors and the quality scorecard is approve (898/850).

Minor (Debuggability & Operability). All three CredentialKeyMismatchError call
sites passed the bare const credentialKeyFile, so the message claimed "the key
file .beads-credential-key is machine-local" without saying where it is. On the
dolt backend that basename is genuinely ambiguous: initCredentialKey resolves it
against s.beadsDir and falls back to the legacy s.dbPath as a transparent
migration, so during the migration window two files with that name can exist
carrying different keys. Pass filepath.Join(s.beadsDir, credentialKeyFile)
instead, at dolt/credentials.go and both embeddeddolt/federation.go sites. No
signature change: the parameter was already named keyFile and its doc comment
already describes it as machine-local.

beadsDir is provably non-empty at all three sites in production, verified in
source rather than assumed: dolt only reaches the funnel with a non-nil key, and
initCredentialKey leaves the key nil when beadsDir is empty; embeddeddolt's
ensureCredentialKey errors out when it is empty.

This lengthens a message the author pre-declared as a judgment call. The
synthesis adjudicated that carve-out deliberately: it covers the message's
wording and its single-line form, not which file the text identifies.

Nit (Test Evidence Quality). dolt's withPeerCredentials is the seam that carries
the sentinel into `bd federation status` on the default backend and had no
fails-closed pin, unlike its embedded twin TestWithPeerAuth_KeyMismatchFailsClosed.
Added one subtest on the existing sqlmock harness asserting the callback does not
run and the sentinel survives the seam's own wrap.

Both pins were proven non-vacuous by mutation, not assumed:
- Reverting the three call sites to the bare const reds all three dolt subtests
  and all three embeddeddolt tests, with the original bare-basename text in the
  diff output.
- Making withPeerCredentials swallow the decrypt error reds only the new subtest,
  on exactly the two properties the nit named (callback ran; no failure).

The dolt test needed beadsDir set on its hand-built store: filepath.Join("",
credentialKeyFile) is the bare basename, so with beadsDir left empty the
resolved-path assertion would have passed vacuously. The embeddeddolt pin's
package-level const became a function of the store for the same reason — its
store has a real temp beadsDir, so the clause now pins the resolved path.

Validation: go vet rc=0 on all three packages; internal/storage, dolt
(3 tests incl. both negative/narrowing tests) and embeddeddolt (3 credential
tests) green; cmd/bd TestEmbeddedFederation 12/12 green including the PR's own
status_credential_key_mismatch e2e subtest. make bazel-sync-check rc=0 with zero
tracked drift — no new files and zero import changes, so no BUILD srcs or deps
can move.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Michael Pursifull <mike@arcaven.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-09-30 20:29:57 -07:00
Vishnu J
892a438f1e
fix(prime): detect git remote from CWD, not BEADS_DIR context (#5139)
* fix(prime): detect git remote from CWD, not BEADS_DIR context

primeHasGitRemote and isEphemeralBranch used GetRepoContext(), which
validates BEADS_DIR against isPathInSafeBoundary. Cross-home agent
sandboxes mount host workspaces under another account path; BEADS_DIR
validation fails and was misreported as "no git remote" even when
`git remote` in the process CWD succeeds.

Probe git in the process CWD (and explicit dir helper) independently of
RepoContext / BEADS_DIR. SEC-003 boundary on BEADS_DIR is unchanged.

Fixes #4927

* test(prime): drop inverted !cgo constraint so the regression test actually runs

The new test carried //go:build !cgo while all 255 sibling test files in
cmd/bd use //go:build cgo, so under the default cgo build the test was
excluded entirely and never exercised the fix it was written for.
Removing the constraint lets it run in both modes.

* test(prime): make the git-remote test hit the boundary it claims to, unify gitDirHasRemote

Review follow-up on #4927 (maphew):

The poison BEADS_DIR value didn't exist on disk, so it tripped
FindBeadsDir()=="" (context.go:107) rather than isPathInSafeBoundary
(context.go:112), even though the test comment implied it exercised the
boundary check. Both funnel into the same err!=nil->false bug so the old
test was a fair proxy, but it didn't test what it said. Seed a real
directory under a rejected prefix (/var/tmp) so BEADS_DIR actually reaches
isPathInSafeBoundary, and add a second case for the FindBeadsDir()=="" path
so both RepoContext failure modes are covered and asserted against
directly via beads.GetRepoContext().

gitDirHasRemote had no production caller — prime only went through
gitCWDHasRemote, so the helper carrying the test's assertions wasn't the
one prime used. Make gitCWDHasRemote delegate to gitDirHasRemote("") so
there is one implementation and the test exercises the real production
path.

* test(prime): scope the unsafe-location subcase to Unix

SEC-003's unsafePrefixes are hardcoded forward-slash literals matched
via strings.HasPrefix. On Windows, filepath.Join renders the fixture
path with backslashes, so the prefix never matches and the assertion
would fail with err == nil. Move it into its own subtest and skip on
GOOS=="windows" rather than deleting or weakening it, so Case 2 (the
nonexistent-BEADS_DIR path, which doesn't touch unsafePrefixes) still
runs on every platform.

gitDirHasRemote / gitCWDHasRemote / primeHasGitRemote are untouched.

* test(prime): delete obsolete unsafe_location_rejected subtest

Upstream added an ALLOW carve-out for /var/tmp in isPathInSafeBoundary
(af076b628, #5028) after this test was written. resolvedPathWithinRoot
resolves both sides, so the carve-out now admits the poison dir on all
platforms and the subtest's premise (that /var/tmp is boundary-rejected)
is false on current main. Delete it rather than retarget at another
unsafe prefix -- none are writable in CI, so a retargeted assertion
would silently no-op via the existing t.Skipf fallback.

The CWD-based checks are unaffected and stay unconditional; update the
surrounding comments since they described the fixture as "a
boundary-rejected BEADS_DIR", which is no longer accurate anywhere in
the file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(bazel): sync cmd/bd BUILD.bazel srcs for prime_git_remote_test.go

Maintainer fixup during PR adoption. cmd/bd/BUILD.bazel enumerates an
explicit go_test srcs list, so the new prime_git_remote_test.go added by
this PR was not compiled into //cmd/bd:bd_test. bazel.yml (armed on this
fork PR: FORK=true => mode=local, not skip) runs make bazel-sync and
exit 1s on any resulting drift, and bazel-pure builds and runs
//cmd/bd:bd_test.

This hunk is the verbatim output of make bazel-sync (bazel run //:gazelle).

Verified: bazel build --config=pure //cmd/bd:bd_test exit 0 both ways;
bd_test -test.list went 1771 -> 1772 entries with
TestGitDirHasRemote_IndependentOfBeadsDir going 0 -> 1 and control
TestOutputContextFunction present in both arms. make bazel-sync is
idempotent (2nd run byte-identical). make bazel-sync-check exits 0 in
both states, so it cannot see this class.

* review(prime): address the three non-gating findings from PR review

Maintainer fixup for PR #5139 review iteration 1. The synthesis and the
quality scorecard both approve with no blocker or major findings; these are
the three non-gating maintainability items, all in scaffolding this PR
itself introduced.

- prime.go: delete the false clause in gitCWDHasRemote's doc comment ("so
  the production path and the test-driven path share one implementation").
  The pair has zero production callers -- the production probes build their
  own command in primeGitCmd -- so the comment now records that instead. Per
  the synthesis, only the false clause is removed: the following sentence is
  accurate, and the fallback is deliberately NOT routed through the helper
  merely to make the old sentence true.
- prime_git_remote_test.go: rename to TestPrimeGitProbes_IndependentOfBeadsDir
  so the test names its real subject, and pin isEphemeralBranch -- the second
  probe this fix repairs, and the source of the user-visible "ephemeral
  branch" half of GH#4927 -- which previously had zero references in the file.
- prime.go: record that primeGitCmd's error result is always nil today and is
  retained for future callers, so the now-unreachable err != nil arms are
  documented rather than mistaken for live error handling.

The isEphemeralBranch pin asserts BOTH polarities under the same poisoned
BEADS_DIR, which is what the codex lane asked for: with a remote but no
upstream the branch really is ephemeral, and after a purely local upstream is
configured the same probe must flip. The two assertions differ by exactly the
two upstream-setup lines, so the pair is its own non-vacuity proof.

On the test finding I took the harm rather than the literal means. The
prescription offered "drop or retarget the gitDirHasRemote/gitCWDHasRemote
assertions", but dropping them would falsify the very sentence the first
finding asks to preserve ("the BEADS_DIR-independent primitive the GH#4927
regression test drives directly"). They are instead kept explicitly as the
fixture/oracle checks -- the alternative the review's own pre-merge checklist
blesses -- and the unpinned-coverage harm is discharged by the new
isEphemeralBranch assertions.

The probe assertions move from t.Fatal to t.Error so a regression in one
probe cannot mask another's. That is what makes the new pin measurable:
reverting primeGitCmd's GetRepoContext() fallback to "return nil, err" (go
build rc 0, so the arm is not vacuous) reds both primeHasGitRemote and the
upstream-configured isEphemeralBranch assertion, while gitCWDHasRemote and
the no-upstream control stay green -- confirming the oracle bypasses the fix,
and that the new assertion does not.

The rename supersedes the test name quoted in the preceding bazel-sync
commit. BUILD.bazel is untouched because the filename is unchanged, and
bd_test -test.list still holds 1772 entries with the new name present once,
the old name absent, and control TestOutputContextFunction present.

Verified: gofmt, go vet ./cmd/bd/, git diff --check, make bazel-sync (rc 0,
no drift), bazel build --config=pure //cmd/bd:bd_test (rc 0), and go test
./cmd/bd/ over the renamed test plus the prime/backup_auto suites that stub
the probe vars.

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 20:27:21 -07:00
Stephanie Jarmak
12b19a6df7
feat(dep): detect cycles through tracks edges (#6148)
* feat(dep): teach bd dep cycles to traverse tracks edges (gc-818bx)

Adds DetectCyclesRequest.IncludeTracks and a CanonicalMixedCyclePaths
walk so a molecule-root deadlock closing through a tracks edge (root
--blocks--> its own entry step, step --tracks--> root) is detectable,
while a cycle made entirely of tracks edges stays silent by
construction (guards against the PR #4933 false-positive regression).

Wired end to end: public issueops.DetectCyclesRequest -> pure
CanonicalMixedCyclePaths/AppendMixedCycleGraphInTx ->
DetectCycleReportInTx -> dolt/embeddeddolt/uow-domain transactional
wrappers -> `bd dep cycles --include-tracks`. Default request behavior
is unchanged (byte-identical code path when IncludeTracks is false).

Tests: pure-function unit tests for the new DFS variant (rotation,
parallel-edge dedup, self-loops, map-order determinism); conformance
cases against both dolt and embeddeddolt real backends plus the uow
provider (RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop,
RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape, and an added
DepTracks case in RunCycleDetectorFollowsOnlyBlockingEdges pinning the
default's exclusion); CLI-level flag registration and threading tests.

Scope: fix candidate 3 only, per gascity-pl's 2026-08-10 scope-narrowing
comment on gc-818bx (candidates 1/2 addressed upstream by gastownhall/
gascity PR #5202).

* fix(dep): find mixed cycles by SCC instead of single-pass DFS (gc-818bx)

CanonicalMixedCyclePaths could report no cycle for a graph that has a
qualifying one. A single global visited/onPath set only detects a back
edge to a node still on the active recursion stack, so a tracks-only
loop that fully closes and unwinds first (a->b->a) leaves b marked
visited-but-off-path by the time a scheduling edge into the same
component (a->c->b) is examined, and the c->b return edge is invisible
to the DFS.

Every internal edge of a strongly connected component lies on some
cycle within it, so replace the DFS with Tarjan's algorithm: find each
SCC, and for any SCC containing a scheduling edge, walk a deterministic
BFS return path back to that edge's source. Nodes, adjacency, SCC
membership, the chosen edge, and the return path are all sorted so the
result stays a pure function of the graph, matching the existing
determinism guarantee.

Adds the counterexample from exact-head review: a--tracks-->b,
b--tracks-->a, a--blocks-->c, c--tracks-->b, which the prior
implementation reported as acyclic despite the qualifying a->c->b->a
cycle.

* fix(dep): fail loudly if SCC path invariant breaks (gc-zo8a7)

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of sjarmak

* fix(dep): keep every default cycle in the --include-tracks report

CanonicalMixedCyclePaths emitted one cycle per strongly connected
component, so a tracks edge joining two separate blocks-only deadlocks
collapsed them into one reported cycle and --include-tracks could report
fewer cycles than the default walk.

The widened report is now the union of the default depth-first walk on the
scheduling-only subgraph and, for each blocks/conditional-blocks edge
inside a component of the widened graph, that edge closed by its shortest
return path over either edge type. The first set is the default report by
construction; the second adds cycles that close through tracks edges. Every
reported cycle still contains a scheduling edge, so tracks-only loops stay
out. The report holds at most one cycle per internal scheduling edge plus
the default cycles.

A missing return path inside a component is an invariant breach; it now
returns an error through DetectCycles instead of panicking.

* test(dep): pin tracks edge direction in the cycle detector contract

A two-node cycle reads the same under edge reversal, so the existing
IncludeTracks cases could not tell a walk that follows issue_id ->
depends_on_id from one that follows the reverse. The new three-node case
seeds a -> c (tracks), c -> b (blocks), b -> a (tracks), whose reported
path is a, c, b and becomes a, b, c if the edges are reversed.

Also refresh the cycledetector.go line citations this branch shifted.

* perf(dep): share one return-path search per target in the --include-tracks report

CanonicalMixedCyclePaths ran one breadth-first search per scheduling edge
inside a component, O(E(V+E)). On a dense tangle E grows with the square of
V, so the report grew with the fourth power of the component size.

Group the component's scheduling edges by target and close every edge into a
target from one shortestPathTree rooted there, confined to the component.
closeMixedCycle now reads the return path out of that tree and still returns
an error, never loops, when the tree does not reach the edge's source.

TestShortestPathTreeClosesEachEdgeAsAPerEdgeSearchDid checks over generated
graphs that each edge closes to the cycle reachPath produced for it alone,
ties included. BenchmarkCanonicalMixedCyclePathsDenseTangle (80 issues, a
blocks edge for every ordered pair, one tracks edge back): 26.3 ms and
27.8 MB per call before, 5.4 ms and 2.8 MB after.

* fix(dep): scope the --include-tracks guarantee and bound its output

Review iteration 1 (maintainer fixup) for the one gating major. The
IncludeTracks doc claimed that requiring "at least one blocks/
conditional-blocks edge" on every reported cycle is what keeps out the
`bd doctor` regression that "produced thousands of cycles". That rule is
NECESSARY, NOT SUFFICIENT. One tracks-only loop fuses everything it
touches into a single strongly connected component, after which every
scheduling edge inside that component lies on a cycle and is reported --
even where those scheduling edges alone are strictly acyclic and the
default walk reports nothing. A 10-step molecule whose entry step tracks
back to its root yields 9 reports against the default walk's 0.

The doc's own BOUND paragraph conceded the volume ("never more than twice
the distinct scheduling edges") while the paragraph above it claimed the
guard prevented it. The algorithm is correct and is unchanged; what was
wrong is the contract written over it, plus the absence of any cap on a
diagnostic that can now be edge-count sized.

A census found the claim in 5 sites, not the 2 the review cited:
  issueops/cycledetector.go                       IncludeTracks field doc
  internal/storage/issueops/cycle_report.go       the BOUND paragraph
  internal/storage/issueops/cycles.go             AppendMixedCycleGraphInTx
  cmd/bd/dep.go                                   flag registration comment
  internal/storage/issueops/cycle_report_test.go  section header
backend/conformance/cycle_detector_contract.go:246 already scoped it
correctly ("a loop made entirely of tracks edges stays silent") and is
left alone. The PR body and the contributor's commit messages assert only
the true narrow rule, so neither needed correcting.

--limit caps the RENDERED list (default 50, 0 = no limit), matching the
idiom in list/search/stale/find_duplicates. It is a rendering cap and not
a narrower request because CycleReport.Cycles promises to omit no cycle:
the printed total stays the whole report's, the truncation says how much
it held back, and --json is never capped.

TestCanonicalMixedCyclePathsBoundsAFusedMoleculeByItsSchedulingEdges pins
the manufacture direction ...KeepsDeadlocksATracksEdgeFuses left open --
that one fuses two real deadlocks and checks neither is lost; this one
fuses none at all and still gets 9 reports.

Also taken, both non-gating: dropped the dormant
`json:"include_tracks,omitempty"` tag, since no serializer of
DetectCyclesRequest exists in the tree and handleDependencyCycles calls
requireNoQuery, so the tag advertised a wire contract the server refuses;
and added a comment naming the backend conformance cases as the only pin
on the row->edge admission switch.

Declined this iteration: factoring appendDependencyGraphInTx and
AppendMixedCycleGraphInTx onto one shared row loop (nit, gate impact
none). It restructures the SQL read path that, per the finding directly
above it, is pinned only at the conformance layer, and
appendDependencyGraphInTx also backs AppendSchedulingGraphInTx -- the
write-time gate behind every `bd dep add`. That is a wider blast radius
than a zero-gate-impact nit earns inside a fixup whose subject is a doc
overclaim; it belongs in its own change.

Validation: go build ./... clean; go vet clean on the 4 touched packages;
golangci-lint v2.10.1 reports 0 issues on issueops/...,
internal/storage/issueops/... and cmd/bd/...; internal/storage/issueops
full package 749 PASS / 0 FAIL / 0 SKIP (748 before, +1 new); cmd/bd
dep-cycles selector 9 PASS / 0 FAIL / 0 SKIP; internal/httpapi
Cycle|SpecParity 6 PASS / 0 FAIL. Mutation: making tracks edges unable to
fuse a component reds the new pin plus 5 incumbents (the feature dies);
reporting only one cycle per component reds the new pin ALONE (1 of 14),
so it covers a degradation no existing test catches.

Review iteration 2: the remedy above re-entered its own finding class. Both
iteration-2 items indict text THIS fixup wrote, not the contributor's.

The --limit cap is UNCONDITIONAL -- `if limit > 0 && len(shown) > limit` never
consults includeTracks -- yet every rationale iteration 1 wrote for it was
scoped to the widened walk, and the IncludeTracks field doc still closed with
"the base walk this type's doc above describes is unchanged". True of the walk;
false of its rendering, since plain `bd dep cycles` printed every cycle at base
and now prints at most 50. That is the same defect class as the major this
commit exists to fix: a doc claiming a scope the mechanism does not honor.

Of the two arms the review offered, only documenting the true scope is
available. Gating the cap on includeTracks reds this PR's own incumbent test:
printCycleReportForTest calls runDepCycles(false, limit), so
TestDepCyclesTruncatesTheRenderedListButNotTheCount/capped asserts the DEFAULT
walk truncates. Measured, not assumed -- that arm fails capped and
registered_default while no_limit passes. The implementation, the flag's help
string and the tests already agreed the cap is unconditional; only the prose
disagreed, so the prose moved:
  cmd/bd/dep_cycles.go      runDepCycles doc: the cap is unconditional, bounds
                            both walks, and names the behavior change vs base
  cmd/bd/dep.go             flag comment: caps both walks; the widened walk is
                            what makes the cap necessary, not what scopes it
  issueops/cycledetector.go the "Default false" closer: the walk is unchanged,
                            its RENDERING is not
Also the nit: the opening paragraph argued no flag can narrow either question
while --limit had no carve-out, where IncludeTracks had one. It now says no flag
narrows the ANSWER, and that --limit caps only what is PRINTED.

New renderer arm "registered default" closes the gap the minor named: every
existing arm drove an explicit limit, so the shipped 50 was pinned only by
TestDepCyclesLimitFlagRegistration's DefValue != "0". It reads the default off
the command and renders past it, so it tracks whatever ships; ids are
fixed-width so "past the cap" cannot match as a prefix of one inside it.

Mutation (3 arms, control restored byte-identical by cp -- the fixset was
uncommitted): gate the cap on includeTracks => capped + registered_default RED;
default 50 -> 0 => LimitFlagRegistration + registered_default RED (the new arm
independently catches an unbounded default); shown[:limit+1] => capped +
registered_default RED, so the arm pins the boundary and not merely "some
truncation". no_limit stays green under all three by design.

Validation: gofmt clean, git diff --check clean, go build ./... rc=0, go vet
clean on cmd/bd and issueops, cmd/bd dep-cycles selector 9 PASS / 0 FAIL / 0
SKIP (same top-level roster, +1 subtest). No production behavior changed this
iteration -- doc text plus one test arm.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: sjarmak <t@t.co>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 20:20:17 -07:00
ecuthiell
61865bb0fe
test(init): make gateway credential fixtures portable across native shells (#5715) (#5725)
* test(init): make gateway credential fixture portable (#5715)

Replace shell-specific fixture commands with an opt-in test helper, exercise exact credential semantics under a restricted shell PATH without copied Windows PE fixtures, and require the focused suite in native Windows PR CI.

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* test(init): keep the original shell across native credential fixtures

Use a symlink to the original Unix shell so macOS AMFI does not reject a
copied system executable. Keep Windows cmd.exe and the test image in place,
internalize helper environment names and assert the typed helper exit code.

Run the six fixture cases through one Bash3.2-compatible driver in the
existing required three-host preflight matrix. Preserve the liveness check
name and optional macOS suite policy; reject missing or skipped execution.

Review: https://github.com/gastownhall/beads/pull/5725#pullrequestreview-5096996756
Bead: saa-cgh.47
Agent-Signature: unknown-model/unknown-reasoning

* test(ci): sync-check the native fixture list and stop forcing a second build graph

Maintainer review fixes for PR #5725, adoption iteration 1. The synthesis is
`approve` with no required changes; all findings are minor or nit. The rebase
lane had to repair this branch (`repaired_clean`, and the original head still
conflicts with main), so there is no accepted-as-is path and finalize owes a
push either way — these cost nothing extra.

Test evidence (minor): the `expected` array is, by its own comment, the single
list owning both test selection and required execution evidence -- but nothing
tied it back to the source file. A seventh TestApplyInitGatewayCredential*
fixture added later would fall out of the `-run` selector, lose native
macOS/Windows execution entirely, and still leave the driver exiting 0 with the
required gate green: precisely the "green because nothing ran" mode the per-name
PASS counting exists to prevent. The driver now compares the array against
`grep -Eo '^func TestApplyInitGatewayCredential[A-Za-z0-9_]*'` on
cmd/bd/init_gateway_test.go, by name and by count, before running anything, and
exits non-zero naming the offending fixture. That file is the whole population --
no same-prefix fixture lives in any other cmd/bd test file.

Release safety (minor): the driver sourced .buildflags and then forced
CGO_ENABLED=0, compiling a package graph disjoint from the ./cmd/bd build the
same job performs two steps earlier under the default. Re-measured under the
tags the steps use: `go list -deps -tags=gms_pure_go ./cmd/bd` is 1505 packages
with cgo and 742 without, and the differing cgo users include `net` and
`os/user`, whose build IDs propagate upward -- so nothing was reused and this
blocking, `cache: false` lane paid a second cold compile on macOS and Windows.
The export is dropped. Two consequences beyond the time: the step becomes
incremental, and the natively executed fixtures now exercise the same build of
cmd/bd that actually ships on those platforms rather than a nocgo one. The
comment now explains the build configuration, which is what the old one did not
do -- it explained why no database is needed, a separate question.

Debuggability (nit): the base comment above test-windows-liveness carried three
checkable mechanism clauses (the test is //go:build windows; the Ubuntu job
selects it by name but compiles it out; main.yml's Windows job runs only on
pushes to main). The replacement stated a conclusion a future maintainer cannot
verify, which is how a redundant-looking CI job gets deleted. The mechanisms are
restored and the new pr-preflight-platforms pointer is appended rather than
substituted.

The remaining nit asked for no change in this PR (the credential cache is keyed
by command string, which is harmless as shipped since neither the marker nor the
failure arm populates the cache) and none was made.

Validation: the driver runs green on Linux under the inherited default CGO --
6 of 6 fixtures PASS, exit 0 -- and the sync check was proved by appending an
unwired seventh fixture, which reds it with exit 1 naming that fixture, before
any test runs. `bash -n` clean, no shellcheck SC2086, and ./scripts/ stays green.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:10:22 -07:00
Jim Wordelman
7d545486e5
fix(init): refuse to silently recreate a missing server-side database as empty (#5791)
* test(init): red — existing project with missing server DB must refuse init

be-5up5: server mode never has a local dolt/ directory, whether this is a
genuine fresh clone or an existing project whose database was lost from the
server — doltDirExists==false alone (GH#2433's signal) can't distinguish
them. Adds TestInitGuard_ExistingProjectMissingServerDB_Refuses, which spins
up a real dolt sql-server with no database and a metadata.json carrying a
non-empty project_id (proof of a prior real init). Currently fails: the
guard returns nil and lets init silently recreate the database as empty,
which is the 2026-08-11 fleet-wide data loss.

RED only — checkExistingBeadsDataAt is not yet fixed.

* fix(init): refuse to recreate a missing server-mode database (be-5up5)

bd init's server-mode "already initialized" check treated a missing or
unreachable database the same as a genuine fresh clone, silently
returning nil and letting init proceed to create an empty database —
even when metadata.json's project_id proved this was an existing
project whose database had gone missing (the 2026-08-11 fleet-wide
data loss).

Guard on cfg.ProjectID != "" to distinguish the two cases. An existing
project now gets a refusal (initGuardMissingServerDBMessage) that
names bd doctor / bd dolt status / bd backup restore as the recovery
path and explicitly does not recommend bd bootstrap, since bootstrap
has its own related mode-blind create bug (tracked separately). A new
--recreate-missing flag is required to opt into creating fresh in this
case — never implied by --force, config, or env. Genuine fresh clones
(empty project_id) are unaffected.

Also:
- doctor/gitignore.go: drop the "bd init (safe to re-run)" fix hint,
  since re-running bd init is exactly the unsafe action this fix
  prevents in the case that matters.
- storage/dolt/errors.go: the general "database not found" hint no
  longer claims bd bootstrap is a safe first step for "an existing
  project" — only for genuine fresh-clone / shared-server-recovery,
  which is what the existing tests actually cover.

* test(init): pin exit_contract's bootstrap-not-recommended requirement (be-5up5)

TestInitGuard_ExistingProjectMissingServerDB_Refuses checked the refusal
and the absence of --force, but not the exit_contract's explicit "does
not recommend bd bootstrap for a server-mode workspace" requirement —
that was only verified by hand during self-review. Pin it directly, and
assert the message names an actual recovery path.

* test(init): cover --recreate-missing positive path (be-ab3b)

be-5up5's guard already correctly permits init to proceed when
--recreate-missing is set; only the negative path (flag absent -> refuse)
had test coverage. Adds TestInitGuard_ExistingProjectMissingServerDB_
RecreateMissingAllows, covering both guard sites the flag gates:
init.go:2566 (server reachable, database confirmed missing) and
init.go:2578 (server unreachable / errored during the check).

refs be-3mvz (review round 1 request-changes), closes be-ab3b

* chore: release gate PASS for bd init missing-server-DB guard fix (be-udx2)

* chore: record full pre-PR contributor check results for be-udx2 gate

* test(init): red — bd init --force recreates a missing server DB as empty

--force is a deprecated alias for --reinit-local (init.go ~395), and the
existing-data guard is gated on !reinitLocal (~763), so --force skips
checkExistingBeadsData — and with it the be-5up5 missing-database refusal
this PR added. The reinit path's own typed confirmation does not cover the
gap either: it keys on countExistingIssues, which returns 0 or an error in
exactly the case where the server-side database is missing, so no prompt
and no destroy token are ever required.

Net effect at this commit, measured against a real dolt sql-server
(2.2.3) holding no "myproject" database, with metadata.json carrying a
project_id:

    $ bd init --force --prefix myproject --skip-hooks
    ...
      Database: myproject
      Issue prefix: myproject
    Run bd quickstart to get started.
    $ echo $?
    0
    $ ls <server data-dir>
    config.yaml  .dolt  .doltcfg  myproject      <-- created, empty

An empty database at the name the real one used to occupy, exit 0, no
prompt. That is the 2026-08-11 fleet-wide data-loss reflex, reached
through the flag an operator in a panic is most likely to reach for.

This test drives the real binary because that is the only way to exercise
the --force -> reinitLocal -> "skip the guard" path end to end; a unit
test on the guard function cannot see that the caller never runs it.
Both subtests fail at this commit.

Reported in review of PR #5791 by bee-ghosttrack, item 1.

* fix(init): green — --reinit-local/--force cannot bypass the missing-DB guard

Add guardMissingServerDatabaseAt, a narrowed form of the be-5up5 refusal
that answers only one question — is this an already-initialized
server-mode project whose configured database is missing or
unconfirmable? — and run it on the reinitLocal path, which
checkExistingBeadsData never reaches.

The distinction the guard encodes: --reinit-local/--force authorize
destroying a database that EXISTS. They do not authorize inventing an
empty one where the configured database has gone missing. Only the
explicit, per-invocation --recreate-missing does that, which is what makes
that flag's "never implied by --force" help text an honest guarantee
rather than an aspiration. The review suggested softening that help text
instead; making the claim true seemed better than documenting that it
isn't.

Deliberately narrow. It returns nil for every state except the missing
database — no metadata, non-Dolt backend, non-server mode, empty
project_id, or a local dolt/ directory all fall through — so it never
resurrects the "already initialized" refusal that --reinit-local is
legitimately meant to bypass. The "stays silent on a fresh clone with no
project_id" subtest pins that boundary.

Same scenario as the previous commit, now:

    $ bd init --force --prefix myproject --skip-hooks
    Error:
    (warn) Database "myproject" not found on server at 127.0.0.1:34813 ...
    bd init will NOT create an empty database here — that would strand any
    existing issue data behind a new, empty database of the same name.
    $ echo $?
    1
    $ ls <server data-dir>
    config.yaml  .dolt  .doltcfg            <-- nothing created

Addresses review of PR #5791 by bee-ghosttrack, item 1.

* test(init): cover the unreachable-server refuse branch

Review of PR #5791, item 2. The PR claimed
TestInitGuard_ExistingProjectMissingServerDB_Refuses covered both guard
sites — server reachable with the database missing, and server unreachable
or errored while checking. It does not: that test starts a live dolt
sql-server, so it only ever exercises the first. The unreachable site had
coverage on the PERMIT side only (the BEADS_DOLT_SERVER_PORT=1 subtest of
_RecreateMissingAllows), which would not notice if its refusal were
dropped.

TestInitGuard_UnreachableServerRefuses closes that: port 1 is unreachable
by construction, so it needs no dolt binary and runs in the fast lane.

Also drops a comment reference to scripts/repro-bd-init-recreates-empty-db.sh,
which is not in the repo or in this diff (item 3, third bullet), and
describes the state the test sets up instead.

Addresses review of PR #5791 by bee-ghosttrack, item 2.

* docs(init-safety): document --recreate-missing and its known limits

Review of PR #5791, item 3 (doc drift), plus the non-blocking note.

The flag's own help pointed users at `bd help init-safety`, whose FLAG
SURFACE section did not list it — so the one place the help sends you was
the one place it was missing. Added there, stating plainly that it is
per-invocation only and never implied by --force/--reinit-local, config,
or env.

docs/recovery/init-safety.md gains an init-missing-server-db section (and
a TOC entry) covering the refusal users will actually hit: why the
fresh-clone and lost-database cases are indistinguishable from the local
filesystem in server mode, why the old "assume fresh clone" answer caused
the 2026-08-11 loss, and the three ways out in the order they should be
tried — diagnose the server first (a stopped server or wrong --data-dir
presents identically and needs no re-init), then restore from an export,
then --recreate-missing as the deliberate last resort.

Both limits the review flagged as non-blocking are recorded there and in
the guard comment rather than left as folklore:

- The guard keys on project_id, minted by GH#2372. A pre-GH#2372 workspace
  carries none and is indistinguishable from a fresh clone, so it FAILS
  OPEN. Accepted deliberately — failing closed would block legitimate
  first inits on every such clone, and this guard's job is to stop a
  silent recreate where prior initialization can be PROVEN, not to guess
  where it cannot.
- Server mode only. Proxied-server mode returns early on a missing root
  and never reaches the guard, and bd bootstrap has its own separate
  mode-blind create path.

Addresses review of PR #5791 by bee-ghosttrack, item 3 and the
non-blocking notes.

* docs(changelog): record the --force missing-database bypass fix

Under Unreleased/Fixed. This is a behavior change to bd init --force on
every server-mode workspace whose database has gone missing, and it was
not recorded anywhere users read.

* fix(init): make the missing-server-database guard fire in shared-server mode

Review round 2, item 1 (blocking): the guard was a no-op in shared-server mode
— the topology of the 2026-08-11 data loss, and so the primary case.

guardMissingServerDatabaseAt statted doltserver.ResolveDoltDir(beadsDir) and
returned early when it was a directory, reading that as "there is local data to
protect". In shared mode ResolveDoltDir returns the machine-global
~/.beads/shared-server/dolt, and SharedDoltDir() MkdirAlls it
(internal/doltserver/doltserver.go:281). The stat therefore always succeeded and
checkDatabaseOnServer was never reached, while every per-project test kept
passing.

Fix per the reviewer's first option: test for THIS project's database directory
rather than the data directory that holds it. A Dolt data dir contains one
subdirectory per database, each with its own .dolt — verified on disk — so
<doltDir>/<dbName>/.dolt is the correct probe in BOTH modes, and it is strictly
more precise in per-project mode too: a data dir that exists but holds no
database for this project no longer counts as local data to protect.

Two new tests, both against a real dolt sql-server rather than an unreachable
port, covering the two cases the reviewer noted were uncovered:

  TestInitGuard_SharedServerMode_MissingServerDB_Refuses
      reachable server, database absent -> must refuse.  This is the actual
      loss shape. Reverting the one-line guard change turns it red with
      "got nil error"; the pre-existing per-project tests stay green, so it
      pins the shared-mode gap specifically.
  TestInitGuard_SharedServerMode_PresentServerDB_Allows
      reachable server, database present -> must NOT refuse, so --reinit-local
      and ordinary reinit keep working. The reviewer verified this by hand and
      flagged it as untested.

Also from the same review:
- docs/recovery/init-safety.md overstated the proxied limit. The proxied path
  does not reach THIS guard (dispatch at init.go:619 precedes the
  initAllowRecreateMissing assignment at :767), but it does reach the older
  checkExistingBeadsData (init_proxied_server.go:89) — and because the flag is
  never assigned there, --recreate-missing is inert under --proxied-server.
  Documented as pre-existing rather than silently fixed.
- Shared-server mode now named explicitly in the same Limits section.
- checkExistingBeedsData typo corrected.
- The "### 3." heading wrapped onto a second line and rendered broken.

Verified: full TestInitGuard suite 15/15 PASS, 0 SKIP (12.1s), including all
pre-existing guard tests. go build ./... clean, gofmt clean, go vet clean.

Refs be-ok1tt, be-udx2.

* test(init): redirect the shared-mode fixtures with BEADS_SHARED_SERVER_DIR

Round-3 MINOR-2, unaddressed through round 4. The two shared-server tests
redirected HOME so SharedDoltDir() would resolve inside the test tree, but
SharedServerPath() reads BEADS_SHARED_SERVER_DIR first and only then falls
back to os.UserHomeDir(). An ambient BEADS_SHARED_SERVER_DIR — the override
that function's own comment advertises for testing — silently won, and the
pair then wrote into and asserted against the developer's real
~/.beads/shared-server/dolt, failing spuriously if a real "myproject" lived
there. HOME is also a no-op on Windows, where os.UserHomeDir() reads
%USERPROFILE%.

Set the variable the resolver actually consults first. No behavior change.

* test(init): make the present-database control pin the early return

Round-3 NIT-4, unaddressed through round 4, and demonstrated there: with the
local-database probe reverted, _SharedServerMode_PresentServerDB_Allows stayed
green, so it pinned nothing of the early return that commit rewrote. It
returned nil via the server check alone, because the fixture never gave this
project a database directory under the shared data dir.

Create that directory, the way a real shared-mode install has one, and then
assert the early return specifically: with the server made unreachable, the
local database directory alone must still satisfy the guard. Removing the
early return now turns this test red.

* test(init): red — the documented --recreate-missing recovery cannot reach its opt-in

Round-3 MAJOR-1 / round-4 finding 1. checkExistingBeadsDataAt derives "is this
project's database here?" from os.Stat(ResolveDoltDir(beadsDir)) — the DATA
directory, which exists on every initialized workspace (shared-server mode
MkdirAlls the machine-global one in SharedDoltDir; per-project mode MkdirAlls
it in ensureDoltInit). So the FR-010 missing-vs-present branch never runs and
both --recreate-missing opt-ins inside it are unreachable.

Four surfaces tell the operator to run `bd init --recreate-missing --prefix
<p>`: the flag help, `bd help init-safety`, docs/recovery/init-safety.md, and
the guard's own refusal text. That command exits 1 with a false "already
initialized" message pointing back at --reinit-local, which is the destructive
path. The documented recovery is a dead end and the only thing that works,
--reinit-local --recreate-missing, is named nowhere.

The existing _Refuses/_RecreateMissingAllows fixtures cannot see this: they
omit the data directory entirely, so their branch condition is true for the
wrong reason. These two add it, which is the state of every real workspace
whose server-side database was dropped.

Both fail at this commit.

* fix(init): green — probe this project's database directory, not the data dir holding it

Round-3 MAJOR-1 / round-4 finding 1. Test for <dolt-data-dir>/<database>/.dolt
instead of the data directory itself, so the FR-010 missing-vs-present branch
is reachable on an initialized workspace and `bd init --recreate-missing`
reaches its own opt-in. This is the same probe, for the same reason, that
guardMissingServerDatabaseAt already uses on the reinit path.

Making that branch reachable also exposes states the data-dir stat used to
shadow, and permitting them would be a new fail-open policy rather than a fix.
The clearest is a workspace that predates GH#2372: it carries no project_id,
so `existingProject` is false, and the branch would permit a silent empty
recreate on exactly the installed base this guard exists to protect. The
data-dir stat therefore stays — it stops being the gate and becomes the permit
condition, admitting only what the old probe already admitted, plus the
explicit per-invocation opt-in. Net behavior change is the opt-in becoming
reachable, and the false "already initialized" message being replaced by the
accurate missing-database refusal where the database is genuinely gone.

Choosing a better proof of prior local init is deliberately NOT done here.
project_id comes from git-tracked .beads/metadata.json, so a fresh clone
inherits one (round-4 finding 2); the replacement signal needs a different
answer in per-project and shared-server mode, and is tracked as its own
architecture decision on be-5pjhd. The known limit is now recorded in the
guard comment and in docs/recovery/init-safety.md rather than left implicit.

Tests: the two red tests from the previous commit now pass, and two more pin
the narrowing — a pre-project_id workspace with a local data dir stays blocked,
and --recreate-missing still opens it.

* docs: record the --recreate-missing fix and the fresh-clone project_id limit

Round-3 NIT-3 / round-4 finding 4: the round-3 probe change (data dir to
<dolt-data-dir>/<database>/.dolt) was never written down, and it is
user-visible wherever the data dir exists but the database is gone. Both that
and this round's --recreate-missing fix are now under [Unreleased] / ### Fixed.
The stray double blank line is gone with the section's move.

Also records, in docs/recovery/init-safety.md's "Limits worth knowing", that
project_id is inherited by a fresh clone because .beads/metadata.json is
git-tracked by default — the round-4 finding-2 gap this series deliberately
does not close. It fails in the safe direction and --recreate-missing is the
supported way through it; the replacement signal is tracked separately.

* docs(adr): ADR-0004 — proof-of-prior-init signal for the missing-database guards

Round-4 finding 2 asked what should replace project_id as the proof that a
workspace was initialized locally, and what the fail-open/fail-closed policy
should be per server mode. It needed a design decision rather than a
mechanical fix, so it was escalated; this records the answer.

The decision is to formalize what the code already does for local hosts and
keep project_id where nothing local can ever help. Presence of this project's
own <dolt-data-dir>/<database>/.dolt is unconditional proof, because the path
is gitignored and only a real local process creates it. Its ABSENCE, however,
cannot be promoted to proof in either direction: it looks identical whether
the workspace was never initialized here or was initialized here and lost its
storage — and the second is the shape of the 2026-08-11 incident. For a
genuinely remote host the probe is not merely silent today, it is structurally
silent forever, since the only code that creates that directory runs on local
server-management paths.

So project_id stays as the tier-2 fallback with its git-inheritance weakness
accepted, and --recreate-missing is the permanent resolution UX rather than a
stopgap. A local-only init marker and repurposing .local_version are recorded
as rejected, with reasons, so neither is re-proposed each review round.

Extends ADR 0002, which set the init safety invariants but left the evidence
question open.

* test(init): red — the reinit guard waves through a pre-project_id workspace

ADR-0004 follow-up 1. guardMissingServerDatabaseAt is the safety net for
--reinit-local and --force, which bypass checkExistingBeadsDataAt entirely. It
returns nil the moment cfg.ProjectID is empty, BEFORE it ever reaches the
per-database .dolt probe eighteen lines below.

checkExistingBeadsDataAt does the opposite: it probes first, and only falls
back to project_id — narrowed by the coarse-directory permit condition — when
that probe comes up empty. So a workspace initialized before GH#2372 minted
project_id, whose local Dolt storage has since been lost, is protected under
plain `bd init` and waved straight through under the two flags an operator
reaches for in a panic. The weaker path is the one behind --force.

Three tests through guardMissingServerDatabaseAt, mirroring the plain-init
trio: no project_id with a local data dir present must refuse; no project_id
with nothing local at all is a genuine fresh clone and must be allowed; and
--recreate-missing must still open the refused case.

The first fails at this commit. The other two pass, and pin the directions the
fix must not break.

* fix(init): green — probe the local database before consulting project_id

ADR-0004 follow-up 1. Move the per-database <dolt-data-dir>/<database>/.dolt
probe above the project_id check in guardMissingServerDatabaseAt, and run it
unconditionally, so this guard reasons in the same order as the plain-init
guard it backstops.

When the probe comes up empty and project_id is also absent, apply the same
coarse-directory permit condition checkExistingBeadsDataAt uses: allow only
when there is no local Dolt data directory either. A data directory with no
database in it still says this workspace has touched local Dolt storage, and
that is exactly the pre-GH#2372 lost-storage case the old early return waved
through under --reinit-local and --force.

One cell of the behavior matrix changes: no project_id, no local database, but
a local data directory present now refuses instead of returning nil.
Everything else is untouched, --recreate-missing still returns nil at the top
of the function, and a workspace with nothing local at all is still treated as
a fresh clone.

The comment records the shared-server asymmetry ADR-0004 accepts — there the
coarse directory is machine-global, so that cell is more conservative — as
settled rather than as an open defect, since it fails toward refuse and its
population only shrinks.

* docs: cite ADR-0004 from the plain-init guard, the recovery doc and CHANGELOG

The comment at checkExistingBeadsDataAt's project_id check said the limit was
"OPEN and tracked by be-5pjhd" and that the replacement signal was
"deliberately not made here". It is made now, so the comment says settled
instead of open, and points at the ADR rather than at a bead — with a note to
read it before reopening, since the two obvious alternatives are recorded
there as rejected rather than unconsidered.

docs/recovery/init-safety.md said the same thing in operator language and is
updated the same way, plus a new bullet stating that the guard now applies
equally to bd init, --reinit-local and --force. That equality is the
user-visible half of the fix and was not previously stated anywhere.

Its "Last reviewed" marker moves to today. The doc is freshness-tracked
against cmd/bd/init.go, which this series changes, and leaving the marker at
2026-09-08 would claim text written today had been reviewed eight days before
it existed.

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-udx2-init-missing-db-guard-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

* chore(bazel): enumerate init_guard_force_e2e_test.go in cmd/bd srcs

The PR adds cmd/bd/init_guard_force_e2e_test.go under a plain '//go:build cgo'
tag, which is the tag class cmd/bd/BUILD.bazel enumerates (the 23 unenumerated
test files in this package are all 'cgo && integration', 'scripttests' or
'chaos'). cmd/bd/BUILD.bazel is base-added, so the contributor's branch could
not have carried this row. Generated by 'make bazel-sync'; no hand edits.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(init): honor --recreate-missing on the proxied route; scope the refusal's evidence claim

Maintainer review fixes for PR #5791 (iteration 1). Five review minors; the
three substantive ones:

1. --recreate-missing was inert under --proxied-server. runInit dispatches to
   runInitProxiedServer and returns before the assignment site, while
   runInitProxiedServer calls checkExistingBeadsData, which reads the global —
   so converting a server-mode workspace with a missing database to proxied
   mode was refused despite the explicit opt-in, and the refusal named the
   exact flag the operator had just passed. It failed closed, so there was no
   data hazard, only a recovery dead-end. The assignment now sits beside its
   flag read, upstream of every dispatch in runInit.

   The PR's recovery runbook documented this inertness as "pre-existing
   behaviour, not introduced here". The early dispatch is pre-existing, but
   --recreate-missing is introduced by this PR, so the flag could not have had
   pre-existing inertness. That paragraph is rewritten to the new behaviour.

2. initGuardMissingServerDBMessage asserted "metadata.json has a project_id"
   unconditionally, but the --reinit-local/--force guard also emits it for a
   workspace predating GH#2372 where only local Dolt storage proves prior use —
   the population the CHANGELOG bullet names. The evidence sentence is now
   selected by the caller, so the message never cites an artifact its caller
   does not have. Pinned from both sides: the project_id cell must cite that
   evidence, the no-project_id cell must not.

3. The new doc comment claimed initGuardServerMessage is "used when there is no
   evidence either way". It has no production caller, so the contrast was
   asserted as two live code paths. Reworded to intent. The dead message's
   surviving "existing project -> bd bootstrap" sentence is pre-existing, is
   pinned by four tests, and is left for a follow-up.

Also re-cited two stale path:line references by symbol and branch (the recovery
runbook's three, and a test comment's two), and expanded the else-branch comment
in checkExistingBeadsDataAt to cover the reachable-but-missing fall-through that
lands there — the branch's guards are correct for both cases only because their
conditions do not mention reachability.

Declined, with reasons, as out of scope for opportunistic cleanup: restructuring
the fall-through itself (a control-flow change in the diff's most complex
function, which both review lanes agree is behaviourally correct today);
rewording the caller-less message's bootstrap sentence (four pinned tests,
pre-existing); and adding --recreate-missing to the generated CLI reference
(the required check-doc-flags job passes at this head and seven other registered
initCmd flags are equally absent, so that page is not a flag enumeration).

Validation: go build ./... and go vet ./cmd/bd/ clean; gofmt clean;
go test ./cmd/bd/ -run 'TestInitGuard|TestCheckExistingBeadsData' ok (26 tests,
real Dolt servers); scripts/check-doc-freshness.sh PASSED; git diff --check
clean. The evidence pin was proved non-vacuous by mutation: forcing the reinit
call site back to an unconditional project_id claim reddens exactly the
no-project_id test and nothing else.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(doctor): drop the bd init hint from #5634's permissions warning

1d7629213b on this branch removed "bd init (safe to re-run)" from the
.beads/.gitignore fix hints, because re-running bd init is the unsafe
action be-5up5 guards against. #5634 (c33738d209) reached main while
this PR was open. It added a CheckGitignore warning for unexpected file
permissions that still carries the old hint, so after the merge it was
the only gitignore check that suggested bd init.

Give it the same "Run: bd doctor --fix" hint as the four other
gitignore warnings. That is a complete repair here: FixGitignore
restores mode 0600, and #5634's test already checks that the warning
clears after it runs.

TestCheckGitignore_WarnsOnLoosePermsWhenPatternComplete only checked
that Fix was non-empty. It now pins the exact hint. With the old
gitignore.go line put back, the test fails.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(init): name the real gitignore template in ADR-0004 and init.go

ADR-0004 and the matching comment in init.go both cite
`defaultGitignoreContent` in cmd/bd/doctor/gitignore.go as the place
that says .beads/metadata.json is git-tracked by default. No symbol by
that name exists, in this branch or in main's history. The constant
that says it is GitignoreTemplate. Its closing lines read "Config files
(metadata.json, config.yaml) are tracked by git by default since no
pattern above ignores them".

Rename the reference in both places. The claim itself is unchanged.
Neither file changes outside that one identifier.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 20:07:49 -07:00
matt wilkie
c33738d209
fix(doctor): tighten .beads/.gitignore perms even when patterns are complete (#5634)
* fix(doctor): tighten .beads/.gitignore perms even when patterns are complete

EnsureGitignoreForBeadsDir returned early when the file was already
pattern-complete, skipping the 0600 tightening below - so a complete file
with loose perms (0644 from an old bd, a checkout, or umask) never got
repaired. Hoist the permission repair above the early return and trigger
on any deviation from 0600, not just missing owner-write.

Adds the tests flagged in the #5285 review: pattern-complete-but-0644 gets
tightened with content byte-identical, and FixGitignore twice is
idempotent (no duplicate appends).

Agent-Signature: claude-fable-5-high on behalf of matt wilkie
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G74Vh4USrUkc9przesWyUJ

* fix(doctor): correct permission-warning wording and pin its branch

Maintainer review fixups for PR #5634 (adopt-pr review iteration 1). All
three changes are confined to the files this PR already touches.

- CheckGitignore reported "Loose permissions on .beads/.gitignore" for any
  mode != 0600, which is factually inverted for a mode *stricter* than 0600:
  a 0400 file was reported as loose and then widened to 0600 by --fix.
  Reword to "Unexpected permissions"; Detail ("Mode is 0400, want 0600") and
  Fix are unchanged. The check predicate is deliberately left alone --
  normalizing to exactly 0600 is the stated policy at every writer of this
  file, and EnsureGitignoreForBeadsDir must restore owner-write to keep its
  append route working, so the widening is intended behavior, not a defect.

- TestCheckGitignore_WarnsOnLoosePermsWhenPatternComplete asserted only that
  *a* warning fired. CheckGitignore also warns for a missing file and for
  missing patterns, so if GitignoreTemplate ever drifted out of
  requiredPatterns the test would stay green while the permission branch went
  untested. Pin the branch: assert the message and the observed mode.

- Retarget the trailing os.Chmod comment. With the chmod hoisted above the
  pattern check, its old "the file may predate the 0600 policy" rationale is
  now handled upstream; the residual case it still guards is the hoisted
  block's os.Stat failing (file removed between the ReadFile and the Stat,
  where os.WriteFile then creates it under umask).

Validation: go test ./cmd/bd/doctor/ -run Gitignore green, go build, go vet,
gofmt all clean. The new assertions are mutation-proved: reverting the message
reds the message assert, and drifting requiredPatterns out of the template
reds both new asserts while the pre-fix Status-only shape stays green -- the
exact masking these assertions close.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 18:34:19 -07:00
ecuthiell
a8003cf6ec
test(cmd/bd): reset repository caches around CWD fixtures (#5747)
* test(cmd/bd): reset repository caches around CWD fixtures (#5746)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* test(cmd/bd): pair the beads/git cache resets at the two remaining chdir fixtures

Maintainer review fixup for the adopt-pr review of #5747 (iteration 1,
synthesis approve, 0 blocker / 0 major).

Takes the single minor finding (Change Impact / Blast Radius). The PR
establishes that a one-sided cache reset around a chdir fixture is a
structural half-fix, but two sites in the same package still encoded
exactly one half each, failing in opposite directions:

- serve_registered_backend_test.go: had the beads-only pattern the PR
  just deleted elsewhere (beads.ResetCaches + bare
  t.Cleanup(beads.ResetCaches)). Converted to the paired closure the PR
  uses, adding git.ResetCaches on both edges. The file was already cited
  as the exemplar for the paired idiom at two other anchors; this was the
  third, unfixed site.
- git_test_helpers.go: runInDir is the package's single helper for this
  contract across 38 call sites, and it reset git only, never beads.
  Added beads.ResetCaches beside both git.ResetCaches calls, and updated
  the doc comment to state why the pair is required. No call-site churn.

Both caches key on the working directory, so clearing one leaves the
other answering for the previous directory.

Validation: go vet ./cmd/bd/ clean at CGO_ENABLED=1; the 22 test
functions that call runInDir plus TestServeRefusesStrictReadonlyOnARegisteredBackend
run 47/47 PASS, 0 SKIP.

Not taken: the optional shared chdirFixture(t, dir) helper the finding
suggests. It would churn all 38 call sites for no behavior change, which
is beyond what a maintainer fixup on an approved PR should carry.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 18:32:26 -07:00
Harry Miller
d0743f89d7
fix(formula): substitute vars in step assignee, labels, and metadata (#5758)
* fix(formula): substitute vars in step assignee, labels, and metadata

Cook and pour substituted title/description/notes/gate but copied
assignee, labels, and metadata through raw, so a poured bead carried
literal `{{var}}` text in all three.

- labels: every label-based query, filter, and automation silently stops
  matching, and nothing errors (GH#5110).
- metadata: general keys came through literal; only a top-level "repo"
  key on a gh:* gate was substituted (GH#5110).
- assignee: worse than cosmetic - close refuses when the actor doesn't
  match the assignee, so every step of a poured molecule is unclosable
  and the molecule can never advance (GH#5754).

internal/formula/expand.go already substituted assignee and labels on
the inline-expansion path, so the two paths disagreed on the same
fields; Step.Assignee is documented as "supports substitution" and
ExtractVariables already scanned it, meaning pour hard-failed demanding
a variable it then refused to resolve.

Both call sites are fixed together: runtime-mode cook feeds the proto
that pour clones, so a field left literal in either path ships a
placeholder onto the bead. Fixing cloneSubgraphInto covers pour, wisp,
bond, and the proxied-server paths, which all funnel through it.

substituteMetadataRepo is generalized to substituteMetadataVars, which
resolves every string leaf of the metadata JSON at any depth. This drops
the earlier gh:*-gate-only restriction (SF2/SF4): reading a `repo` key
AS a GitHub selector is only correct on a gh:* gate, but resolving a
{{var}} in it interprets the key not at all. The walk still decodes into
json.RawMessage, so untouched values stay byte-identical, and object
keys are never rewritten (a rewritten key could collide with a sibling).

The variable scan is widened to match: extractAllVariables (pour) and
ExtractVariables (cook) now cover assignee, labels, metadata strings,
notes, and await ID, so pour demands exactly the variables it resolves.
Undeclared handlebars are still filtered out by VarDefs.

Regression coverage asserts on a poured bead, and checks the assignee
via validation.AssigneeMatches rather than a string compare - a
substitution-only assertion would pass while the unclosable symptom
persisted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(formula): regenerate schema_gen.go after the types.go doc edits

TestSchemaGenIsCurrent holds schema_gen.go to a byte-for-byte rerun of
the generator over types.go, and the field docs are part of the
generated output — so the Labels/Metadata comment updates made it stale.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(mol bond): resolve vars like pour instead of demanding every handlebar

buildAttachCloneOpts demanded every variable extractAllVariables found in
the proto subgraph and applied no declared defaults, unlike pour
(cmd/bd/pour.go) and wisp (cmd/bd/wisp.go). Widening the scanned field set
to assignee, labels and metadata therefore widened bond's hard refusal
along with it: a proto whose label or metadata carried an undeclared
documentation handlebar, or a declared var carrying only a default, made
`bd mol bond` fail with "missing required variables" where it previously
succeeded.

Run applyVariableDefaults + extractRequiredVariables there, matching the
sibling call sites. extractRequiredVariables returns the unfiltered list
when VarDefs is nil, so a legacy template still requires every var it
mentions; the change is strictly a reduction in false failures. Applying
the defaults also puts them in opts.Vars, which is the map
cloneSubgraphInto actually substitutes from.

Also from review:

- docs/workflows/gates.md no longer enumerates a stale three-field list for
  where `{{var}}` substitution applies.
- maxMetadataSubstitutionDepth's doc names walkJSONStrings (not the
  long-gone substituteJSONVars) and says plainly that hitting the bound
  deliberately ships a literal placeholder rather than erroring.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* build(bazel): add the validation dep to the bd_test go_test (make bazel-sync)

mol_embedded_test.go and template_test.go now import internal/validation
directly (validation.AssigneeMatches, to check the substituted step
assignee), so gazelle emits //internal/validation on bd_test. bd_lib
already carries the dep, so bd_test compiles through embed, but gazelle
lists every direct test import on the go_test itself. cmd/bd/BUILD.bazel
landed on main after this PR branched, so the PR could not carry the
line; without it, bazel.yml's "BUILD files in sync" step fails in the
required Bazel / test lane. Generated by `make bazel-sync`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-09-30 18:08:44 -07:00
Rongjun GENG
8da2ae4328
fix(embeddeddolt): commit pending changes before push (#5433) (#5795)
* fix(embeddeddolt): commit pending changes before push (#5433)

Every Pull variant (Pull, PullWithStrategy, PullRemoteWithStrategy,
PullRemote, PullFrom) auto-commits pending working-set changes first
(GH#2474, so a crashed command's leftovers don't make the merge
refuse to start), but no Push variant (Push, ForcePush, PushRemote,
PushTo) did. A write that landed in the working set but was never
explicitly committed -- auto-commit configured off, or a session that
ended right after a write with no intervening commit -- silently
pushed nothing new while `bd dolt push` still printed "Push
complete." and exited 0.

This is the half of #5433's silent-stall report the maintainer traced
and confirmed in code (issue comment, quoting exact line numbers this
matches on current main): "every Pull variant calls CommitPending
before pulling... no Push variant does... push never flushes the
working set, then prints 'Push complete.' on nil error with no
remote-ref or working-set check. Strongest hook for a narrow
push-honesty PR." Reporter confirmed: "Yes, please open the
push-honesty PR. That is the surface that actually cost us."

Scoped to exactly this half -- the confirmed, traced, mechanical gap
matching an already-established pattern (copy Pull's own guard to
Push). Did NOT attempt the harder half discussed in the same thread:
verifying the remote ref actually advanced and reporting honestly
when it didn't. That needs a deliberate design call the maintainer
themselves treated as separate (distinguishing a legitimate no-op
push, already in sync, from one that had something to send but
transferred nothing) and risks false positives if done carelessly --
a bigger change than this issue's narrowed scope asked for. Flagging
in the relay rather than guessing at that design.

Also confirmed the server-mode backend (internal/storage/dolt) has
the identical asymmetry -- Push/ForcePush/PushRemote all route through
pushToRemote, which likewise never calls CommitPending -- but the
issue's repro and the maintainer's trace are both embedded-mode
specific, so left server-mode untouched pending its own verification.

Does not claim to fix the mysterious full stall itself (bd dolt
commit also returning "Nothing to commit" while HEAD stays frozen,
even when called directly) -- the reporter and maintainer both
independently concluded that has no known deterministic trigger.
This closes one real, confirmed contributing gap: push not flushing
pending changes the way pull always has.

RED: added TestPushCommitsPendingChangesFirst, table-driven over all
four Push variants. Creates an issue (a genuinely pending, uncommitted
change -- verified via GetCurrentCommit before/after CreateIssue, so
the test would fail loudly if CreateIssue ever started auto-committing
on its own), then calls each Push variant and asserts HEAD moved.
Push/ForcePush/PushRemote route through the swappable vcPush/
vcForcePush vars (remote_peer_auth_test.go's existing
captureRemoteEntryPoints seam) so the test stops with errStopRemote
before any network IO; PushTo calls versioncontrolops.Push directly
with no equivalent seam, so it actually attempts the push and fails on
"remote not found" in this remote-less test store -- still proves
CommitPending ran first, since that failure only happens after this
fix's guard clause. All four failed pre-fix (HEAD did not move).
GREEN: all four pass after the fix.

Verified: full remote-verb/peer-auth suite (TestWithPeerAuth and its
variants, TestRemoteVerbsPresentStoredPeerCredentials,
TestRemoteVerbPlainRemote*) still green -- confirms this fix doesn't
disturb credential resolution or the swappable-seam test
infrastructure it shares. go vet clean, go build ./... clean across
the repo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018c3vLFNVgPebSpCJrd8xTD

* chore(bazel): enumerate push_commit_pending_test.go in embeddeddolt go_test srcs

Generated by `bazel run //:gazelle`. The PR predates base's addition of
internal/storage/embeddeddolt/BUILD.bazel, so its new test file was not in
the explicit go_test srcs list; bazel would have silently run zero of its
cases. Base parity at the rebase base was 118/118 enumerated.

* fix(autopush): record post-push HEAD, and cover the clean-store push path

Maintainer review fixup for #5795 (adopt-pr review iteration 1).

Push now commits pending changes before pushing (GH#5433), so HEAD can move
across the call. maybeAutoPush read HEAD only before the push and recorded that
hash as LastCommit, which is now the parent of what was actually pushed, so the
next tick saw a mismatch and pushed once redundantly before re-latching. Route
the recorded hash through pushedCommitForState, which re-reads HEAD after a
successful push and falls back to the pre-push value if the re-read fails (the
push itself already succeeded, so dropping LastCommit would lose change
detection entirely).

Also:

- Add a clean-store arm to TestPushCommitsPendingChangesFirst. The guard relies
  on commitAll(tolerateEmpty=true) mapping Dolt's "nothing to commit" to
  (false, nil) for every push against an already-committed store, and nothing
  in this package asserted it. Flipping that flag reds the new arm alone, with
  the four pending-change arms still green.

- Correct the `bd dolt remote reset-data` confirmation, which promised the
  remote is "rebuilt from local HEAD" while the push now adds a commit created
  after the operator types y.

Not taken here, tracked separately: extending auto-push change detection to also
fire on a dirty working set (that gate predates this PR, so skipping it is an
incompleteness rather than a regression this PR introduces), and the PR-body
disclosure that push now commits on the auto-push and `bd sync` cadences.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 15:58:51 -07:00
ecuthiell
3402679901
fix(output): route graph renderers and ratchet stdout writes (#5624)
* fix(graph): route render modes through command writer (#5622)

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* test(output): ratchet list and graph stdout routing (#5617)

Replace the rejected source-shape census with typed forbidigo rules for process-stdout writes across list and graph files. Existing out-of-scope paths carry visible line-local exceptions; new sites fail lint by default.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* docs(lint): link graph diagnostics and exclusions (saa-cgh.75)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
2026-09-30 15:55:33 -07:00
Jim Wordelman
9d646fc887
fix(dolt): server-mode bd ready never wakes expired defers (re-proposes #6082) (#6424)
* test(dolt): red — defer auto-wake must run for classified-read-only server-mode opens (be-vbhpf)

TestServerModeDeferAutoWake exercises the same defer/wake contract as the
embedded and proxied-server variants, against a real dolt sql-server. Today
the sweep (DoltStore.wakeExpiredDefers) unconditionally skips whenever the
store is opened read-only — including when that read-only-ness comes purely
from command classification (bd ready/bd list are read-only for the CURRENT
project), which is indistinguishable, before the fix, from a strict
--readonly or foreign-project open that must never sweep.

RED: expired_dated_defer_wakes_on_ready and expired_dated_defer_wakes_on_list_ready
fail (issue never returns to open). dateless_defer_never_wakes and
future_dated_defer_stays_hidden pass today too, trivially (no sweep runs at
all pre-fix) — kept as regression guards for the GREEN step, which is where a
unit test proving classifiedRead=false still does NOT sweep belongs, since
that distinction doesn't exist yet at RED.

* feat: green — defer auto-wake runs for classified-read-only server-mode opens (refs be-vbhpf)

bd ready/bd list on a dolt-sql-server-backed store open with the store
classified read-only for command purposes; the lazy defer-wake sweep
silently early-returned before ever running, so expired defers never
woke unless something else opened the store writable first.

Threads a new ClassifiedRead flag through dolt.Config -> DoltStore,
set at the call site to exactly "read-only because of command
classification, not strict --readonly/preview/foreign-project"
(policy.readOnly && !readonlyMode && !previewMode in main.go).
wakeExpiredDefers's guard now delegates to a small extracted
predicate, deferWakeSweepEligible(readOnly, classifiedRead), so the
truth table can be unit-tested without a live store.

* chore: release gate PASS for be-6iglh-gate

* docs(release-gates): record the be-5fjqh rebase onto current main

origin/main advanced 6 commits past this branch's base and PR #6082 went
CONFLICTING; hourly pr-audit filed be-5fjqh. The branch is now rebased onto
0efe0adf5.

The only conflict was cmd/bd/main.go: this branch and e05000d64 (wy-sbgucn)
each append a field to the same dolt.Config literal at the same anchor line.
Resolved keep-both -- PoolReadTimeoutFallback and ClassifiedRead drive
disjoint code paths.

The addendum records the new base and SHAs, patch-id equivalence for the five
files that did not conflict, what was re-verified at the new base (build plus
the diff-owned tests, container-backed), and what was NOT re-run (the
full-suite and ci-pr-policy lanes still refer to the old base).

Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Jim Wordelman

* docs(release-gates): record the be-qjern re-propose rebase and full re-gate

PR #6082 was closed and its branch deleted 2026-09-01 by an unknown actor
under the shared quad341 identity. Operator ruling 2026-09-08: accidental,
not a rejection — re-proposing. This addendum records a second self-rebase
onto current origin/main (zero conflicts this time), the full-suite and
ci-pr-policy re-gate the 09-01 addendum left outstanding (0 FAIL, policy
FAIL attributed to pre-existing be-mrl6j), and re-verification of both
diff-owned container-backed tests at the new HEAD.

refs be-qjern

* test(feat): red — add strict --readonly server-mode subtest to TestServerModeDeferAutoWake (refs be-acsyx)

* docs(release-gates): green — reword container-backed evidence claims, add nit-3 comment (refs be-acsyx)

bee-ghosttrack nit 2: TestDeferWakeSweepEligibleHonorsClassifiedRead is a
pure-function table test, not container-backed like TestServerModeDeferAutoWake
— reworded release-gates/be-6iglh-gate.md criteria 2(4) and 3 accordingly, and
attributed the preview/foreign-project claim to code structure at
cmd/bd/main.go:1485 rather than to that test. PR #6424 body reworded to match
(not part of this commit; edited via gh pr edit).

bee-ghosttrack nit 3 (optional): one-line comment on the unreachable
"classifiedRead without readOnly" table case explaining it documents totality,
not a reachable state.

Full suite: 0 FAIL. Targeted re-verification (TESTCONTAINERS_RYUK_DISABLED=true
to dodge host-load reaper flakiness): TestServerModeDeferAutoWake 5/5 subtests
PASS (12.427s), TestDeferWakeSweepEligibleHonorsClassifiedRead 4/4 subtests
PASS (5.957s).

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-6iglh-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

* ci(proxied-shard): discover TestServerMode* entry points

Review finding (major, Test Evidence Quality): TestServerModeDeferAutoWake —
this PR's only end-to-end guard for the classified-read defer-wake fix — was
selected by no CI lane. The two lanes that set BEADS_TEST_PROXIED_SERVER=1
both shard through proxied-test-shard.sh, whose discovery grep matched only
`^func TestProxiedServer`, so the wiring lines at cmd/bd/main.go:1675 and
internal/storage/dolt/store.go:2136 had zero CI-executed coverage: the one
CI-reachable new test pins the pure predicate and cannot catch a mis-wired
flag.

Widen discovery to `^func Test(ProxiedServer|ServerMode)` in the shard script
and in scripts/ci/gen_proxied_shard_manifest.py so the two discovery patterns
stay in step, and widen the shard script's manifest-name validation to match.
That last part is load-bearing, not cosmetic: without it a regenerated
manifest containing a TestServerMode* row is rejected outright ("Invalid
shard manifest line") and the whole lane exits 1.

This also rescues the two pre-existing TestServerModeServe* suites, which
share the identical requireSharedProxiedServer gate and the same shared dolt
sql-server harness and were equally invisible — the unclosed class this PR
was following.

Verified: discovery goes 151 -> 154; a 15-shard BEADS_TEST_SHARD_LIST_ONLY=1
dry run assigns each of the 154 to exactly one shard with no pre-existing
test moved (the three land on shards 4/13/15 via hash fallback); the
pre-change script selects none of the three.

Also clarifies the reviewers' nit: the "foreign-project" exclusion named in
the new comments is not tested at the guard or in the policy expression —
those opens build their own dolt.Config and leave ClassifiedRead false, so
the guarantee is fail-closed by default.

Iteration-2 review (two minors, both non-gating): the fixup's own new prose
asserted two universals that measurement falsifies — the same class as the
nit above, reintroduced in the CI files this fixup added.

  * proxied-test-shard.sh claimed "Both families gate on
    requireSharedProxiedServer", contradicted two lines earlier by its own
    mention of the TestProxiedServerPathHelpers unit test. Transitive gate
    census over the 154 discovered entry points: 143 reach
    requireSharedProxiedServer, 10 reach the different helper
    requireProxiedServerEnv, and TestProxiedServerPathHelpers
    (cmd/bd/proxied_server_test.go, bare `package main`, three assert.Equal
    calls on path helpers) has no gate and no build tag, so it also runs in
    every ordinary `go test ./cmd/bd/` lane. Now scoped to the
    TestServerMode* family, which does gate uniformly (3/3), and the
    TestProxiedServer* side is described as mixed rather than generalized
    over.

  * main.yml claimed TestServerMode* discovery means "neither family can be
    silently left out of CI". Discovery is a non-recursive cmd/bd/*_test.go
    glob: 154 top-level matches versus 156 recursive, the difference being
    cmd/bd/doctor/database_test.go:60 and cmd/bd/doctor/dolt_test.go:126.
    Now scoped to the top-level entry points, and the comment names the
    residual hazard (a container-gated suite added under cmd/bd/<subpkg>/ is
    still never selected here) instead of implying it cannot happen.

Both edits are comment-only and behaviorally inert: non-comment lines are
byte-identical in both files, and the 15-shard BEADS_TEST_SHARD_LIST_ONLY=1
sweep is byte-identical before and after (154 assignments, 0 duplicates,
assigned set == discovered set, the three TestServerMode* still at 4/13/15).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* ci(bazel): add defer_wake_server_test.go to cmd/bd go_test srcs

Maintainer CI repair, generated by `make bazel-sync` (gazelle).

`cmd/bd/BUILD.bazel`'s `go_test` srcs is an explicit list, not a glob, so the
new `cmd/bd/defer_wake_server_test.go` was never compiled or run by the Bazel
lane. `Bazel / test` failed two required steps on the pushed head
`0a3f5e0047`:

  Go test equivalence:
    go test:  105 packages, 8988 top-level tests
    bazel:    107 go_test targets, 106 tested; 8987 top-level tests seen
    tests go test runs that Bazel did not (1):
      cmd/bd  TestServerModeDeferAutoWake
    EQUIVALENCE: FAIL

  BUILD files in sync (gazelle, go_srcs, MODULE.bazel): out of sync

`BAZEL_TEST` is listed in `CI_GATE_REQUIRED` for `CI Gate / Required`
(.github/workflows/pr.yml), so this is a required-lane red, not advisory.

That the missing test is this PR's own headline guard makes the repair squarely
in scope: the PR exists to close exactly this "no CI lane runs it" gap, and its
review fixup closed it for the proxied shard lane. The Bazel lane had the same
gap for a different reason.

Attribution: main's Bazel run at this PR's exact base 43a526b828 concluded
success, so the red is this branch's, not inherited.

Validation:
- `make bazel-sync` produces exactly this one line; a second run is a no-op
  (gazelle idempotent, md5 7d1d0549fcd466159451c02181661c78).
- Byte-identical to CI's own `bazel-sync-patch` artifact for this head
  (blob pair efec974..6dd76e3).
- srcs-only change: gazelle added no deps entry, so every import the new file
  needs was already declared.
- `bazel build //cmd/bd:bd_test` succeeds, and the generated
  `bd_test_/testmain.go` now enumerates TestServerModeDeferAutoWake, which is
  the row the equivalence check reported missing.
- `tools/bazel/go_srcs.py --check` was already clean, and `bazel mod tidy`
  produced no MODULE.bazel drift, so this single line is the whole repair.

No contributor commit is modified and no Go source changes.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 15:53:22 -07:00
Harry Miller
dfdedf5dfb
fix(status): disclose the counted rows bd list will not show (#5763)
* feat(stats): count the rows the default listing suppresses

bd status counts the issues table; bd list hides gates and templates on
account of what they are. The two therefore disagree, and nothing
reconciles them: a teardown driven by bd list leaves a gate behind and
status reports a total the operator cannot account for from any listing.

Break the suppressed rows out as their own counts. TotalIssues keeps
counting the database, which is what a command titled "Issue Database
Status" should report; these say how much of that total no default
listing will show. Every backend's statistics path funnels through
ScanIssueCountsInTx, so one query serves all of them.

Infra types need no counterpart here: they live on the wisp plane, which
this query does not read.

* fix(status): disclose the counted rows bd list will not show

bd status reported "Total Issues: 2" for a workspace whose every listing
showed one, because gates and templates are suppressed from a default
bd list. Nothing connected the two numbers, so the remainder read as a
phantom -- most visibly after a teardown driven by bd list, which leaves
its gates behind and then cannot see them.

Report the suppressed rows under the summary they qualify, naming the
flag that reveals each kind. The breakdown is printed rather than a
single hidden-total, since a template gate would otherwise be counted
twice. Nothing is printed when there is nothing suppressed.

Stacked on the statistics counts that make this reportable.

* docs(api): put gate_issues and template_issues on the Statistics schema

The Statistics schema is pinned to types.Statistics, so the two new
counts were on the wire the moment the struct grew them, and
TestWireTagBijection fails the openapi gate until the spec says so:

    Go fields with no spec property: [gate_issues template_issues]

Document both as a breakdown of total_issues rather than an addition to
it — they count rows the default `bd list` suppresses, which
total_issues already includes — and warn against summing them, since a
row can be both a gate and a template.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(status): give --assigned the same disclosure, and test the behavior

Three points from review.

1. `bd status --assigned` never printed the line. AssigneeStats does not
   go through ScanIssueCountsInTx - it folds one actor's rows through
   workapi.FoldStatsAssigneeSummary, which left both new fields zero. That
   route's filter sets only Assignee, so IsTemplate stays nil and the
   actor's gates and protos really ARE in those rows while
   `bd list --assignee` suppresses both: the same reconciliation gap, one
   scope down. The fold now counts them, and its doc says they are set
   deliberately rather than borrowed from a workspace-wide answer.

2. The infra-type suppression is now explained rather than asserted away,
   and the answer is that a durable infra row is NOT unreachable, so the
   third breakdown is filed as GH#6439 rather than dismissed. Both the
   plane routing and the listing's exclusions read the workspace-configured
   types.infra set, and writing that key only invalidates a cache
   (dolt/config.go) - it never moves rows already written. So durable rows
   created while a type was not infra stay durable once it becomes one, and
   a type evicted from the set creates durable rows outright, which the
   create contract already pins ("evicted infra type",
   issue_operations_contract.go). Counting them needs that configured set,
   which ScanIssueCountsInTx - portable SQL with no config seam, called
   from six backend sites - cannot reach; guessing with the built-in names
   would be wrong in exactly the workspaces where it matters.
   suppressedTypeSummary's doc now carries that reasoning.

3. The behavior itself had no test - both existing cases exercised a pure
   string formatter, and would pass with the render call site deleted. Now:

   - TestRenderStatusEmitsTheSuppressedRowsLine captures renderStatus's
     stdout, asserts the line and both parts, and asserts it sits after the
     totals it reconciles rather than in the extended block. It fails with
     the call site removed ("renderStatus did not emit the disclosure
     line"), plus a companion asserting the line is absent when there is
     nothing to disclose.
   - Three conformance cases in stats_reporter_contract.go, wired into all
     three role wirings (dolt, embeddeddolt, uow), so the new SQL is
     checked cross-backend rather than at one call site:
     BreaksOutTheRowsTheDefaultListingSuppresses (with the negative rows a
     loose predicate would also move), BreaksOutAGateThatIsAlsoATemplate
     (the two suppressions are independent, so a proto's gate step counts
     in both), and AssigneeStatsBreaksOutTheSuppressedRows for the fold.
     statsReporterCounts and assertStatsReporterDelta carry the two fields.
     All three are behavioral reds against zeroed counts, not compile
     errors:

         GateIssues moved by 0 (0 -> 0), want 1
         TemplateIssues moved by 0 (0 -> 0), want 1
         GateIssues = 0, want 1 - the actor's gate is in this answer but
           not in `bd list --assignee`

4. Nit: pluralCount takes both spellings instead of appending "s", so a
   caller with an irregular plural is not silently mis-served.

Also adds the CHANGELOG entry the behavior change was missing, including
the GH#6439 gap.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(conformance): declare the new stats cases in the order the table runs them

TestRoleContractCasesCoverEveryContractCase checks more than coverage: the
roleContractCases table has to list cases in the order their contract file
DECLARES them, because that is the order the unit-of-work leg's runners use
and the order its config-writing cases depend on.

I declared all three new cases together, then registered the assignee one
with the other assignee cases in the table, so the two orders disagreed:

    roleContractCases is out of declaration order at position 449: table
    has RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal,
    source has RunStatsReporterAssigneeStatsBreaksOutTheSuppressedRows

Fixed by moving the declaration rather than the table entry, since the
assignee case belongs beside the other assignee-scoped ones anyway - the
grouping the table already had was the correct one. Caught by CI because I
ran go vet over backend/conformance but not its tests; both now pass.

Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(changelog): move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).

Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(status): complete the disclosure's remedy and pin its population

Maintainer review fixes for PR #5763 (adopt-pr iteration 1). Four of the
five review findings taken; the nit is declined with its measurement.

Finding 2 (minor, gate impact minor) - the printed remedy was incomplete.
The two counters come from the same scan as TotalIssues and are status-blind
with it, but the flags they named lift only the TYPE exclusion, so a CLOSED
gate was counted while `bd list --include-gates` still would not show it.
Gates are closed as the work they guard completes, so that is the ordinary
case rather than an edge.

Took the "complete the hint" arm over the "scope the counters" arm. Every
other field ScanIssueCountsInTx fills is workspace-wide; the disclosure
exists to account for TotalIssues, a database number printed three lines
above it; and scoping these two to the listing's population would leave them
explaining nothing about the total they are broken out of. `--all` "replaces
the status exclusions only" and lifts no type exclusion of its own
(backend/conformance/reader_contract.go:487), so the two flags together are
exactly the remedy. Recorded the population in the types.go field comment,
the status.go doc, and the CHANGELOG, which printed the old example verbatim.

Finding 3 (minor) - the three new conformance cases seeded only open rows,
so a backend counting over every status and one counting only the listing's
population returned identical numbers on all of them. Added a closed gate and
a closed proto to the first case. Proved it now decides the question: scoping
both SQL SUMs with `AND status <> 'closed'` reds exactly that case
("GateIssues moved by 1 (0 -> 1), want 2") while the all-open sibling
BreaksOutAGateThatIsAlsoATemplate stays green.

Finding 4 (minor) - the normative role doc in issueops/statsreporter.go
enumerated only the six prior counts. Added the two to that scan's bullet and
corrected two statements this PR had falsified: the headline "six counts of
one set", and the AssigneeStats bullet's "the fold ... tallies the five
statuses and nothing else", which stopped being true when the fold gained the
two increments.

Finding 1 (minor, gate impact minor) - ran `make bazel-sync`. It proposed
exactly one line, `+ "status_suppressed_test.go"` in cmd/bd/BUILD.bazel, and
nothing else, confirmed by porcelain rather than by bazel-sync-check.
Generator-owned, not hand-edited.

Finding 5 (nit) - declined. The three helpers already in package main
(pluralIssue, pluralize, plural) all DERIVE the "s" and cannot render a
caller-chosen pair; the tree's one two-form helper, pluralWord, is unexported
in internal/storage/issueops, and exporting it so a CLI string could reach it
would add exported surface to a storage role for a cosmetic. Recorded that
trade in pluralCount's doc comment instead.

Validation: `go build ./...` and `go vet` (6 pkgs) clean, gofmt clean,
`git diff --check` clean; cmd/bd 4/4 named PASS, internal/httpapi
TestWireTagBijection|TestSpec* PASS, internal/workapi PASS,
internal/storage/uow TestStatsReporterContract 18/18 subtests PASS. Both new
pins are mutation-proved: reverting `--all` reds all four table cases, both
flag subtests and the render-path pin, while the absence assertion stays
green.

Not done here: the PR body carries the same stale example line
("1 gate (--include-gates)"). Review iterations do not touch the PR surface,
so that correction is stamped for finalize.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 15:44:40 -07:00
Julian Knutsen
a7fe6aea50
feat(httpapi): PATCH /v0/beads/issues/{id} accepts claim, the wire spelling of bd update --claim (#6890)
The update operation had no way to express a claim, so an HTTP client of
`bd serve` had to refuse `bd update <id> --claim` outright. The request now
carries a `claim` boolean that passes straight through to
issueops.UpdateRequest.Claim on the same lifecycle role the direct route
uses, so the claim and the patch land in one transaction with the direct
route's semantics: same-actor re-claim is idempotent (changed: false), a
foreign holder is 409 already_claimed and an unclaimable status 409
not_claimable, both naming `claim` and carrying {id}:claim's extension
members (shared through claimRefusal), and a refused claim writes none of
the patch.

With claim: true the patch may be empty (the claim is the whole write).
claim beside expected_assignee, expected_status or force_assignee_transfer
is refused at the edge as a 400 naming `claim` rather than surfacing the
role's ErrValidation as the generic patch 400. No capability token: per the
document's version-skew rules, member presence is probed, and an older
server refuses `claim` as unknown_parameter before any database work.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-09-30 15:42:37 -07:00
postoso
f005323431
fix(cli): document that bd list --format exports the dependency graph (#5723)
* fix(cli): document that bd list --format exports the dependency graph

The --format help read "Output format: 'digraph' ..., 'dot' ..., or Go
template", which reads like a per-issue rendering knob. It is not. Every
non-dot format in outputFormattedList walks the dependency edges between
the listed issues and renders one line per edge, so `bd list --format
digraph` and `bd list --format '<template>'` print nothing at all and
exit 0 whenever no listed issue depends on another. Only 'dot' declares
nodes, so it is the one value that always produces output, which makes
the other two look broken rather than empty.

The template context is the edge too: .IssueID, .DependsOnID, .Type,
.Issue, .Dependency. Nothing named .ID exists at the top level, so a
plausible-looking `--format '{{.ID}}'` renders "<no value>".

Behavior is unchanged. This corrects the advertised surface and adds a
test that pins the edge scope the help now states, covering both halves
of it: no output when there are no dependencies, and no output when the
only dependency leaves the listed set. The second case is the one that
holds the endpoint-membership guard in place, so a listing cannot start
spilling edges to issues the caller filtered out.

Generated CLI docs are not regenerated: docs/cli-docs.pin builds them
from tag v1.1.0, not HEAD, so regenerating here would create drift.
./scripts/check-cli-docs-drift.sh --base main reports PASS.

* docs(cli): name 'json' in the bd list --format help

--format also accepts 'json', special-cased in gatherListInput to mean
--json. The rewritten help read as exhaustive over graph formats, so it
was wrong for exactly that value, which is the defect the rest of the
string is fixing.

Name it, and note the precedence: runListCore's --json branch returns
before the --format branch is reached, so --json wins when both are given.

Verified against a built binary. --format json is byte-identical to
--json, --format JSON matches too since the special case uses EqualFold,
and --json --format digraph prints the JSON listing rather than the edge
list that --format digraph prints on its own.

---------

Co-authored-by: postoso <postoso@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:38:37 -07:00
Vishnu J
5e0a5b649d
fix(prime): document all three PRIME.md fallback tiers in --help (#6275)
* fix(prime): document all three PRIME.md fallback tiers in --help

bd prime --help named a single PRIME.md location ("the local clone or
resolved workspace"), which conflates the current-directory and
resolved-workspace tiers and omits the global fallback entirely.
readCustomPrimeContent checks three locations in order: .beads/PRIME.md
relative to the current directory and PRIME.md in the workspace .beads
directory (both introduced together in GH#876), then
~/.config/beads/PRIME.md (added for GH#2330). Users and agents had no
way to discover that order from --help.

Document all three tiers in lookup order: tier 1 is
current-directory-relative, not clone-wide; tier 2 is the .beads
directory bd resolves for this workspace (described by outcome, since
FindBeadsDir has several resolution paths, most of which follow a
redirect); tier 3 is the global config fallback. The lead-in notes that
the lookup runs only once bd resolves a workspace, since runPrime
returns before readCustomPrimeContent otherwise (emitting no content,
or an empty --hook-json envelope). The single long help line becomes a
short bullet list with no line longer than the surrounding text.

Add TestPrimeHelpMentionsAllFallbackTiers, which asserts the tiers are
documented and appear in their actual lookup order.

Fixes gastownhall/beads#6095

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(prime): spell out per-OS user config dir for tier (3) in --help

Follow-up to #6095 review on #6275 (bee-ghosttrack, MAJOR 1 + MAJOR 2).

Tier (3) of the PRIME.md lookup order named ~/.config/beads/PRIME.md as
the global path, but resolveGlobalPrimePath uses os.UserConfigDir(),
which is ~/Library/Application Support on macOS (XDG_CONFIG_HOME is not
consulted) and %AppData% on Windows. On those platforms the help text
pointed users at a file bd never reads, reproducing the confusion #6095
exists to fix. Reword tier (3) to name the user config dir and list the
Linux, macOS, and Windows spellings.

TestPrimeHelpMentionsAllFallbackTiers no longer pins the Linux spelling
as its tier-3 needle; it asserts the platform-neutral "user config dir"
wording, checks that all three per-OS paths appear (the help text is
static, so every spelling must be present), and includes the literal
(1)/(2)/(3) labels in the ordering needles so that swapping only the
labels fails.

Docs-only: resolveGlobalPrimePath is unchanged; aligning its location
with the ~/.config/beads credentials path is left for its own issue.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs(prime): make the PRIME.md tier help accurate under -C

Maintainer review fixes for #6275, review iteration 1. Both lanes and the
quality scorecard returned approve with no required changes; this commit takes
the two non-gating items, both text-only.

Taken:

- Contract & Interface Fidelity (minor, both lanes). Tier (1) is resolved
  against primeWorkspaceDir(), which returns the absolute -C target when -C is
  set (prime.go:281-289), so "relative to the current directory" was wrong
  under `bd -C dir prime`. And tier (2)'s "honors $BEADS_DIR" was imprecise:
  applyChangeDirSelection does os.Setenv("BEADS_DIR", resolveChangeDirBeadsDir(
  -C target)) (main.go:943-956) before the command runs, so an exported
  $BEADS_DIR is silently outranked by -C. Both amendments are help text only.
  Verified at source rather than taken from the finding. Note the review's
  suggested wording was written in markdown; the surrounding help text uses no
  backticks, so the amendment matches the block's own plain style.

- Test Evidence Quality (nit, codex + claude). The comment claimed a
  label-only swap "still fails the ordering check below", but since the (N)
  label sits inside each needle such a swap drives every strings.Index to -1,
  which trips the presence t.Errorf while the ordering loop explicitly
  continues past -1. Reworded to name the assertion that actually catches it.

As base drift already moved tier (1) under the -C target without updating
base's own primeCmd.Long, the PR remains a strict improvement over base prose
either way.

Validation: gofmt clean, go build ./cmd/bd/ and CGO_ENABLED=1 go vet ./cmd/bd/
clean. TestPrimeHelpMentionsAllFallbackTiers still PASSES -- its three needles
are prefixes of the amended lines, so the ordering pin is untouched. Under
-run Prime: 61 PASS / 1 FAIL / 3 SKIP, and the single failure
(TestPrimeBinaryPortfolio) is pre-existing host contention, proven by a control
run at the unmodified head c9cfb3e416 which fails identically with the same
cause ("cannot start dolt server on port ...: busy").

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 15:31:52 -07:00
Jim Wordelman
ed15632a16
fix(cli): preserve redirect-source dolt_database for no-DB commands, guarded on explicit targets (#5774)
* fix(doctor): preserve redirect-source dolt_database for no-DB commands (be-xil)

selectedNoDBBeadsDir() (used by doctor/bootstrap/context/dolt no-DB
commands) resolves an ambient beads dir via beads.FindBeadsDir(), which
always follows a .beads/redirect internally before returning. By the
time prepareSelectedNoDBContext's own internal
preserveRedirectSourceDatabase call sees a beadsDir, it is already the
post-redirect target (which has no redirect file of its own), so the
source repo's configured dolt_database is silently never captured into
BEADS_DOLT_SERVER_DATABASE. doctor's Dolt health checks still open the
store via BEADS_DOLT_SERVER_DATABASE when set, so this left doctor
falling through to the shared target's own default database and
reporting a false "wrong database" diagnosis with a destructive --fix.

Call preserveRedirectSourceDatabase with the source dir explicitly
before selectedNoDBBeadsDir() resolves and loses that information,
mirroring the pattern already used by the store-requiring
PersistentPreRunE path just below it.

go build/vet ./cmd/bd/... clean; new regression test and sibling
PersistentPreRun tests pass.

* test(doctor): red — explicit --db target must override ambient redirect

Adds TestDoctorPersistentPreRunExplicitDBTargetOverridesAmbientRedirect,
covering both reviewers' round-1 change request: an explicit --db target
must not be shadowed by an ambient repo's unrelated redirect-source
database. Currently RED — preserveRedirectSourceDatabase() is called
unconditionally, so BEADS_DOLT_SERVER_DATABASE leaks the ambient repo's
redirect-source db past the explicit target.

refs be-fyt

* fix(doctor): green — guard redirect-source preservation on explicit --db

Round 1 of be-fyt review: preserveRedirectSourceDatabase() was called
unconditionally inside the skipsStoreInit branch, mirroring the guard
already present on the store-requiring sibling branch below it. Since
beads.GetRedirectInfo() always resolves from the ambient CWD repo's
local .beads regardless of --db/BEADS_DIR (bd-wayc3), an explicit
--db/BEADS_DB/BD_DB target's own database was silently shadowed by the
ambient repo's unrelated redirect-source database — reopening be-xil's
failure mode via a narrower trigger.

Fix: only preserve the redirect-source database when dbPath is unset,
matching the existing guard at the sibling call site.

TestDoctorPersistentPreRunExplicitDBTargetOverridesAmbientRedirect now
passes; full ./cmd/bd/... suite shows the identical 9 pre-existing
be-j8e-class failures as the pre-fix baseline, no new failures.

refs be-fyt

* docs(release-gates): add be-27c gate record

Explicit --db target must override ambient redirect-source database
(be-xil follow-on). PASS 7/7, independently re-verified.

* test(doctor): red — BEADS_DB/BD_DB leak past the redirect-source guard

The skipsStoreInit guard added in 848ed9f9 is spelled `dbPath == ""`, and
the PR body describes it as covering "an explicit --db, BEADS_DB, or BD_DB
target". It does not: main.go:1002-1004 only falls back to the configured
db when BEADS_DB, BD_DB and BEADS_DIR are all unset, so with either env var
set and no --db flag, dbPath stays "" and the guard reads "no explicit
target given" for a caller that gave a perfectly explicit one.

selectedNoDBBeadsDir (main.go:519, :523) does honor BEADS_DB and BD_DB, so
the two disagree: BEADS_DIR is correctly rebound to the explicit target
while the ambient repo's redirect-source database is preserved into
BEADS_DOLT_SERVER_DATABASE anyway. That is be-xil's "wrong database"
failure mode, still live for two of the three targets the guard names.

Both subtests fail at this commit:

  BEADS_DOLT_SERVER_DATABASE = "ambient_source_db", want ""
    (leaked past an explicit BEADS_DB target)
  BEADS_DOLT_SERVER_DATABASE = "ambient_source_db", want ""
    (leaked past an explicit BD_DB target)

Reported in review of PR #5774 by bee-ghosttrack, item 2.

* fix(doctor): green — guard on the explicit target, not on dbPath

Replace the `dbPath == ""` guard with explicitDBTargetGiven(), which asks
the question selectedNoDBBeadsDir asks — dbPath, BEADS_DB, or BD_DB — so
the two cannot drift apart again. Both subtests from the previous commit
now pass; the four pre-existing PersistentPreRun tests are unchanged.

Deliberately NOT keyed on PersistentFlags().Changed("db"), which the review
suggested as the condition. A --db value naming a *database* rather than a
path is moved to dbNameFromDBFlag and clears dbPath (main.go ~990), and it
is consumed only on the store-requiring path (~1553, proxied-server mode).
On the no-DB path selectedNoDBBeadsDir therefore finds no explicit
directory target and falls through to beads.FindBeadsDir(), which follows
the ambient repo's redirect — so the ambient workspace IS what gets
selected and its source database must still be preserved. Measured on the
previous commit with `bd doctor --db somebaredbname` in a redirected repo:

  dbPath=""
  BEADS_DIR=".../ambient-shared/.beads"      ← ambient redirect target
  BEADS_DOLT_SERVER_DATABASE="ambient_source_db"   ← correctly preserved

Keying on Changed("db") suppresses that and reopens be-xil for
`bd doctor --db <name>`. TestDoctorPersistentPreRunBareDBNameStillPreserves-
AmbientSourceDatabase pins it: with Changed("db") in the predicate it fails
with `BEADS_DOLT_SERVER_DATABASE = "", want "ambient_source_db"`.

(A free function referencing rootCmd also cannot compile here — it forms an
initialization cycle through rootCmd's own PersistentPreRunE — so that
variant would need cmd threaded through, as selectedNoDBBeadsDir does.)

Addresses review of PR #5774 by bee-ghosttrack, item 2.

* docs(changelog): record the redirect-source database fixes

Both entries under Unreleased/Fixed: the be-xil preservation for no-DB
commands, and the be-fyt explicit-target guard on top of it. Called out in
review of PR #5774 by bee-ghosttrack as a non-blocking gap — this is a
behavior change to bd doctor/bootstrap on every redirected workspace and
was not recorded anywhere users read.

* test(doctor): compare BEADS_DIR canonically so macOS passes

CI caught this on macos-latest (the only failing check on this PR):

  doctor_context_test.go:376:
    BEADS_DIR = "/private/var/folders/.../ambient-shared/.beads",
         want  "/var/folders/.../ambient-shared/.beads"

Same directory. On macOS /var is a symlink to /private/var, so t.TempDir()
hands back the /var form while the value under test is resolved through
beads.FindBeadsDir() -> utils.CanonicalizePath, which runs EvalSymlinks.
A raw string compare therefore fails on macOS and nowhere else.

Both of the assertions added in this PR now canonicalize each side before
comparing. Only my two are touched: the pre-existing sibling assertions
reach BEADS_DIR via resolveCommandBeadsDir(dbPath), which does not
EvalSymlinks, so they are unaffected and left alone rather than churned.

Canonicalizing is a no-op where the path is already resolved, so this is
symmetric and cannot mask a genuine mismatch — the assertion still fails if
a different directory is selected. Verified utils.CanonicalizePath does
resolve symlinks with a throwaway probe (symlink in, real path out).

* docs(cli): correct the "cannot drift apart" claim, name the BEADS_DIR gap

Review item 5 (round 2, PR #5774) is right and the claim in the code was
wrong. explicitDBTargetGiven covers three routes; selectedNoDBBeadsDir
honors a fourth — BEADS_DIR != "" -> beads.FindBeadsDir() (~line 551) —
so the two predicates still disagree there, and the comment asserting they
"cannot drift apart again" pointed a future reader at exactly the wrong
conclusion.

Reproduced before writing this, rather than taking the review's probe on
faith. At this head, BEADS_TEST_SKIP=dolt, ambient repo git init-ed with
an active redirect and BEADS_DIR naming an unrelated target:

  PROBE[git_repo]:  BEADS_DIR=".../target/.beads"
                    BEADS_DOLT_SERVER_DATABASE="ambient_source_db"  <- leaked
                    dbPath=""
  --- FAIL: .../git_repo
  --- PASS: .../plain_dir

The plain_dir control passes, which pins the defect to the bd-wayc3 branch:
GetRedirectInfo only reaches the ambient repo through findLocalBdsDirInRepo
(internal/beads/beads.go:394), which keys off git.GetRepoRoot() alone. Every
test in doctor_context_test.go builds a plain t.TempDir(), so the branch
production always takes has no coverage — that is the second half of it.

Comments only; no behavior change, and the gap is documented rather than
closed here deliberately. Emptiness is the wrong test for it: BEADS_DIR
pre-set to the redirect target is bd-wayc3's own case, where preservation is
wanted, so the fix has to compare BEADS_DIR against the redirect target.
That comparison, the git-repo fixture and the third test case are specified
in be-bf75p with the probe source attached.

gofmt/vet/build clean; go test ./cmd/bd/ -run
'TestDoctorPersistentPreRun|TestBootstrapPersistentPreRun' green.

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-27c-redirect-source-guard-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

---------

Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:29:36 -07:00
ecuthiell
1d637e12fc
fix(init): select the project origin before proxied persistence (#6453)
* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(config): explain role command routing policy (saa-cgh.99)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Keep init role operations on the captured selected Git context (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): select project origin before proxied persistence (GH#6384) (saa-cgh.120.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(init): use branch-local origin lookup fixtures (GH#6384) (saa-cgh.120.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(init): distinguish inline origin and normalize SCP remotes (saa-cgh.120.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(init): discriminate inline origin URL rewriting (saa-cgh.120.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): keep discovery fences out of the routing scrub

Maintainer review fixes for the three majors in iteration 1.

Finding 1 -- routingKeys conflated Git's *redirect* keys with its *fence*
keys. Scrubbing a redirect narrows the authority a child inherits, which is
this package's purpose; scrubbing a fence widens it. Remove
GIT_CEILING_DIRECTORIES and GIT_DISCOVERY_ACROSS_FILESYSTEM from the set and
document why they must stay out. Reproduced at this head: under
GIT_CEILING_DIRECTORIES=$P/child, `git -C $P/child/sub config beads.role
maintainer` is refused (exit 128); with the ceiling scrubbed it exits 0 and
writes the privileged role into $P/.git/config. This matters most at the four
cmd/bd/config.go role sites, which pass neither -C nor cmd.Dir, and `-C` names
a directory rather than a repository, so an explicit directory is not a
substitute for the fence.

The other half of that finding -- narrowing the GIT_CONFIG prefix so
GIT_CONFIG_NOSYSTEM/_GLOBAL/_SYSTEM survive -- is deliberately NOT applied
here. Open PR #6461 already implements it value-aware (isConfigSuppression
retains GIT_CONFIG_GLOBAL=/dev/null but still scrubs
GIT_CONFIG_GLOBAL=/tmp/evil), which is stricter than the key-only form the
review prescribed. Applying the key-only form here would make
IsRoutingKeyForOS return false for the whole key and bypass #6461's value
check once the two merge. The injection channel this package must close, the
GIT_CONFIG_COUNT/KEY_n/VALUE_n triple, is covered either way. Tracked in
bd-dz16y.

Finding 2 -- the comment at cmd/bd/config.go:202 claimed "All role commands
ignore inherited Git routing", but only the writers are scrubbed; the readers
that resolve maintainer-vs-contributor are not. Scope the claim to the writers
in that file and name the uncovered plane, rather than duplicating reader
scrubs that open PR #6461 already carries for internal/routing,
beads.RepoContext, bd config show and bd doctor role (hooks.go is carried by
#6454/#6463/#6464). Tracked in bd-dz16y.

Finding 3 -- the scrubbed startup probe gitDirsForRepo has two byte-identical
unscrubbed twins in internal/beads, so the PR created a config-from-repo-A /
workspace-from-repo-B divergence. Take the documentation arm: worktrees.md no
longer claims every startup probe scrubs. #6461 hardens both twins; the code
half is tracked in bd-5p25o.

Also drop the dead isRoleGitRepo helper (Finding 5): it ran the same argv,
Dir and scrubbed env as the gitUC.IsGitRepo call whose result it was compared
against, so it always equalled isRepo while doubling a git subprocess. Its
comment also asserted that dropping discovery ceilings is intended, which the
Finding 1 fix falsifies.

Tests: a unit pin that the two fences survive ScrubRoutingForOS on both POSIX
and Windows semantics, and a behavioural pin that a scrubbed `git config`
cannot escape an operator ceiling into the containing repository. Both were
verified red before this change (IsRoutingKeyForOS = true, want false;
"scrubbed git config escaped the operator's ceiling") and green after.

Iteration 2 (non-gating minors/nits; scorecard 881/1000 approve, no blockers
or majors remained).

The routingKeys doc split the two removed keys by polarity instead of calling
both "fences". GIT_CEILING_DIRECTORIES withholds authority, so the "removing
one widens" direction claim is true only of it. GIT_DISCOVERY_ACROSS_FILESYSTEM
is permit-only: git already stops at a filesystem boundary, unset IS the stop,
and the variable exists only to disable it, so retaining an inherited =1 can
only widen. Retention is kept deliberately -- scrubbing it would cost a
legitimate cross-mount checkout every `bd worktree` verb, the minor PR #6464
iteration 2 adjudicated -- and the comment now states the cost that buys:
base 566c84ba8 scrubbed both keys in scrubWorktreeRemovalGitEnv's own
hardcoded exactKeys list, so re-pointing that adapter at ScrubRoutingForOS
reverses base policy for this key. The losing side is recorded in bd-dz16y.
The fences pin now carries a GIT_DISCOVERY_ACROSS_FILESYSTEM=1 row; the
previous =0-only fixture pinned git's own default, so a value-aware scrub that
retained only the no-op value would have passed it (probed: =0 retained, =1
dropped).

The cmd/bd/config.go:202 enumeration named only unscrubbed readers, but
bd init's own role accessors are unscrubbed too and one is a WRITER
(getBeadsRole init.go:2990, setBeadsRole init.go:3004,
init_contributor.go:345, none passing Env, Dir or -C). So two writes can
disagree, not just a write and a read: `bd init --role` can persist beads.role
into the inherited-routing target while `bd config set` writes the scrubbed
one. Those files are outside this PR's range, so the claim is corrected here
and the code gap is tracked in bd-dz16y item 2.

The ceiling pin now enters the fenced directory with t.Chdir instead of
setting cmd.Dir, matching the four production role sites that pass neither -C
nor cmd.Dir. Re-verified red before the fix in the new shape ("scrubbed git
config escaped the operator's ceiling"), green after.

Pre-approval CI: repair the two-way collision with #6477, which landed on
main during this PR's review.

#6477 (cf683435e) narrowed GetConfig's error swallow: only exit 1 with empty
stderr still reads as "absent"; everything else, including exit 128, now
surfaces. Each side is green alone, but merged they red in both directions,
and both reds are interaction-only (verified: this head alone green, main
alone green, merged red).

- This PR's TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted
  `require.NoError` with the comment "The existing reader maps Git exit errors
  to absence" -- naming the exact premise #6477 deleted. The malformed
  captured-HOME config now surfaces instead of reading as "no role set", so
  the case expects the error. What it pins is unchanged: the generic
  constructor still resolves against the current caller environment.
- #6477's TestConfig_ReadFailuresAreNotMissing/invalid_routing_boolean poisons
  GIT_CONFIG_NOSYSTEM and read beads.role. That key is precisely the one this
  PR makes immune to inherited config routing, so the case could no longer
  observe its own poison. Retargeted to a non-role key (test.marker still
  exits 128 with the same diagnostic, verified), and the role leg inverted to
  pin the immunity instead -- dropping the scrub turns that NoError back into
  the exit-128 routing error, so the case now guards the hardening rather than
  merely avoiding it.

Rebased onto main (511849496) to express the main-side half; the rebased tree
is byte-identical to `git merge-tree origin/main HEAD`, so this is the
combination that will land.

Validation on the refreshed head: build, gofmt, `git diff --check`, `go vet`
and `GOOS=windows CGO_ENABLED=0 go vet` over all 11 changed packages, all
clean. gitenv/execenv/githooksenv/gittraceenv/storage-domain-git/config/
metrics/scripts suites green. `BD_LINT_NEW_FROM_MERGE_BASE=511849496 make
ci-pr-lint`: 0 issues on both the linux and windows arms. cmd/bd was run with
one selector over both sides' changed test files at this head and at main
alone: the FAIL and SKIP sets are byte-identical (16 base-preexisting init/
workspacegate failures, one of which names another test's temp dir), so this
PR adds no new cmd/bd failure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(init): note proxied-init fingerprints still inherit Git routing

Maintainer review fix for the one minor in relaunch iteration 1 (codex,
verified by the synthesis).

resolveProxiedInitRemoteURL now reads origin from the selected project
through the routing-scrubbed NewInitGitRepository, but the repo_id and
clone_id computed right after it still come from beads.ComputeRepoID and
beads.GetCloneID. Both reach git through runGitInRepo/mainRepoRootForPath
in internal/beads/fingerprint.go, which set only cmd.Dir and inherit the
process environment. Probed at 8e77aa3523 with a throwaway package that
calls the real functions: under a decoy GIT_DIR + GIT_WORK_TREE both IDs
equal the decoy repository's; under a missing GIT_DIR both fail with "not
a git repository"; with no routing both match the selected project.

The review offered two arms. Arm (b), naming these calls in the #6460
deferral note, would record a false plan: #6460 scrubs the EnsureGitRepo
bootstrap and leaves both fingerprint calls unchanged, and no open PR
touches fingerprint.go. Arm (a), scrubbing inside the fingerprint helpers,
changes which repository bd doctor, bd migrate and embedded bd init
fingerprint for users who export GIT_DIR on purpose; that policy change
needs its own review. So the #6460 note stays as it is (it is still true),
a comment at the fingerprint call site names the gap, and the code change
is filed. Tracked in bd-6e967, which also carries the review's nit (no
test pins the cwd wiring at the resolveProxiedInitRemoteURL call site).

Validation: git diff --check and gofmt clean; go vet -tags gms_pure_go
./cmd/bd clean; golangci-lint --new-from-merge-base=origin/main
./cmd/bd/... 0 issues; TestProxiedInitRemoteURLUsesSelectedProject
passes.

Agent-Signature: claude-code-unknown-model-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-09-30 13:12:24 -07:00
Michael Hackner
98ab920417
fix(show): render Created/Started/Updated in local timezone (#5980)
* fix(show): render Created/Started/Updated in local timezone

bd show printed these stored-UTC timestamps as bare dates without
converting, so if it's already tomorrow in UTC, the whole calendar day
was wrong.

Storage is unchanged and still UTC, as is --json.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* test(show): stop swapping time.Local in TimestampsRenderLocal

TestFormatIssueMetadata_TimestampsRenderLocal assigned the process-global
time.Local to pin a Pacific zone. Every time.Now() in the process reads that
variable, including goroutines no test can synchronize with: a net/http
connection from the serve test winding down after it returns, and the event
collector Dolt starts at package init. The swap is a data race, and -race
reports it whenever the unsynchronized read is still in the detector's
history: Bazel prcore shard 9 on this PR, and the test run alone (3/3).

Hand the stamp over in a zone twelve hours ahead of time.Local instead, so
its own digits fall on the next calendar day on any machine and only a
conversion to local time prints the right date. No global is written, so
the test runs in parallel like its neighbors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Merge Queue <merge-queue@gascity.local>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-09-30 08:46:43 -07:00
ecuthiell
448c4b8621
test(prime): use native config root in global fixture (#5778)
* test(prime): use native config root in global fixture

The global PRIME override fixture staged Linux and macOS paths while the Windows child resolved os.UserConfigDir from inherited APPDATA. Build one isolated profile, ask the host for its native config directory, and stage the override only at that path. Production behavior is unchanged.

Related to #4638.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* test(prime): create advertised profiles and exercise Windows fixture

Create each isolated profile directory before exporting its path. Run the
global override through the shared test runner in the existing required
Windows job, rejecting absent, skipped or failed selected coverage.

Agent-Signature: unknown-model/unknown-reasoning

---------

Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 07:26:09 -07:00
Rongjun GENG
11ec3a67bc
fix(list): resolve short/partial parent IDs for --parent (#5440) (#5794)
`bd list --parent <shortid>` (the id without its project prefix, e.g.
"c7v" instead of "tm-c7v") errored "not found: issue c7v" instead of
resolving the same way `bd history <shortid>` already does (GH#4868).
getHierarchicalChildren called store.GetIssue(ctx, parentID) directly
on the raw CLI value with no partial-ID resolution step at all.

Fixed by calling the same utils.ResolvePartialID used by bd history,
right at the top of getHierarchicalChildren, mirroring history.go's
own error handling: a resolved ID replaces parentID; an ambiguous
match is a hard error; a genuine not-found falls through unchanged so
the existing "parent issue '%s' not found" message still fires with
the id the user actually typed.

Scoped to exactly the code path the issue's repro hits (local/embedded
mode's getHierarchicalChildren, used by plain `bd list --parent` and
`--tree --parent`). Did not extend to:
- gatherProxiedHierarchical (list_show_filter_modes.go/
  list_proxied_server.go), the proxied-server equivalent -- history.go
  itself documents that proxied mode has no local store to resolve
  against and intentionally passes the raw ID through for the server's
  own lookup to handle, so this isn't an oversight to fix, it's the
  existing convention.
- `--json --parent <shortid>`, which takes an entirely different code
  path (reader.List's own ListRequest filter, built by
  BuildListFilter/LoadStoreListConfig, never touching
  getHierarchicalChildren at all) and has the same underlying gap but
  fails differently -- silently returns [] instead of erroring.
  Confirmed via manual repro. A real, separate defect, but fixing it
  means resolving in a materially different layer (the filter
  builder, not a single CLI command's helper), which is a broader
  change than this issue asked for.
- The same shape of bug in `bd create --parent`, `bd ready --parent`,
  and `bd label --parent`, which independently call GetIssue on a raw
  --parent value the same way. Noticed while tracing this, not
  reported, not verified beyond a grep -- flagging rather than
  expanding scope on unconfirmed instances.

RED: added TestEmbeddedList/parent_filter_short_id, a real embedded-
Dolt CLI subprocess test (BEADS_TEST_EMBEDDED_DOLT=1) using the plain
(non-JSON) render to match the issue's own repro and the existing
tree_parent test's pattern. First draft used bdListJSON and passed
trivially even pre-fix -- caught by checking which exact code branch
the JSON path takes (jsonOutput's early return in list.go, well before
getHierarchicalChildren) and confirming zero-debug-output during
manual tracing; switched to bdList once that was understood. Confirmed
RED against unfixed code (children missing from output) before writing
the fix.
GREEN: children appear via both the full ID and the short ID after
the fix.

Verified: full TestEmbeddedList suite (51 subtests) green, no
regressions -- ran twice, once after the initial fix and once after
correcting the test to hit the right code path. go vet clean.


Claude-Session: https://claude.ai/code/session_018c3vLFNVgPebSpCJrd8xTD

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-09-30 07:23:35 -07:00
ecuthiell
e766da5ed0
fix(worktree): preserve CRLF gitignore appends (#5677)
* fix(worktree): preserve CRLF gitignore appends (#5670)

Choose CRLF only when the user repository's existing .gitignore delimiters are consistently CRLF. Preserve existing bytes and retain LF as the default for every other convention.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* fix(worktree): complete trailing CR before a CRLF gitignore append

Append only LF when the last existing byte already supplies the CR in the
file's unambiguous CRLF convention. Preserve all existing bytes and cover the
exact output and repeated-add behavior.

Refs gastownhall/beads#5677
Agent: unknown-model/unknown-reasoning

* docs(worktree): clarify LF trailing CR completion (saa-cgh.83)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): reuse the shared gitignore line-ending detector (saa-cgh.83)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(gitignore): keep line ending coverage with its shared owner (saa-cgh.83)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* build(bazel): enumerate worktree_gitignore_eol_test.go in cmd/bd go_test srcs

cmd/bd/BUILD.bazel lists go_test srcs explicitly (647 entries), so the new
untagged test file added by this PR is not compiled into //cmd/bd:bd_test.
`make bazel-sync-check` cannot see this: it only runs tools/bazel/go_srcs.py,
which manages the go_srcs filegroup glob, not the go_library/go_test srcs
lists. The bazel.yml "BUILD files in sync" step runs `make bazel-sync` and
fails on any resulting porcelain drift, so gazelle adding this entry would
red that job; the lane is armed for this fork PR via
`github.event.pull_request.head.repo.fork == true`.

This line is gazelle's own output: re-running `make bazel-sync` after it
leaves the file unchanged. With it, both of the PR's new tests execute under
bazel (TestAddToGitignoreCompletesTrailingCR PASS in shard 3/16,
TestAddToGitignorePreservesCRLFWhenAppending PASS in shard 4/16;
//cmd/bd:bd_test 8 PASS / 0 FAIL / 0 SKIP) instead of being silently
excluded from every bazel target.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(worktree): cover the CRLF append arm that uses the detected line ending

Maintainer review fix for PR #5677, adoption iteration 1. The synthesis is
`approve` with no required changes; the one actionable finding is a minor, and it
is taken because the PR already owes a push (the rebase needed a repair and a
maintainer bazel commit is already on the branch).

addToGitignore's `separator := lineEnding` is guarded twice: the block is only
entered when the file does not end in "\n", and inside it a trailing "\r" is
completed with a bare "\n" instead. So the detected "\r\n" is used for exactly one
shape -- a CRLF file whose final byte is neither, i.e. an unterminated final line.
Neither existing fixture reaches it: "a/\r\nb/\r" ends in CR and takes the
completion branch, and "node_modules/\r\n" ends in LF so the block is never
entered. internal/gitignore's own table already covers this input for the
detector; the call site that consumes it did not.

The new case asserts the exact bytes for initial "node_modules/\r\nbuild/", and
appends twice so idempotence is covered as well as CRLF correctness.

Mutation-proved: replacing `separator := lineEnding` with a hardcoded "\n" --
which would write the mixed-terminator .gitignore this PR exists to prevent --
reds ONLY this new test; all three pre-existing tests stay green. That is the
surviving mutant the review reported, and it is now dead.

The remaining nit asked for no change ("None required": the inline duplication of
the append policy is byte-for-byte nil today, deliberate because the O_APPEND
stream cannot take a whole-buffer API, and locked by exact-byte tests), so none
was made.

Not included: `make bazel-sync` also wants an `upgrade_smoke_loop_test.go` row in
scripts/BUILD.bazel. That is base drift, not PR content -- the row is absent at
this branch's rebase base (147047e153) but origin/main already carries it, 33
commits ahead -- so it heals on the next base refresh, and adding it here would
duplicate main's own fix on a file this PR does not touch.

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 01:46:12 -07:00
ecuthiell
3f9561db2b
fix(show): preserve last-touched under --readonly (#5786)
* fix(show): preserve last-touched in readonly mode (#5785)

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* chore(bazel): enumerate last_touched_readonly_test.go in cmd/bd go_test srcs

adopt-pr maintainer fixup for PR #5786. The PR adds a new
//go:build cgo test file to cmd/bd; gazelle enumerates plain-cgo
test srcs unconditionally (330 of 645 enumerated srcs at the base
carry exactly that tag), so the new file is a real srcs-enumeration
gap. Produced by `make bazel-sync`; no hand-edits.

* fix(last-touched): guard ClearLastTouched, name both readonly triggers, add CHANGELOG entry

Maintainer review fixup for the adopt-pr review of #5786 (iteration 1,
synthesis approve, 0 blocker / 0 major).

- CHANGELOG: add the missing [Unreleased]/Fixed entry naming --readonly,
  bd show and .beads/last-touched, linking #5785. Anchored at the tail of
  the Fixed list rather than its top, which is where main appends.
- last_touched.go:65: the comment said "Strict --readonly", but the guard
  also fires when the flag is absent and readonly:true is set in config
  (main.go:1124 folds the config key into readonlyMode). Reworded to match
  the repo's canonical phrasing at serve.go:617-618.
- ClearLastTouched: take the same readonly early return. Removing the
  marker is as much a mutation of workspace-local state as writing it, so
  this makes the file's stated invariant true rather than narrowing the
  comment to match the gap. Zero production callers today (definition plus
  one non-readonly test caller), so no shipping behavior changes.

Declined, both non-gating and both "Required fix: None for merge": moving
the cmdCtx.ReadonlyMode write in PersistentPreRunE (serve.go:612-618
documents reading the global deliberately, and the divergence is latent
rather than live), and its conditional test arm, whose antecedent is false
once the hardening is declined.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 18:17:57 -07:00
Rome Thorstenson
6530c7532f
feat(update): add -l shorthand for --add-label, matching bd create -l (#6139)
* feat(update): add -l shorthand for --add-label, matching bd create -l

bd create registers labels as StringSliceP("labels", "l", ...), so
`bd create -l foo` works. `bd update -l foo` did not: cobra prints usage
and exits 1 on an unknown shorthand.

That is a correct failure but an easy one to miss. A caller copying the
create form has no reason to expect the flag to differ, and the failure
looks like help output rather than an error in a scrolled log. In one
deployment this left issues believed-labelled that were not, until
someone checked by hand.

Additive: --add-label is unchanged. -l maps to ADD rather than SET
because add is the non-destructive reading and matches what create -l
does on a new issue. -l was previously unregistered on updateCmd (its
shorthands are -s, -t, -e), so there is no collision.

go test ./cmd/bd/ -run Update passes.

Executed-By: mayor

* fix(update): drop backquotes from the --add-label usage string

pflag's UnquoteUsage reads the first backquoted span in a usage string as
the flag's ARGUMENT NAME, so "-l matches `bd create -l`" rendered the flag
as

  -l, --add-label bd create -l       Add labels (repeatable); ...

in `bd update --help`, where every sibling shows its type. It now reads
`-l, --add-label strings`, matching --remove-label and --set-labels.

Adds the shorthand assertion the review asked for, plus a guard on the
rendered argument name so the backquotes cannot come back unnoticed. Both
verified red before green: restoring the backquotes fails the second test
with the string it renders, dropping -l fails the first.

* build(bazel): list update_add_label_shorthand_test.go in cmd/bd go_test srcs

cmd/bd/BUILD.bazel's go_test enumerates test srcs explicitly rather than
globbing, so the PR's new test file is invisible to `bazel test //...`.
This is review iteration 1's one minor finding (Change Impact / Blast
Radius, gate impact minor).

The drift is merge-target-attributable and this PR is its sole source:
`bazel run //:gazelle -- -mode=diff cmd/bd` (bazel 9.2.0) proposes five
srcs entries and four deps here, but the other four srcs and all four
deps are already present at origin/main -- only this file is absent
there. The reviewers' `if:`-guard uncertainty resolves against the PR:
bazel.yml's `bazel-test` job, which owns the "BUILD files in sync" step,
is gated on `vars.RBE_WEST_WORKERS == 'true' || inputs.rbe == 'off' ||
github.event.pull_request.head.repo.fork == true`, and #6139 is a fork
PR, so the third disjunct holds and the job runs. That step runs
`make bazel-sync` and fails on any `git status --porcelain` output, and
bazel-autofix.yml only pushes its patch to same-repo branches (forks get
an apply recipe), so the drift would not self-heal.

Deviation from the prescribed remedy, deliberate: the finding said to run
`make bazel-sync`, but on this 25-commit-old base the generator would
also add the eight entries that are pure base staleness and already at
the merge target. Only the single PR-owned entry is added here, in
gazelle's own proposed position (sorted, between uow_factory_test.go and
update_claim_proxied_test.go).

Verified: re-running gazelle no longer proposes this file (the other
eight remain untouched); `make bazel-sync-check` rc=0; the 11 TestBazel*
/ TestCheckBuildTags* policy tests pass. Composition asserted inside the
tree CI actually builds -- `git merge-tree --write-tree origin/main
<probe>` rc=0, and the merged cmd/bd/BUILD.bazel differs from
origin/main's by exactly this one line, while the same merge without the
fix is byte-identical to origin/main's (control).

Contributor commits are untouched; no Go file changes.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 17:26:17 -07:00
Harry Miller
fe5b9d1e0f
fix(formula): reject a waits_for gate with no spawner, and stop reporting invalid formulas as not found (#5761)
* fix(formula): reject a waits_for gate that has no spawner to wait for

waits_for = "all-children" (or "any-children") names no spawner, so
collectDependencies infers one from needs[0] and emits no dependency at
all when the step has no needs. Validation accepted that step, cooking
gave it a gate:all-children label, and the result was a step with zero
dependencies that is ready immediately — a fan-in that silently never
fans in. Only the label survived to suggest otherwise.

Reject it where the intent is still visible, naming both repairs: add
needs, or name the spawner with children-of(step-id), which carries its
own spawner and stays valid without needs. depends_on is deliberately not
accepted as a substitute, because the inference does not read it.

The fan-in example in docs/workflows/gates.md taught exactly the broken
shape — a summarize step with waits_for and no needs — so it is corrected
here alongside, with the spawner step it was missing.

* fix(formula): make a validation failure distinguishable from "not a formula"

Callers that resolve a name as a formula and fall back to a proto/issue
lookup have no way to tell the two apart, so a formula that exists and
does not validate is reported as not found and its real error is thrown
away. The spawnerless waits_for gate rejected above lands in exactly that
path.

ErrVarValidation already exists for the same reason, covering bad --var
values. Give Validate the matching sentinel; the message it produces is
unchanged. Wiring the fallbacks to it is a separate change.

* fix(mol): report an invalid formula instead of calling it not found

pour, wisp, bond and seed resolve a name as a formula first and fall back
to a proto/issue lookup. Any error from the formula path was treated as
"this is not a formula", so a formula that exists and fails validation
came back as "'<name>' not found as formula or proto ID" — with bd
formula list happily showing it. The real error was never printed, and
the advice to run bd formula list confirmed the wrong diagnosis.

Each fallback now reports a validation failure directly, the way it
already does for the bad --var values ErrVarValidation covers. A name
that really is not a formula is unaffected.

* fix(mol bond): make --dry-run validate the formula the real bond validates

resolveOrDescribe resolved a formula name with parser.LoadByName, which
never calls Formula.Validate - LoadByName -> loadFormula -> ParseFile does
not, and only parser.Resolve does. The real bond path
(resolveAndCookFormulaWithVars) calls Resolve, so the dry-run previewed
"will cook as proto" for every formula the real bond rejects, including
for the waits_for-without-a-spawner rule this branch adds. The function's
own comment already promised the opposite.

resolveOrDescribe now resolves before it validates provided vars, which
also means the --var check runs against the merged formula rather than the
unmerged one, so a var declared only in a parent is checked too. The two
error wrappings match the real path's, so the routes produce the same
message rather than merely the same exit code.

TestBdMolBondDryRun_RejectsInvalidFormulaLikeTheRealBond runs both routes
against the same invalid formula and asserts they agree - both fail, both
name waits_for, neither reports it as "not found as issue or formula". It
reproduces the gap against the old code:

    dry-run previewed a bond the real bond rejects:
      A: dryrun-invalid-gate (formula -> will cook as proto)

Also from review:

- validation_sentinel_test.go uses strings.HasPrefix instead of a slice
  that would panic with index-out-of-range rather than failing cleanly if
  the message ever shortened.
- Step.WaitsFor's field doc now states the needs requirement, and
  schema_gen.go is regenerated from it, so the generated schema documents
  the rule the validator enforces. docs/workflows/gates.md already said it.

The condition-filtering follow-up is filed as GH#6437: Validate runs
inside parser.Resolve, before FilterStepsByCondition, so a spawner dropped
by a false condition still reaches collectDependencies as a dangling
reference and is skipped silently - the same zero-dependency gate, past
the new check.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(mol bond): assert the dry-run gap in process, not through a subprocess

The regression test spawned an embedded bd and ran two CLI invocations,
which is the most expensive shape of test in cmd/bd - and cmd/bd already
runs 477s of its 600s budget on the macos runner, so the addition timed
the package out.

The process boundary was never what the test was about. resolveOrDescribe
and resolveOrCookToSubgraph are both reachable directly with a molReader
that answers "no such issue", and GT_ROOT puts a temp formula dir on
formula.DefaultSearchPaths without touching HOME or the working directory.
Same assertion - the two routes agree, both name waits_for, neither
reports an invalid formula as not found - in 0.03s instead of 18s.

Asserting the routes against each other rather than against a literal
message is deliberate: it is what stops a validation rule added later from
re-opening the same gap. The LoadByName control is now explicit too, since
that call still accepting the formula is the reason the bug existed; if it
ever starts validating, the comparison stops distinguishing anything and
the test says so instead of passing quietly.

Second case added while here: the dry-run validated --var values against
the UNMERGED formula, so a constraint declared only in a parent went
unchecked. Resolving first fixes that as well, and an extends chain with
the enum in the parent pins it:

    dry-run accepted a var value the real bond rejects; the enum is
    declared only in the parent (real bond said: formula "dryrun-child":
    variable validation failed:
      - variable "env": value "staging" not in allowed values [dev prod])

Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(changelog): move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).

Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(bazel): enumerate the PR's two new test files in go_test srcs

Base added cmd/bd/BUILD.bazel and internal/formula/BUILD.bazel after this
branch's merge base, so the two untagged _test.go files this PR adds were
absent from their go_test srcs lists. Generated by 'make bazel-sync'
(bazel run //:gazelle); no hand edits. A second sync is a no-op.

* docs(formula): correct the waits_for spawner doc and the dry-run parity claim

Maintainer review fixup for the adoption of #5761 (review iteration 1
pre-merge checklist). Wording only -- no control flow changes.

internal/formula/types.go: the new Step.WaitsFor doc said "Requires needs
(or depends_on)", but Formula.Validate receives only step.Needs and cook
infers the spawner solely from Needs[0] (cmd/bd/cook.go:961-962) -- the
DependsOn loop never feeds waitsForSpawnerStepID, and the struct doc's
"merged during cooking" happens after Validate. A depends_on-only bare gate
is therefore correctly rejected: the code and the error message are right,
only the comment was wrong, and it shipped into the generated schema surface
agents read. docs/workflows/gates.md already states it correctly.
Regenerated schema_gen.go with `go generate ./internal/formula/`.

CHANGELOG.md: "so it fails on exactly what the real bond fails on" was an
overclaim. The dry-run now resolves and validates the way the real bond
does, but five later real-path failure surfaces (inline expansions,
expansions, aspect load/type, condition filtering) stay outside the preview.
Named that boundary rather than claiming total parity.

Contributor commits untouched.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 17:09:59 -07:00
Harry Miller
11fa7f5852
fix(mol): a dispatch hint for a command that does not exist, and a --ref bond that deadlocks (#5759)
* fix(mol): print a real dispatch command in mol ready --gated

The gate-ready listing ended with "bd sling <agent> --mol <molecule-id>".
No bd binary has ever had a sling command: sling belongs to the gastown
orchestrator (gt sling), and the line was a hardcoded Println with no
implementation behind it. Following the hint gives "unknown command".

Print the bd-level action instead. The listing already knows each
molecule's ready step, so the hint names that step's ID and the assign
command that actually dispatches it; agents pick work up by claiming a
step, which is what puts a molecule in the hooked status this command
filters on.

The regression test resolves the printed command against the root command
tree, so a future hint cannot name a command that does not exist.

* fix(mol): stop a --ref arm from deadlocking the molecule it bonds into

bd mol bond <proto> <mol> --ref <name> gave the spawned arm two
relationships to mol at once: ParentID nested it under mol, and
AttachToID added a blocking dependency ON mol. Those cannot both be
satisfied. The arm waits for mol to close; mol cannot close while it
holds an open arm child. bd ready empties out with nothing naming the
cause, and the only escape is closing the parent by hand.

The documented Christmas Ornament example is exactly this shape --
"bd mol bond mol-worker-arm bd-patrol --ref arm-{{worker_name}}" takes
the default sequential bond type, so the primary use of --ref deadlocked.

Nesting already attaches the arm, and its dotted ID records it, so the
blocking edge is dropped for a nested arm rather than pointed somewhere
else. A bond without --ref is untouched: that arm is a sibling, mol
closes, and the arm then unblocks, which is satisfiable and stays. A
parallel bond never blocked and is likewise unchanged.

* fix(mol bond): refuse --ref with --type conditional instead of inverting it

Dropping the attachment edge for a nested --ref arm traded a deadlock for
lost ordering, which is defensible for a sequential bond but not for a
conditional one. DepConditionalBlocks means "B runs only if A fails"
(internal/types/types.go), so dropping it does not lose ordering - it
inverts the meaning, turning an arm that should almost never run into one
that always runs. That is a silent false dispatch, strictly worse than the
visible deadlock it replaced.

refuseConditionalRefArm now rejects the combination, consulted both from
gatherMolBondInput (so --dry-run and the proxied route refuse identically,
rather than previewing a bond the real command rejects) and from
buildAttachCloneOpts (so a caller that skips flag validation cannot
construct the arm either). The drop in buildAttachCloneOpts narrows to
DepBlocks, so a future bond type reaching that point is not silently
stripped of its edge as well.

The sequential case keeps the drop, and the loss is now stated rather than
implied: bond's long help says a --ref arm carries no ordering and is ready
as soon as it is spawned, and the CHANGELOG entry says the same. The
committed docs/cli-reference/mol.md is generated from the tag in
docs/cli-docs.pin, so it picks the wording up at the next release
regeneration - hand-editing it fails the drift gate.

Also from review: the parallel arm's redundant-but-satisfiable
DepParentChild edge is now explained rather than merely test-pinned, and
`bd mol ready --gated` says which molecule its dispatch example belongs to
when more than one is listed. registerMolBondFlags is extracted so a test
can build an isolated command instead of mutating the package-level one.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(changelog): move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).

Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(bazel): enumerate the PR's two new cmd/bd test files in go_test srcs

gazelle-generated. Both files are untagged (no //go:build), so the
bazel go_test target owes their enumeration; the in-package census showed
the gap was exactly these two and zero pre-existing untagged gaps.
Note make bazel-sync-check exits 0 on the un-synced head, so only the
literal make bazel-sync surfaces this.

* fix(mol): correct the --ref help, the refusal message and the hint header

Review iteration 1 on PR #5759. All four synthesis findings are minor or nit
with no gating impact (scorecard 967/850, Required Changes: None); taken
because a maintainer commit already exists on this branch (d66096104), so the
push is owed either way.

Finding 1 (minor) - the new --ref help paragraph asserted "B is nested inside
A", which is inverted for the proto+mol order that every --ref example in the
same help text uses: for aIsProto && !bIsProto the dispatch passes issueB as
mol, so ParentID is B. Rephrased by role, matching the CHANGELOG's own neutral
wording, and de-positionalized the parenthetical in the same paragraph, which
named A as the container too.

Finding 2 (minor) - the conditional + --ref refusal claimed "a nested arm
cannot be ordered against the molecule that contains it" from
gatherMolBondInput, which runs before operands are resolved and so also
refuses mol+mol and proto+proto, where --ref is inert and nothing nests.
Reworded to state the nesting rationale as what --ref does where it applies
rather than as a claim about the bond in front of the user.

Finding 3 (nit) - the ordering-trade comment claimed docs/cli-reference/mol.md
already documents the trade. It does not: that page is generated from the
release named in docs/cli-docs.pin (v1.2.2), whose source has zero hits for
"nested inside". Softened to name the long help as the documented place and
mol.md as where it will appear once the pin advances. mol.md is deliberately
untouched - hand-writing it would diverge from the pinned generator output and
red a currently-green required check.

Finding 4 (nit) - "for the first one above" could name a different molecule
than the step ID printed beneath it, whenever the first listed molecule has no
ready step and a later one does. Both offered arms miss that case (indexing
element 0 and dropping the fallback nil-derefs; suppressing the line only when
NO molecule has a step leaves the disagreement intact), so this implements the
stated intent instead: firstReadyStepID also returns the listing position and
the header names it.

Deviations, with the measurements behind them:

- Finding 2's "leave the nesting rationale on the attach-path error" arm was
  not taken as a message split. gatherMolBondInput runs at mol_bond.go:104,
  before the usesProxiedServer() branch, and buildAttachCloneOpts is reached
  only via bondProtoMolWithSubgraph/bondProtoMolAttachInto downstream of it, so
  the attach-path string is unreachable from every CLI route; split that way
  the corrected wording is all any user would see and the rationale would be
  dead text. One shared, shape-agnostic message keeps both true. Verified from
  the CLI: `mol bond no-such-a no-such-b --type conditional --ref arm-ace`
  refuses (rc 1), while the same nonexistent operands without --type
  conditional reach operand resolution and fail there.
- Finding 2's alternative arm (scope the gather-time refusal to the attach
  shapes) would falsify this PR's own CHANGELOG entry, which states the
  combination is "refused outright (including under --dry-run and on the
  proxied route)".
- No mol+mol refusal test was added: gatherMolBondInput never resolves
  operands, so mol+mol and proto+mol are the same input to it and such a test
  would be vacuous.
- Artifact sweep for the inverted claim came back empty: CHANGELOG.md and the
  PR body already describe the nesting by role ("nested inside its target"), so
  the A/B inversion existed only in the help paragraph.

Tests: the PR's 9 tests plus the new one pass by name (go test ./cmd/bd/ -run
'TestBuildAttachCloneOpts|TestGatherMolBondInput|TestGatedReadyHint' = 10 PASS
/ 0 FAIL; the full cmd/bd package does not finish). Mutation proof that the new
pin is not a duplicate: hardcoding the header position to 1 - the pre-fix
meaning - reds only
TestGatedReadyHintHeaderNamesTheEntryItPrinted/example_comes_from_a_later_molecule
while its sibling subtest and all 9 existing tests stay green. go build ./...
and go vet ./cmd/bd/ exit 0.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 17:05:18 -07:00
Marco Del Pin
63d8cc2522
cmd/bd: bd label rename <old> <new> (stacked on #6007) (#6009)
* storage: add RenameLabel primitive with merge semantics

Add a storage primitive that renames a label across every issue and
wisp that carries it, in one transaction per store. An issue that
already carries the new label is a merge - the stale old-label row is
dropped rather than raising a duplicate-key error - and the call
reports renamed/merged counts plus every touched id.

- internal/storage/issueops/labels.go: RenameLabelInTx sweeps the
  labels and wisp_labels tables (INSERT IGNORE then DELETE, so the
  merge never errors), emitting one EventLabelRenamed plus the usual
  full-snapshot journal row per touched issue/wisp, matching
  AddLabelInTx/RemoveLabelInTx's journal shape. A single batch event
  was considered and rejected: the journal-completeness guard requires
  every touched row to carry its own journal entry.
- internal/storage/storage.go: RenameLabel added to the Storage
  interface, next to AddLabel/RemoveLabel/GetIssuesByLabel.
- internal/storage/dolt, internal/storage/embeddeddolt: direct
  implementations. The dolt commit targets the fixed events/labels
  table pair; doltAddAndCommit's own HasStagedChanges guard skips it
  when the rename touched wisps only (wisp tables are dolt-ignored,
  same as AddLabel/RemoveLabel).
- internal/storage/hook_decorator.go: HookFiringStore.RenameLabel
  fires on_update per touched issue, matching AddLabel/RemoveLabel.
- internal/types/types.go: new EventLabelRenamed event type. Unlike
  EventLabelAdded/EventLabelRemoved, one rename produces exactly one
  of these per touched row, never a paired add+remove.
- internal/jira/tracker_test.go: mock stub for the new interface
  method.

Tests: internal/storage/dolt/label_rename_test.go, against a real
dolt-sql-server container - basic rename, merge, wisp sweep,
zero-carrier no-op, over-length refusal, event assertion. All green.
Also verified TestEveryBeadMutatorJournalsOrIsExempt still passes.

Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.

* storage: refuse RenameLabel(x, x) instead of wiping the label

RenameLabelInTx's merge branch treats every carrier of oldLabel as
already carrying newLabel when the two names collide (they are the
same string): the batched INSERT IGNORE no-ops on every row, and the
unconditional DELETE FROM <table> WHERE label = ? that follows then
removes every row for that label plane. A self-rename silently wiped
the label instead of leaving it untouched.

Reject oldLabel == newLabel (compared after trimming, case-sensitive)
before any write, returning the new ErrRenameLabelSameName. Verified
red->green: TestRenameLabel_SameNameRefused and
TestRenameLabel_SameNameAfterTrimRefused both fail (GetLabels returns
[] on both the labels and wisp_labels planes) against the pre-fix
code, and pass against the fix. Full TestRenameLabel* suite in
internal/storage/dolt still green.

* telemetry: instrument InstrumentedStorage.RenameLabel

AddLabel and RemoveLabel already get OTel spans/metrics through
InstrumentedStorage; RenameLabel had no override and so fell through
to the embedded storage.DoltStorage passthrough, invisible to
storage.* tracing. Add the override, mirroring the AddLabel/RemoveLabel
shape: span attributes for the old/new label pair (bd.label.old,
bd.label.new, matching the existing bd.dep.from/bd.dep.to pairing
convention), and on success a bd.result.count / bd.merged.count pair
following the SearchIssues-style "set result attributes after a
successful call" pattern already used elsewhere in this file.

* storage: document the O(N) round-trip cost of RenameLabelInTx's event loop

renameLabelInPlane's per-issue loop (InsertDerivedEvent + RecordEventInTx)
is O(len(oldIDs)) SQL round trips inside one transaction, up to four per
touched issue. On a huge label population that lengthens the transaction
and raises the odds an optimistic-concurrency retry has to redo the whole
rename from scratch.

No batching added: InsertDerivedEvent's dedup SELECT is a real
cross-replica convergence check (Protocol v0.1 C2.3), not a redundant one
this transaction could skip, and no batch primitive for this shape exists
anywhere in this package - building one here would be new shared
infrastructure grown for a single caller. AddLabelInTx/RemoveLabelInTx
already pay the identical per-call cost for their one issue; this loop is
that cost repeated once per touched issue. Documented inline as a
disclosed limitation rather than silently left unremarked.

* bda-lbjv: derive rename merge count from rows-affected, not a prior read

renameLabelInPlane computed merged from a snapshot SELECT of newLabel's
carriers taken before the INSERT IGNORE - a check-then-insert whose
result is used. A concurrent AddLabel(issue, newLabel) committing between
snapshot and insert made the reported count schedule-dependent while the
stored data stayed correct (cross-model finding: the Opus panel cleared
A1, codex flipped it to NOT-SAFE on exactly this line).

Now the count is a measurement: INSERT IGNORE reports one affected row
per id actually inserted, so merged = len(oldIDs) - inserted, and the
newLabel pre-read is gone entirely.

Tests: sqlmock scripts the racing schedule (insert sees a row the
snapshot read could not); mutation control confirms the old
implementation fails the new test. Full issueops package + live-store
TestRenameLabel_* green.

* bda-c77s: first-party coverage for EmbeddedDoltStore.RenameLabel

The embedded impl had zero tests while DoltStore.RenameLabel carries a
dedicated suite; AddLabel/RemoveLabel both have parallel embedded
coverage by convention. Four wiring cases (basic, merge, zero-carrier
no-op, same-name refusal) - the deep semantics stay pinned by the shared
issueops suite and the dolt-side tests against the same implementation.

BEADS_TEST_EMBEDDED_DOLT=1: 5 RUN, all green, 2.8s.

* storage: scope the rename delete to the ids the sweep captured

An unrestricted DELETE ... WHERE label = ? makes the sweep's blast radius
engine-dependent: under current-read DELETE semantics a row a concurrent
AddLabel(oldLabel) committed after this transaction's snapshot would be
removed without ever being renamed, counted or journaled. Restricting the
delete to the captured ids touches exactly the rows the INSERT IGNORE above
accounted for on every engine; a concurrent add outside the snapshot now
deterministically SURVIVES the rename - the same observable state as that
add landing after the rename committed, which is the only order-independent
reading of the race.

sqlmock WithArgs pins the id-scoped statement shape; the embedded-Dolt
lifecycle set stays green (5/5).

* cmd/bd: add `bd label rename <old> <new>` with dry-run preview

Wire the storage.RenameLabel primitive (previous commit) into a CLI
command that renames a label everywhere it appears in one call instead
of a per-issue add-then-remove loop.

- cmd/bd/label.go: `bd label rename <old> <new> [--dry-run]`.
  validateLabelRename refuses empty/identical labels and the
  'provides:' reserved prefix before any store call - it is a pure
  function so those rules are testable without a store. --dry-run
  previews the blast radius (count plus the first issues) read-only,
  via a path kept separate from the write path so it can never reach a
  transaction.
- cmd/bd/label_proxied_server.go: the proxied-server route composes
  the existing per-issue LabelUseCase.AddLabel/RemoveLabel (and wisp
  twins) in one uow.RunTx, the same fan-out shape label propagate
  already uses on this route. It journals as an add/remove pair per
  issue rather than the direct route's single EventLabelRenamed,
  because LabelUseCase has no rename-shaped event; the rename
  semantics (merge-on-collision, honest zero-carrier no-op, dry-run
  preview) are identical on both routes.
- docs/core-concepts/labels.md: documents rename, dry-run, and merge
  semantics under Label Management.

Tests: cmd/bd/label_rename_test.go (pure argument-validation table
test, no store needed) plus new subtests in
cmd/bd/label_embedded_test.go covering the full CLI path - basic
rename, merge, dry-run writes nothing, zero-carrier no-op,
identical/empty/reserved-prefix refusals. All green.

Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.

* cmd/bd,domain: emit label_renamed on the proxied route, not add+remove

runLabelRenameProxiedServer used to fan a rename out into a per-issue
AddLabel-then-RemoveLabel pair, journaling label_added/label_removed
instead of one EventLabelRenamed - a divergence from the direct
DoltStore/EmbeddedDoltStore route the upstream reviewer has already
rejected for another PR touching the same class of proxied/direct
split.

Add domain.LabelUseCase.RenameLabel and domain.LabelSQLRepository.
RenameLabel. The repository method delegates straight to
issueops.RenameLabelInTx (r.runner satisfies issueops.DBTX
structurally), so the proxied route is not merely the same SQL SHAPE
as the direct one, it is the same function: identical merge semantics,
the same ErrRenameLabelSameName refusal, and one EventLabelRenamed per
touched issue. runLabelRenameProxiedServer now just calls
uw.LabelUseCase().RenameLabel(...) inside its existing uow.RunTx.

Declare recordingLabelUC.RenameLabel so the notifying unit of work
records one update per touched issue/wisp (mirroring
HookFiringStore.RenameLabel on the direct route) instead of silently
recording nothing through the embedded interface - caught by the
existing structural parity guard, TestRecordingLabelUseCaseCoversItsSurface,
which fails on any domain.LabelUseCase method neither declared on
recordingLabelUC nor exempted with a reason.

Tests, verified red->green:
  - internal/storage/domain/db: TestLabelUseCase/RenameLabel adds 5
    subtests. EmitsOneRenamedEventPerIssue is the direct regression
    test - reverting RenameLabel to a simulated add-then-remove
    fan-out reproduces exactly the pre-fix event counts (renamed=0,
    added=2, removed=1) it now asserts against (renamed=1, added=1,
    removed=0).
  - cmd/bd/label_proxied_integration_test.go: new "rename" subtest
    exercises `bd label rename` end to end through the real proxied
    server and asserts the same label_renamed/added/removed counts
    directly against the events table.
  - internal/storage/uow: TestRecordingLabelUseCaseCoversItsSurface
    goes red (RenameLabel inherited, records nothing) without the
    recordingLabelUC override and green with it.

Full internal/storage/uow suite (287s) and the new domain/db and
cmd/bd tests all pass.

* cmd/bd: record commandDidWrite before the rename error return

runLabelRename read renamed>0 into commandDidWrite only after the
`if err != nil` early return, so a rename whose SQL side committed but
whose store call also returned an error - the Dolt publication step
failing after the working-set write landed - never marked the command
as having written. The caller's deferred auto-commit would then skip
creating a Dolt commit for a write that, on disk, actually happened.

Move the commandDidWrite.Store(true) check ahead of the error check,
matching applyLabelEdit's existing per-issue marking a few lines above
in the same file.

New test: TestRunLabelRename_CommandDidWriteSetBeforeErrorReturn wraps
a real *dolt.DoltStore in a spy whose RenameLabel reports a publish
failure (renamed>0, err!=nil) after delegating to the real rename, and
asserts commandDidWrite is set despite the returned error. Verified
red->green: reverting the ordering reproduces the exact failure this
guards against.

* bda-bnid: nolint:forbidigo on proxied bulk rename call

The route delegates to domain.LabelUseCase.RenameLabel deliberately: one
EventLabelRenamed per issue with identical merge semantics to the direct
route. Patch.Labels (the lint's suggested remedy) would reintroduce the
per-issue add/remove event divergence this delegation replaced. Matches
the file's own convention (4 sibling nolints, same shape).

Negative control: without the nolint golangci-lint forbidigo reports
exactly this line; with it, 0 issues.

* cmd/bd: address review on label rename (CHANGELOG entry, dry-run caveat, partial-failure count)

Two blocking items from review (bee-ghosttrack, PR #6009):

- Add the CHANGELOG entry for `bd label rename`, in the house voice used
  by the neighboring bd-label entries (bold lead sentence, PR link, dense
  explanatory prose on the merge/dry-run/partial-failure contract).
- The `--dry-run` merged count is a plain snapshot intersection of two
  independent reads - exactly the check-then-count shape
  renameLabelInPlane's own comment documents rejecting for the write
  path, because it is schedule-dependent under a concurrent
  AddLabel/RemoveLabel. That is an acceptable estimate for a preview, but
  nothing said so: the command's Long text, the --dry-run flag help, and
  an inline comment at the computation site now all say the number is
  not authoritative.

One non-blocking nit fixed (the other - hydrating full issue rows in the
direct dry-run just to print 10 titles - is left alone; see below):

- On a partial rename failure (renamed>0, err!=nil - e.g. a Dolt
  publication failure after the SQL side already committed) the command
  now reports how many issues were renamed and merged before the
  failure, instead of only the error. Mirrors the existing shape in
  conflicts.go's ResolveConflictRows handling ("resolved %d of %d
  conflict(s) before failing").

Left alone, and why: the GetIssuesByIDs-hydration nit. GetIssuesByLabel
hydrates every matching issue via GetIssuesByIDs on both the old-label
and new-label reads, which is wasteful on a label carrying 10k issues
when the text-mode preview only prints 10. But the JSON-mode contract
already returns every matching issue's id+title (not capped at the
preview limit), so avoiding hydration only helps the text-mode path and
would branch the two output modes apart for a marginal win on an
uncommon case (a rename dry-run over a 10k-issue label). Not clean
enough to do inline without its own test coverage and a decision about
whether the JSON contract should change too - flagged in the review as
skippable, so skipping it here.

Verification:
- go build ./... - clean
- go vet ./cmd/bd/... - clean
- gofmt -l cmd/bd/label.go - clean
- go test ./cmd/bd/... -run 'Label|LabelRename' - all pass
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/... -run 'TestEmbeddedLabel$' -v
  - all pass, including label_rename_basic/merge/dry_run_writes_nothing
- BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/...
  -run TestProxiedServerLabel -v - all pass, including the "rename" subtest
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/issueops/... -run Rename -v
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/... -run Rename -v (live dolt-sql-server)
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/embeddeddolt/... -run Rename -v

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* cmd/bd: report an upper bound on a failed rename, not a landed count

The partial-failure message asserted that renamed>0 means the SQL side committed. On both routes the counts are assigned inside the transaction closure (label_proxied_server.go RunTx, dolt/labels.go withRetryTx), so a Commit failure or retry exhaustion returns them holding the rolled-back attempt numbers - nothing landed, and the user read 'renamed 6 issue(s) before failing'. Retry exhaustion under a busy server is the likely failure for a bulk rename, so it misreported exactly when it fired. Now reports an upper bound. commandDidWrite keeps the same premise deliberately: it is fail-safe in the other direction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* cmd/bd: pin the partial-failure wording, and hedge the merged count too

Round-3 review: the r2 correction rode unpinned. Nothing in the suite drives
a failing rename with renamed > 0, so the whole TestEmbeddedLabel suite passed
with the hunk reverted - the fix was unfalsifiable, which is the same defect
class the correction itself was about.

Extracts the sentence into labelRenamePartialFailureMessage, a pure function a
test can assert on without inducing a mid-transaction failure, and pins it:
the hedged phrasings must be present AND the two pre-correction phrasings must
be absent. Mutation-checked - restoring the old wording turns it red on three
assertions.

Also the round-3 nit: (%d merged) was the one unhedged clause in a hedged
sentence. It now reads (of which up to %d merged), so no number in the message
asserts a write that may never have landed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs: retire the landed-count premise from the CHANGELOG too

Round-4 review, MAJOR: the code retracted a premise and the CHANGELOG kept
publishing it. The entry still said a partway failure 'reports how many issues
were renamed and merged before the failure' - a landed count - while
labelRenamePartialFailureMessage had already become an upper bound.

The sentence carried the premise TWICE and the review named one: besides the
count, its parenthetical offered 'a Dolt publication failure after the SQL side
already committed' as the case, when the whole point of the correction is that
renamed > 0 cannot distinguish that from a rollback. Rewrote both halves: the
bound is explicit, and the two failure shapes are named as indistinguishable
from the count alone.

Also round-4 MINOR: the helper had been inserted between reportLabelRename's
doc comment and its func, so the comment headed the wrong function and
reportLabelRename was left undocumented. Moved back down.

Not done, deliberately: the round-4 NIT that the pin covers the helper and not
the call site. It is marked 'noting, not asking', and an unrequested fix is the
one that ships a defect - this PR already demonstrated that.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* CHANGELOG: move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so these lines
merged cleanly into a released section (gastownhall/beads#6643).
Moved 31 line(s); the code is unchanged.

* cmd/bd: register label rename in the proxied capability registry

TestProxyCapabilityRegistryCoversCommandTree requires every command path to
carry a proxied-server row. label rename has a proxied route (RunE hands the
rename to runLabelRenameProxiedServer and the --dry-run preview to a proxied
read UOW), so it joins its label siblings in proxyPermittedPaths.

* storage: mint a version for every bead a label rename touches

TestEveryBeadMutatorMintsOrIsExempt (added with #6650) fails on this PR:
RenameLabelInTx writes the labels table but never reached
RecordVersionInTx. A rename changes the label set - part of the durable
snapshot - of every issue that carried oldLabel, whether it gained
newLabel or already had it (merge), so each touched issue now mints one
version row, the same gate AddLabelInTx/RemoveLabelInTx draw on a row
that landed. RecordVersionInTx is already a no-op for wisps and when
versioned history is disabled, and a rename nobody carries touches no
id, so the no-op shape mints nothing.

TestRenameLabelMintsOneVersionPerTouchedBead is the runtime twin of the
static guard: plain rename +1, merge +1, untouched bead +0, a second
rename with no carriers +0, current_revision equal to the row count.

* build(bazel): list this PR's six new test files in their go_test srcs

Generated-artifact drift repair, produced by the repository's own command
(`make bazel-sync`) and inspected before committing, not hand-written.

The PR adds six `_test.go` files and none were listed in their package's
`go_test` srcs, so Bazel compiled each of those packages' test targets without
them - green by omission. That was invisible on the pre-merge head because its
CI predates the Bazel lanes entirely (zero `Bazel /` rows). This merge brings in
e1b2e79484 (#6941), which makes those lanes feed the required gate, so the
omission would now surface as a real red.

Purely additive: 6 insertions, 0 deletions, `go_test` srcs only. No `go_library`
srcs change is needed because every added file is a test, which is also why this
cannot break the build the way a missing production source would.

Verified: `make bazel-sync` is now a no-op against this tree (empty porcelain),
and `bazel build //cmd/bd/... //internal/storage/... //internal/types/...
//internal/telemetry/...` completes successfully - 3429 actions, 0 errors.

---------

Co-authored-by: Marco Del Pin <marco@omniaevo.it>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 17:02:35 -07:00
Alex
c8cc5c03fa
fix(doctor): accept a leading v in version strings (#6153)
* fix(doctor): accept a leading v in version strings (be-snd)

A build stamped from a Go pseudo-version reports "v1.1.1-0.2026…-<sha>",
the canonical module spelling, and bd writes that main.Version into
.local_version on every command. The version helpers parsed digits
first, so the same binary's doctor then flagged the file it had just
written ("Invalid version format in .local_version"), and a v-prefixed
version compared as major 0. A prerelease suffix passed by accident
(the leading digits of "0-rc" parse), so upstream release candidates
never showed it; only v-stamped builds did.

Strip an optional leading v before parsing in IsValidSemver,
CompareVersions and ParseVersionParts. Versions without the prefix are
unchanged; the table row that called "v1.2.3" an invalid format flips,
deliberately. Prerelease ORDERING is out of scope: the comparison stays
the dot-part parse it was.

Reproduced on stock main (40b323245): the same build stamped with and
without the v against a server-mode scratch store — warning vs
"Version tracking active".

Fixes #6152

Agent-Signature: claude-code-claude-fable-5-max on behalf of a3ackerman
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D95BMAo3WieQDwPQMNWJ2e

* fix(doctor): keep CompareVersions's doc comment on its declaration (be-snd)

Review: stripVersionPrefix had landed between CompareVersions's doc comment
and its func, so godoc hung the CompareVersions text on the helper and left
CompareVersions undocumented. The helper now sits above that comment block;
no behavior change.

Agent-Signature: claude-code-claude-fable-5-1-max on behalf of A3Ackerman
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015LrzRcJhWSUH6SnU64gtFE

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 16:58:32 -07:00
Karel Bourgois
e8f318316f
feat(count): --include-ephemeral, the plane knob bd count never had (#6240)
* feat(count): --include-ephemeral, the plane knob `bd count` never had

`bd count` can admit the wisps table only through `--include-infra`, which
makes four changes at once. This adds the flag that makes just the first one,
mirroring the `--include-ephemeral` that `bd list` gained in #6098.

## Why the plane is unreachable on its own

The write path routes on STORAGE CLASS, not type — dolt's `useWispsTable` is
`Ephemeral || NoHistory || WispType != "" || IsInfraType`. So a `no_history`
task lives in the wisps TABLE while remaining ordinary durable work, and a
default `bd count` never sees it.

Recovering it today means `--include-infra`, which this repo's own doc calls
"FOUR changes at once and not one": it admits the plane, drops the infra-type
exclusions, changes the template treatment, and reconciles cardinality with
`bd list --all`. Its template exclusion then silently drops template rows of
the named type — so a caller who wanted the plane trades one silent undercount
for another.

`ListRequest.IncludeEphemeral` has been the narrow answer on the listing side
since #5476, and #6098 gave it a CLI flag. `CountRequest` had no equivalent
field at all. This is the missing half of that pair.

## The change

- `issueops.CountRequest.IncludeEphemeral` — the plane knob alone: exactly the
  first of `IncludeInfra`'s four changes, with none of the other three.
- `internal/workapi/count.go` — one line, `} else if !in.IncludeEphemeral {`.
- `cmd/bd/count.go` — flag registration, matching `bd list`'s wording.
- `internal/httpapi` — `include_ephemeral` on `countIssues`, in the spec; the
  generated `types.gen.go` is `make api-gen` output, not hand-edited.

Unset, the count is durable-plane only: the historical answer, unchanged. Every
default is untouched.

It does NOT promise a count and a listing agree. They already differ on
TEMPLATES without this flag and still do with it — a count includes template
rows unless `IncludeInfra` excludes them, a listing excludes them unless
`IncludeTemplates` admits them. That predates this and is unchanged by it; only
`IncludeInfra` sets out to reconcile cardinality, and it pays with three
changes beyond the plane.

## Verification

    ok  github.com/steveyegge/beads/internal/workapi
    ok  github.com/steveyegge/beads/internal/httpapi
    ok  github.com/steveyegge/beads/issueops
    --- PASS: TestEmbeddedCountIncludeEphemeral (39.71s)
    --- PASS: TestCountIncludeInfraFlagShape
    --- PASS: TestParseCountRequestCarriesEveryFilterFlag

`TestEmbeddedCountIncludeEphemeral` was run with `BEADS_TEST_EMBEDDED_DOLT=1`
and really executed — 39.71s, not a skip. The default fast tier would have
skipped it and reported `ok`.

`make api-gen` reproduces `types.gen.go` byte-for-byte from the spec hunk, so
the two cannot drift apart in review. `go build ./...`, `go vet` and `gofmt`
clean.

Claude-Session: https://claude.ai/code/session_01X1jMLQTSrCwtzFRS1xeUC6

* count: reframe the comments for this repo, not the fork they came from

Review on #6240 (bee-ghosttrack): five comment blocks were written from the
fork's point of view and become false once merged here — "belongs upstream",
"the half that still has to go upstream", "the fork's old wide default",
and "upstream's default" meaning the current default.

Find-and-replace, as asked: the reasoning is kept, only the frame of reference
changes. "upstream's default" -> "the default before this change"; the bd
list sibling "landed in #6098"; the infra-type divergence is "pinned, not
fixed, here" with the reason; the embedded test's fork-maintenance history is
replaced by what it actually pins. No code changes.

* build(bazel): list the two test files this PR adds in their go_test srcs

Maintainer review fixes for #6240, review iteration 1. The synthesis and the
quality scorecard both returned approve with no required changes; this commit
takes the one minor whose subject is the PR's own added files.

Taken:

- Change Impact / Blast Radius (minor, gate impact minor). The PR adds
  cmd/bd/count_include_ephemeral_embedded_test.go and
  internal/workapi/count_skipwisps_test.go, but neither was listed in its
  package's explicit go_test srcs, so the PR's own assertions were invisible to
  `bazel test`. Both rows are now listed.

  Gazelle's verdict, not a hand-guess: `make bazel-sync` was run (bazel 9.2.0 is
  available here) and it produced exactly these two entries. Its full output
  also rewrote 12 other BUILD.bazel files -- pre-existing base drift from other
  PRs' files, plus dep/select churn -- which is out of scope for this PR, so the
  generated result was reverted and only the two rows this PR is responsible for
  were re-applied, at the slots gazelle chose. Both srcs lists remain sorted
  with no duplicates (cmd/bd bd_test 637 entries, internal/workapi workapi_test
  24 entries).

  The cgo build tag on count_include_ephemeral_embedded_test.go does not exempt
  it: the repo lists tag-gated *_embedded_test.go files anyway (99 of the 101 in
  cmd/bd are listed, and the sampled ones are simultaneously listed and tagged).

Declined:

- Test Evidence Quality (nit, gate impact none). The filing lane itself marked
  it optional and explicitly said not to gate on it, and its own reasoning holds:
  internal/storage/dolt/counts.go and internal/storage/embeddeddolt/counts.go
  both delegate to the same issueops.CountIssuesInTx, differing only in
  transaction acquisition.

Validation: go build ./... and CGO_ENABLED=1 go vet on cmd/bd, internal/workapi
and issueops all clean; go test ./internal/workapi/ ./issueops/ ok. No
production code changed -- the commit is two generated-list rows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 16:56:23 -07:00
ecuthiell
beed11c7f4
fix(init): use selected hook context in embedded initialization (#6464)
* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(config): explain role command routing policy (saa-cgh.99)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): isolate role configuration from inherited Git routing (saa-cgh.109.3)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): use the selected origin in contributor setup (saa-cgh.109.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): isolate Git writes in planning repositories (saa-cgh.109.9)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(init): retain inherited planning commit author (saa-cgh.109.9)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): align embedded role gates with selected Git context (saa-cgh.109.12)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): scope embedded artifact Git operations to selected directory (saa-cgh.109.15)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(init): cover selected optional artifacts and explain refused commits (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Honor role-probe cancellation and exercise actual fork planning (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): warn when automatic contributor role write fails (saa-cgh.109.3)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(init): cover successful nonquiet contributor role writes (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Assert the automatic contributor setup banner alongside warnings (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* test(init): read persisted role routing from the store (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96)

Reported by bee-ghosttrack in gastownhall/beads#6343.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(gitignore): clarify exclude fixture path variable (saa-cgh.104)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): refuse exclude writes after read errors (saa-cgh.110)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitignore): share append byte composition (saa-cgh.105)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitignore): use shared composition for exclude rules (saa-cgh.111)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): omit the empty exclude leading separator (saa-cgh.112)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(hooks): explain conservative tracked-file guard (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(git): resolve hooks paths in an explicit read-only context (saa-cgh.109.17.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Bind init hook operations to the selected repository (saa-cgh.109.17)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Give the hooks tail fixture an explicit remote context (saa-cgh.109.17)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(git): canonicalize the hooks fixture repository root (saa-cgh.109.17.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): complete selected hook options and alias handling (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Clarify hooks resolver ownership and preserve work-tree diagnostics (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Explain restoration of absent routing variables in selected exclude tests (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Keep init role operations on the captured selected Git context (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): keep embedded hook setup in the selected project (saa-cgh.120.12)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init,config): maintainer fixup for #6464

Pre-review CI repair:
- Annotate #nosec G702 on the selected hooks-path git invocation. No shell
  is involved, every path is passed as its own argv element, and both values
  reach that line absolute via resolveInitHooksContext.

Review iteration 1, blocking:
- internal/config: give the secret-config guard the inherited-env fallback
  that the structurally identical hook guard in cmd/bd/hooks.go already has.
  isGitTracked is the fail-open half of "refuse to write a secret key into a
  git-tracked config.yaml", and the scrub alone narrowed it to upward
  discovery from the config file's directory: under a detached work tree
  (GIT_DIR + GIT_WORK_TREE with no in-tree .git) the probe reported
  "untracked" and the secret was written into the tracked file. Probe the
  scrubbed environment first so inherited routing cannot hide a tracked
  file, then the inherited one; either probe reporting the path as tracked
  refuses the write. Adds the legitimate-routing subtest that the
  poisoned-routing matrix could not express.
- cmd/bd/config.go: the new comment claimed "All role commands ignore
  inherited Git routing". Only the writers were hardened -
  routing.DetectUserRole, beads.RepoContext.Role, `bd config show` and
  `bd doctor` still resolve beads.role through the inherited environment, so
  `bd config get beads.role` and `bd config show` can disagree under one
  environment. Narrow the comment to the four verbs it covers; widening the
  boundary to the readers is a separate change.

Review iteration 1, non-blocking:
- cmd/bd/worktree_cmd.go: disclose that ClearRouting unsets the variables on
  the bd process itself, and state what clearing the discovery-scope
  controls does to repository selection. The comment previously claimed the
  opposite of what the init path's own note admits.
- cmd/bd/init_proxied_server.go: drop isRoleGitRepo. With workDir set, gitUC
  is NewInitGitRepository(workDir), whose IsGitRepo runs the same
  `git rev-parse --git-dir` with the same Dir and scrubbed env; with workDir
  empty the helper returned its fallback. It was isRepo in both arms, plus a
  second git subprocess per `bd init --proxied`.
- cmd/bd/doctor/gitignore.go: omit the leading blank line when creating a
  fresh .gitignore, matching the two sibling writers this PR already
  conditionalized in cff94aa43.

Review iteration 2, non-blocking:
- cmd/bd/worktree_cmd.go: iteration 1's own rewrite lumped
  GIT_DISCOVERY_ACROSS_FILESYSTEM in with GIT_CEILING_DIRECTORIES as
  "removes an inherited stop". That is backwards. git(1) documents that
  discovery "does not cross filesystem boundaries" by default and that this
  variable "can be set to true to tell Git not to stop at filesystem
  boundaries" - it only ever permits, so clearing it *adds* a stop and
  narrows the walk. Split the clause per control: the ceiling widens,
  GIT_DISCOVERY_ACROSS_FILESYSTEM narrows (a repository reachable only
  across a mount point is no longer found by any `bd worktree` verb, with no
  opt-out), and ClearRouting's GIT_CONFIG prefix match drops the whole
  GIT_CONFIG* family for the command's lifetime rather than for one child
  probe. This comment is the only in-tree assertion about the variable's
  direction; export_auto.go:1083-1085 groups the two without claiming one.
- cmd/bd/config.go: "bd config's own beads.role reads and writes" covered
  `bd config show`, which the very next sentence lists as an exception. Name
  the four verbs that do scrub (get/set/unset/set-many, at config.go:209,
  :355, :609 and :902 - the only four git invocations in the file).
- internal/config: make the guard's fail-open default unspellable. The
  mirrored helper took `envs ...[]string`, so a future zero-probe call would
  fall through to "untracked" and write the secret with no compiler
  backstop. Promote the first environment to a required parameter. The tail
  stays variadic rather than matching the twin's fixed (clean, inherited)
  arity because the fallback's fixture guard has to probe one environment
  alone, and exec treats a nil Env as "inherit the current process" rather
  than as a disabled probe.

Pre-approval CI repair:
- Annotate the four gosec taint findings this PR newly introduces in package
  cmd/bd: G704 on the two connectivity probes in dolt.go, G702 on the
  staged-deletion probe in hooks.go and on the ls-remote probe in
  sync_git.go. None of the four is reported by the PR lane, whose lint is
  scoped to the diff (only-new-issues / --new-from-merge-base), and all four
  sit on lines this PR does not otherwise touch - but main.yml runs the same
  wrapper with BD_LINT_NEW_FROM_MERGE_BASE unset and sweeps the whole tree,
  so merging as-is turns main's Lint and PR Lint jobs red. Measured
  whole-tree at pr.yml's pinned golangci-lint v2.10.1 with
  --build-tags=gms_pure_go: origin/main 0 issues, this head 4, this head
  with the annotations 0. The findings are taint over-approximation rather
  than new exposure: gosec's analysis is not field-sensitive, so routing
  config discovery through env-derived paths marks the whole store value
  tainted and every remote URL read back off it inherits that. Each
  annotation states why its own call site is safe; the additions are
  comment-only, with no deletions and no behaviour change.

  The hooks.go annotation sits on the isExportFileStagedForDeletion
  declaration rather than on the exec.Command call. main has since rewritten
  that body to address the export file through nearestExistingDir +
  filepath.Rel, so a call-site comment both conflicted with the merge and
  described an argument the merged body no longer builds. On the declaration
  it merges cleanly and its justification holds for either body.

Pre-approval base refresh (rebased onto 511849496):
- Reconcile this PR with gastownhall/beads#6477, which landed on main after
  this branch was first rebased and which changes the same reader. The two
  changes collide in both directions, and neither side's CI can see it: the
  PR lane builds this branch against its own base, main's lane never has the
  PR, and only the merged tree fails.
- #6477 direction: its new subtest
  TestConfig_ReadFailuresAreNotMissing/invalid_routing_boolean poisons
  GIT_CONFIG_NOSYSTEM and expects the beads.role read to exit 128. This PR
  scrubs GIT_CONFIG* for exactly that key, so git never sees the poison and
  the read succeeds. Replaced that row with
  TestConfig_BeadsRoleScrubsInheritedRoutingEnv, which pins both halves of
  the new contract: beads.role reads through the scrub, and a key outside it
  (user.name) still surfaces the same poison as an exit-128 read error
  rather than as an absent key. #6477's general guarantee is untouched -
  malformed_config still proves it for beads.role through the repository's
  own config file.
- Opposite direction: this PR's own
  TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted
  require.NoError on a generic-constructor read, commented "The existing
  reader maps Git exit errors to absence" - the precise behaviour #6477
  removed. Expect the propagated exit error instead. The test's intent is
  unchanged and in fact better served: only the current caller environment
  can see the changed HOME's broken .gitconfig, so that error is itself the
  proof that generic role reads still use it.

* test(init): retarget the bare row to the work-tree-less install policy

This PR's TestInitEmbeddedHooksSelectedTail/bare row (authored
2026-09-09) asserted that a bare repository fails to resolve hooks
and installs nothing. #6457 (6a4b4aa14e, 2026-09-27) added
git.ResolveWorkTreelessHooksContext specifically to end that
behavior -- its own comment calls out "turning a supported
repository into a warning and no install at all" as the defect it
fixes -- so the row pinned a policy main had deliberately
superseded by the time the two met.

Retargeted in place rather than deleted, so the bare shape keeps
coverage through the embedded-init entry point (main's new
bare/git_dir_cwd rows cover only the proxied path): bare now
installs like any other selected repository, and being its own
common directory, its hooks path lands in its own config.

Mutation-proved load-bearing: removing the work-tree-less fallback
reds this row alone (the other eight rows stay green) with
".../hooks/pre-commit: no such file or directory" -- i.e. it
reproduces the original expectation exactly.

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 16:54:33 -07:00
Jim Wordelman
ced3dfe220
fix: isolate 2 doctor role tests from global git beads.role (#6247)
* fix: isolate 2 doctor role tests from global git beads.role (refs be-klbl6)

TestCheckBeadsRole_NotConfigured and TestCheckBeadsRole_NotGitRepo fail
when a global `git config --global beads.role` is set on the host, since
`git config --get` reads global/system scope regardless of whether the
target path is a git repo. Isolate via GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEM
pointed at os.DevNull.

This commit originally also cleared the ambient BEADS_ACTOR in three
cmd/bd tests (TestCollectViperEntriesWithEnvOverride and the two
TestPrepareSelectedCommandContext_* tests). main has since fixed those
itself (06b3320a6, and clearActorEnv in context_binding_test.go), so
that half was dropped when rebasing onto main.

Test-isolation only; no production code changed.

* docs(release-gates): PASS 7/7 — be-1wwre (ambient BEADS_ACTOR / global git beads.role leak into 5 tests)

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-1wwre-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

* fix(doctor): isolate the 2 role tests via HOME/XDG, not GIT_CONFIG_*

The role reads now scrub every GIT_CONFIG* entry from the subprocess
environment (gitenv.ScrubRoutingAndSuppression, landed in #6454/#6461), so
the GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEM=/dev/null suppression this PR
originally used never reaches git and the two tests still read the ambient
global beads.role. Redirect the config search path instead, matching the
idiom TestCheckBeadsRoleIgnoresInheritedRouting already uses in this file.

Adopt-pr rebase repair (base cefcabb1e).

Review iteration 1 (both nits, non-gating; scorecard 1000/1000 approve):

- Extract the repeated 4-line preamble into isolateGlobalGitConfig(t), which
  returns the temp home, and call it from all three sites. The preamble went
  from 3 copies to 1; TestCheckBeadsRoleIgnoresInheritedRouting keeps its
  `home` for the .gitconfig/nondefault fixtures it writes.
- Record the system-scope residual in the helper doc comment: HOME/XDG
  redirection cannot close /etc/gitconfig (or PROGRAMDATA), and
  ScrubRoutingAndSuppression takes GIT_CONFIG_NOSYSTEM with it, so no
  env-based way to close system scope exists from a test in this package.

Two deviations from the reviewer's prescription, both measured:

- The helper lives in role_test.go, not beside newGitRepo in
  git_repo_template_test.go as prescribed. All three identical sites are in
  role_test.go, and that file's own
  TestNewGitRepo_UsesRepoLocalHooksPathDespiteGlobalConfig (:105) has a
  deliberately different preamble - no USERPROFILE, and GIT_CONFIG_GLOBAL
  pointed at a writable fixture so it can write a global config - so it must
  not adopt the helper. Placing the helper there would leave a non-adopting
  neighbour in the helper's own file, manufacturing the drift the nit targets.
- The doc comment scopes the NOSYSTEM claim to ScrubRoutingAndSuppression
  rather than "the scrub". ScrubRouting (keepSuppression=true) retains the
  suppression trio - routing.go:121 short-circuits the isConfigSuppression
  exemption only when keepSuppression is false - as bare_parent_fallback_test.go:175
  documents. Measured both arms: ScrubRoutingAndSuppression drops
  NOSYSTEM/GLOBAL/SYSTEM and keeps HOME/USERPROFILE/XDG_CONFIG_HOME;
  ScrubRouting keeps all three.

Behaviour-preserving and non-vacuous: cmd/bd/doctor is 885P/4F/15S, the same
4-name pre-existing FAIL set as the pre-refactor head; neutering the helper
body reds exactly 5 cells (both targets plus absent/nonrepository/default_global)
while repository/inline/invalid stay green.

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Gas City Merge Queue <noreply@gascity.local>
2026-09-29 13:26:35 -07:00
ecuthiell
cb9a68896e
fix(hooks): keep standalone operations in one selected Git context (#6463)
* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96)

Reported by bee-ghosttrack in gastownhall/beads#6343.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitignore): share append byte composition (saa-cgh.105)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(gitignore): clarify exclude fixture path variable (saa-cgh.104)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): refuse exclude writes after read errors (saa-cgh.110)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(config): explain role command routing policy (saa-cgh.99)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitignore): use shared composition for exclude rules (saa-cgh.111)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitignore): omit the empty exclude leading separator (saa-cgh.112)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): isolate role cleanup in the selected repository (saa-cgh.109.4)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): reset only common local role configuration (saa-cgh.109.10)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): scope hooks-path cleanup to selected common config (saa-cgh.109.11)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(hooks): explain conservative tracked-file guard (saa-cgh.98)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(git): resolve hooks paths in an explicit read-only context (saa-cgh.109.17.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Bind init hook operations to the selected repository (saa-cgh.109.17)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Give the hooks tail fixture an explicit remote context (saa-cgh.109.17)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(git): canonicalize the hooks fixture repository root (saa-cgh.109.17.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(hooks): make worktree role preservation independent (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Keep init role operations on the captured selected Git context (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Clarify hooks resolver ownership and preserve work-tree diagnostics (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Report selected config read failures during hook reset (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Explain restoration of absent routing variables in selected exclude tests (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): keep successful config stdout separate from diagnostics (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): complete selected hook options and alias handling (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks): keep standalone operations in one selected Git context (saa-cgh.120.4)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Assert standalone hook diagnostics through the CLI stderr contract (saa-cgh.120.4)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(hooks): isolate output mode and accept repository path aliases (saa-cgh.120.4)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(hooks,config): clear the out-of-repo hooks path, close the fail-open secret guard

Maintainer adoption fixes for the three majors raised by the #6463 review.

1. `bd hooks install --beads` configures <effective .beads>/hooks, which
   BEADS_DIR or a .beads/redirect can place outside the repository, but the
   cleanup predicate (doctor.IsBeadsManagedHooksPath) matched only the two
   repo-relative forms. Uninstall therefore deleted the hook files and left
   core.hooksPath pointing at the emptied directory: .git/hooks stays shadowed,
   every hook is silently disabled, and beads-managed config is still installed
   -- the exact failure the GH#4440 contract at hooks.go:1505 exists to stop.
   `bd doctor --fix` shares the predicate, so nothing repaired it either.

   At base the same command wrote files to FindBeadsDir()/hooks but configured
   <mainRepoRoot>/.beads/hooks, a value the predicate does match, so the config
   was always removable. Making the write target consistent was the right fix;
   it just left the cleanup predicate behind. The regressing slice is
   post-uninstall removability.

   The predicate now takes the resolved storage hooks directory explicitly, and
   uninstall, `bd doctor --fix` and CheckHooksPath all resolve it through one
   new helper (doctor.BeadsManagedStorageHooksDir -> beads.FindBeadsDir), which
   is the same resolution install itself performs. Deliberately not
   ResolveBeadsDirForRepo: that is repo-anchored and blind to BEADS_DIR, i.e.
   half the finding's population. The new arm is gated on a resolved storage
   directory so it can never reach a third-party hooksPath.

   The `beads` subtest flips from "outside-storage predicate remains
   conservative" to asserting core.hooksPath is absent after uninstall; the
   doctor side gains TestFixHooksPath_ClearsDanglingOutOfRepoStorageHooks and
   five predicate table rows, including the negatives that pin the gating.

2. internal/config.isGitTracked gained `cmd.Env = gitenv.ScrubRouting(...)` with
   no inherited fallback. Its only caller is fail-open by construction -- a
   probe that cannot answer means "untracked" and the secret write proceeds.
   Probed directly with real git: in a bare-repo-plus-external-work-tree layout
   the scrubbed probe exits 128 while the inherited one exits 0, so scrubbing
   alone made `bd config set ai.api_key` write the secret into a git-tracked
   config.yaml that base refused -- a hardening that moved a guard toward
   exposure. It now uses the two-probe shape this same range already applies in
   isGitTrackedFileWithEnv (scrubbed first, inherited fallback, either index
   tracking the file refuses the write).

3. cmd/bd/config.go's "All role commands ignore inherited Git routing" is a
   false universal: the readers that decide maintainer-vs-contributor
   (internal/routing, beads.RepoContext.Role, doctor/role.go, config_show.go)
   are unscrubbed, so GIT_CONFIG_COUNT/KEY/VALUE still flips the role. Narrowed
   to what is true -- bd config's own role read and write -- and it now names
   the uncovered reader plane instead of claiming coverage over it.

   The reader-scrub arm is deliberately not taken here: #6461's published head
   already hardens all four reader files (verified at refs/pull/6461/head), so
   duplicating it would rewrite four files an open sibling PR is already
   changing. No sibling head is an ancestor of this one, so whichever leaf
   merges first must carry the reader legs.

Also fixed, non-gating and nearby:

- install/uninstall act on the selected config-scrubbed hooks path while every
  status and execution reader (bd hooks list, bd doctor, runChainedHook) still
  resolves through the inherited context -- and git itself honors the inherited
  core.hooksPath. When the two disagree, a warning now names both paths instead
  of reporting a bare success that `bd hooks list` will contradict. The
  inherited path was already computed, so this costs no extra subprocess.
- the `rev-parse --absolute-git-dir` failure now carries git's stderr, as
  loadGitContext does for the same class of failure.

Second review iteration: the three majors above were validated fixed by both
lanes, leaving one minor and two nits, none of them merge gates. The minor is
accepted with its slice pinned; the rest is bookkeeping.

- The cleanup predicate recognizes what install would configure *right now*
  (doctor.BeadsManagedStorageHooksDir -> beads.FindBeadsDir), not the value
  install actually wrote, and every FindBeadsDir arm reads live inputs
  (BEADS_DIR, redirect contents, storage existence, process cwd). When those
  drift between install and cleanup the value becomes unclearable again. Closing
  it needs install to record what it wrote (a local beads.hooksPath key) and the
  predicate to match the record -- new persisted surface, deliberately not added
  in an adoption fixup after the review converged. Filed as bd-s76jm. The slice
  is now pinned rather than silent, by two tests that must flip when bd-s76jm
  lands and that pair with the existing opposite-polarity pins:
  TestFixHooksPath_LeavesDanglingStorageHooksWhenStorageIsGone (whole storage
  deleted -- the trigger CheckHooksPath's own docstring names for GH#4440) and
  TestStandaloneBeadsUninstallLeavesHooksPathWhenResolutionDrifts (BEADS_DIR set
  at install, absent at uninstall: the hook files are deleted and
  core.hooksPath survives). Predicate-level, `storage hooks with no storage
  resolved` -> false already pinned it.
  Not taken instead: widening the predicate by path shape. The arm is gated on a
  resolved storage directory precisely so it cannot reach a third-party
  hooksPath, and two table rows pin that.
- cmd/bd/config.go's narrowed comment scoped its guarantee to "bd config's own
  ... read and write" while listing `bd config show` as an unscrubbed exception
  -- and `bd config show` is a bd config read (config_show.go:336), so the
  scoping clause contradicted its own exception list. It now names the four
  subcommands that really are scrubbed. Note that is get/set/set-many/unset:
  config.go:903 is `bd config set-many`, so the reviewer's suggested
  "get/set/unset" wording would have under-named the set.

The four items this commit previously called "tracked follow-ups" carried no
bead ids, which made them declines that would evaporate at merge. Now filed:

- bd-ewdt8: the GH#4440 uninstall regression suite still exercises the
  production-dead uninstallHooks/resetHooksPathIfBeadsManaged rather than the
  shipped hooksUninstallCmd route. Tabling those cases over both entry points is
  a test-only refactor across nine call sites; the shipped route does now carry a
  real hooksPath-clearance assertion (item 1).
- bd-ez09k: exposing GitDir on git.HooksContext to drop the extra rev-parse is
  declined on risk, not cost (loadGitContext's absolute git dir is anchored on an
  already symlink-resolved workDir, while `rev-parse --absolute-git-dir` runs
  from the raw cwd, so substituting it changes the provenance of the pinned
  GIT_DIR inside the very resolver under review, for a finding with no gate
  impact); and `isRoleGitRepo`'s doubled probe (init_proxied_server.go) is
  untouched because all four open sibling PRs rewrite that file (32-57
  insertions each).
- bd-16d58: `bd init` still installs beads hooks through the legacy
  installHooksWithOptions (init.go:2072, beadsHooks=true), which writes files to
  FindBeadsDir()/hooks while configuring <repoRoot>/.beads/hooks. Both values are
  now clearable, but that route's install/config mismatch remains. Corrected
  scope: `bd config apply` is not in this population -- config_apply.go:202
  passes beadsHooks=false, so it takes the common-git-dir branch and configures
  no hooksPath at all. bd-s76jm blocks it: making this route configure an
  out-of-repo value without the recorded-value fix would trade a
  hooks-never-run bug for an unclearable-core.hooksPath one.

Validation (env -u BEADS_DIR, private TMPDIR):

- internal/config: full package green.
- cmd/bd/doctor: full package run at the reviewed head and with this fixset
  produce an identical 7-test failure set, all environment-driven (reachable
  Dolt server, global beads.role=maintainer, ambient dolt.host/dolt.user).
- cmd/bd: the full package exceeds go test's 10m default at the reviewed head
  too, aborting before it reaches any hooks test (pr.yml:973 documents this and
  uses -timeout=30m). Instead, all 51 tests in the four files that touch the
  changed symbols pass under CI's flags: -tags gms_pure_go -race -short.
- go vet clean for linux, CGO_ENABLED=0, and GOOS=windows CGO_ENABLED=0 over
  cmd/bd/..., internal/config/... and internal/git/... -- the two new
  unconstrained cmd/bd test files still compile in the no-cgo lanes.
- Mutation proofs, each reddening only its own pin while every incumbent stays
  green: removing the predicate's storage arm reds exactly
  TestIsBeadsManagedHooksPath/out-of-repo_storage_hooks,
  TestFixHooksPath_ClearsDanglingOutOfRepoStorageHooks and
  TestStandaloneHookCommandsUseSelectedContext/beads; removing isGitTracked's
  inherited fallback reds the new external-work-tree test with
  `refusal = <nil>`, the fail-open write itself, while the three pre-existing
  routing cases stay green; suppressing the divergence warning reds only
  TestStandaloneHooksWarnOnEffectivePathDivergence.

Second-iteration validation (same flags):

- cmd/bd/doctor -run 'TestFixHooksPath|TestCheckHooksPath|TestIsBeadsManagedHooksPath':
  29/29 === RUN green, counted rather than read off a bare `ok`.
- cmd/bd, the five hooks-context tests: 16/16 === RUN green, including the
  incumbent .../beads arm that asserts the value IS cleared without drift. That
  arm and the new drift test differ by one setup line and assert opposite
  outcomes, which is what makes the new pin non-vacuous; each new test also
  asserts its own precondition (no storage resolves) so it cannot pass for the
  wrong reason.
- gofmt, git diff --check, go build, and go vet clean for linux, CGO_ENABLED=0
  and GOOS=windows CGO_ENABLED=0 over cmd/bd/... -- the added doctor import in
  cmd/bd/hooks_worktree_test.go compiles in the no-cgo lanes.
- cmd/bd/config.go's delta is comment-only, so no behavior and no generated CLI
  docs are affected.

Pre-approval CI repair: main advanced 11 commits after the review loop, and
the merged tree (this head merged with main) reds two tests that are green on
each side alone. Base-parity proves it: internal/storage/domain/git is 31/31 at
main alone and 33/33 at the reviewed head alone, but 5 FAIL merged. GitHub
builds refs/pull/6463/merge, so this is the tree CI will actually test.

Both reds are the same two-way collision between this PR's role-read hardening
and #6477 ("preserve config read errors instead of treating them as absent"):

- This PR's TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted
  `require.NoError` on a generic `beads.role` read whose HOME holds a broken
  .gitconfig, with the comment "The existing reader maps Git exit errors to
  absence." #6477 deliberately deleted exactly that premise, so the broken
  config now surfaces as a real error (exit 128). HOME is not a routing key, so
  the changed HOME is still visible to the generic reader -- which is what the
  subtest exists to prove. The assertion flips to `require.Error`; `found` and
  the empty value still hold, and the selected-constructor half is untouched.

- #6477's TestConfig_ReadFailuresAreNotMissing/invalid_routing_boolean poisons
  GIT_CONFIG_NOSYSTEM and read `beads.role`. gitenv.IsRoutingKeyForOS treats any
  GIT_CONFIG* key as routing (routing.go:61, a prefix rule, not the explicit
  map), so this PR's role-read scrub strips the poison and the read succeeds --
  #6477's row is obsoleted by design for the one key this PR hardens, and its
  tail BeadsRole assertion with it. The row is retargeted to test.marker, a key
  that still inherits routing, which preserves #6477's contract (a routing-env
  read failure must surface as an error, exit 128 with a diagnostic) on the same
  mechanism. Its role-read leg now asserts the hardened outcome positively, so
  the boundary between the two contracts is pinned rather than dropped. The two
  untouched rows (malformed repo config, invalid key) never depended on routing
  env and stayed green throughout.

Repair validation, on the merged tree, env -u BEADS_DIR and a private TMPDIR
outside the worktree:

- internal/storage/domain/git: 45/45 === RUN PASS, 0 FAIL, 0 SKIP.
- Non-vacuity: dropping the GIT_CONFIG_NOSYSTEM poison reds the retargeted row,
  so it still exercises the routing mechanism rather than passing trivially.
- cmd/bd blast radius (188 selectors from every cmd/bd test file either side
  changed): the failing-name set is identical to main's under the same selector
  and host -- 16 names both sides, zero new -- while RUN rises 393 -> 529 and
  PASS 357 -> 493, so all +136 added executions pass.
- cmd/bd/doctor full package: identical 6-name failure set at main alone and
  here; RUN 876 -> 896 and PASS 855 -> 875. All six are host-environmental
  (global beads.role=maintainer, a live Dolt server on 127.0.0.1:3307).
- internal/config 398/398, scripts 98 RUN/0 FAIL (including #6482's rewritten
  check_doc_freshness_test.go), gitenv+execenv+githooksenv+gittraceenv 64 RUN,
  internal/git+gitignore 68/68, storage/domain/fs 84/84, dolt credentials 34/34,
  metrics 58/58, drift packages (beads, query, timeparsing, issueops, schema)
  1559 RUN/0 FAIL.
- scripts/check-doc-freshness.sh passes on the merged tree, which clears #6482's
  new duplicate-marker failure mode against the DOCS rows this head touches
  (cmd/bd/main.go, cmd/bd/config.go, cmd/bd/*.go).
- go build ./... exit 0; go vet exit 0 over all 20 changed packages for linux,
  CGO_ENABLED=0 -tags gms_pure_go, and GOOS=windows CGO_ENABLED=0.
- BD_LINT_NEW_FROM_MERGE_BASE=511849496 make ci-pr-lint: gofmt clean,
  golangci-lint 0 issues, golangci-lint (windows) 0 issues. This is the gate a
  never-pushed maintainer fixup otherwise evades entirely.

The base merge is a separate commit below this one so the maintainer fixup stays
a single commit; its tree was verified identical to an independently computed
git merge-tree of the reviewed head and main.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* build(bazel): restore the internal/utils debug dep the merge dropped

Merge-queue inference repair for PR #6463 (stop reason ci_repairable).

The three Bazel lanes were red on this PR and green on main -- eight
consecutive successful bazel.yml runs on main, including the tip this branch
merged. The cause is the merge commit 86defb414, not the PR's own change: main
carries "//internal/debug" in internal/utils' go_library deps (added by #6907's
BUILD sync), and this branch's copy of internal/utils/BUILD.bazel still dates
from #6798. The merge kept the branch side and discarded main's newer content,
so the dep row was lost while internal/utils/id_parser.go -- which is on main
and imports internal/debug -- still needs it.

Regenerated with the repository's own `make bazel-sync`; the result is
byte-identical to origin/main's version of the file, and a second sync is a
no-op, so this restores exactly what the merge dropped and nothing else.

Proven by counterfactual: with the row removed, `bazel build
//internal/utils:all` fails with "GoCompilePkg ... compilepkg: missing strict
dependencies" -- the CI failure class -- and with it restored the same command
exits 0 (390 actions). `go build ./...` is clean and `go test ./internal/utils/`
passes.

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 13:20:38 -07:00
postoso
9017d33745
feat(count): accept --has-metadata-key (#6282)
bd list, bd ready and bd search all take --has-metadata-key. bd count did
not, so counting the rows that merely carry a key meant listing them and
measuring the page. This is the last metadata-filter parity gap between
count and the listings.

The storage layer already carries the filter: types.IssueFilter has
HasMetadataKey and sqlbuild.AppendMetadataClauses consumes it. What was
missing is the role field, the builder wiring, the CLI flag and the HTTP
contract, so this is one change rather than a stack.

Parsing matches list_input.go and ready_input.go, including the key
validation. BuildCountFilter now passes the key to ValidateMetadataFilters
instead of the empty string it passed before, which makes the role's
existing refusal reachable from the count surface; failReadErr already
classifies that error as a 400 on has_metadata_key.

apigen types are regenerated from the spec via go:generate, not hand
edited. The pinned CLI docs are untouched.

Fixes #6160

Co-authored-by: postoso <postoso@users.noreply.github.com>
Co-authored-by: Gas City Adopt-PR <noreply@example.com>
2026-09-29 13:16:37 -07:00
ecuthiell
8269a88cbf
fix(compact): target external GC at the active database (#6327)
* fix(compact): report active database size (#5619)

Measure legacy admin compact --dolt reporting through ActiveDatabaseSizer so sibling databases cannot distort reclaimed-space numbers. Omit unavailable advisory measurements without blocking GC.

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* docs(compact): explain the legacy size field names

Keep the existing compact JSON schema distinct from the newer GC helper.
The active external-GC target is addressed by the separate issue6313 leaf.

* fix(compact): select the authoritative local active GC directory

Ask the active storage instance for its optional external-GC directory
capability. Reuse the authority captured at store open, and refuse stale,
unsupported or invalid local targets rather than guessing from a root,
general CLI path or advisory size. Preserve archive-level fallback behavior.

Add native owned-process target and no-launch regressions plus instance
authority tests; retain the parent active-size and legacy JSON contracts.

Fixes #6313

* fix(compact): resolve GC capability through storage decorators

Use the existing storage unwrapping boundary so external GC sees the captured
active database behind the root command's dependency, telemetry and hook
decorators. Cover owned, shared and unsupported stores through the real chain,
and describe the active database in compact help.

Refs gastownhall/beads#6313
Agent: unknown-model/unknown-reasoning

* fix(compact): preserve external GC refusal diagnostics (#6313)

Route all four new target refusals through the standard error/hint formatter
and assert their stderr schema, message, hint and exit status. Preserve the
relative-path refusal and unavailable dry-run target omission. Update the
requested compact and flatten help mirrors without regenerating other docs.

Addresses the diagnostics and documentation review on PR #6327. Existing
PR #5668 ancestry and mandatory parent-first sequencing remain unchanged.

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* docs(compact): align flag help with active GC target (saa-cgh.94)

Authored by /root/cgh86_review; closes the independent root review help finding.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs: retain release-pinned CLI references (saa-cgh.94)

Preserve corrected live compact/flatten help while generated references continue to match docs/cli-docs.pin v1.2.2. Fix the exact six-line hosted docs-policy failure without changing pin authority.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(compact): classify cancellation before the GC authority refusal

Maintainer review fixes for #6327, review iteration 1. Non-gating findings
only: the synthesis and the quality scorecard both returned approve with no
blocker and no major finding.

Taken:

- Error Handling & Resilience (minor, both lanes). runCompactDolt formatted a
  cancelled or expired context as the permanent "cannot select a local
  database" refusal plus its four-cause hint, and in --dry-run turned it into a
  hard exit-1. Classify context.Canceled/DeadlineExceeded ahead of the
  ErrUnsupported arm and report the interruption instead. The ctx probe stays
  in ExternalGCPath: it is the only cancellation checkpoint before the
  uninterruptible external `dolt gc`, so the finding's other arm (drop the
  probe) would trade a misleading message for launching a multi-minute GC on an
  interrupted command.

- Change Impact / Blast Radius (minor). Document why
  resolveLocalActiveDatabaseDir keeps the cfg.AutoStart conjunct, and make the
  CLI hint name the remedy (`bd config set dolt.auto-start true`) instead of
  only the condition. The offered code arm is declined: AutoStart rides
  resolveAutoStart's own exclusions (forced false for ServerModeExternal and
  under BEADS_TEST_MODE=1), so dropping it widens GC authority - a behavior
  change, not a cleanup.

- Release Safety (minor). Add the three new test files to the gazelle explicit
  go_test srcs lists so this PR's assertions are visible under `bazel test`.
  Verified with `bazel run //:gazelle -- --mode=diff`: gazelle requests none of
  the three, so the rows match its own output. The two rows it still wants are
  pre-existing base drift in unrelated files and are left alone.

- Test Evidence Quality (nit). The two "unsupported ... through decorators"
  rows were measured vacuous for the decorator claim. Pin the refusal's origin
  through ErrUnsupported.Backend ("external" = the active store refused,
  "active store" = the interface assertion missed) and pin the opposite
  polarity on the size-only/locator-only rows. Residual recorded on the test:
  the dry-run decorator row still cannot discriminate, because its benign
  preview is identical for both origins.

Declined, and carried to the human-approval summary:

- Debuggability & Operability (minor, gate impact none). Reusing the `bd gc`
  companions adds production output in an iteration no further review pass
  grades, and the alternative arm would assert the refs are left in place
  "deliberately", which nothing in the change establishes.

- Resource Lifecycle & Cleanup (nit, Required fix: none). exec.CommandContext
  would kill a mid-flight `dolt gc`; that is a data-safety question for the GC
  path rather than a cleanup.

Validation: `go build ./...` and `go vet` on cmd/bd + internal/storage{,/dolt}
clean; scripts/ci/pr-lint.sh against the pinned base green (gofmt,
golangci-lint 0 issues, windows cross-lint 0 issues), proved non-vacuous by a
misspell planted on an added line; 66 PASS / 0 FAIL / 0 SKIP over the covering
cmd/bd selectors. Both new pins are mutation-proved: removing the
classification arm reds exactly the three new cancellation rows and nothing
else, and dropping storage.UnwrapStore now reds three decorator rows where it
previously reddened two. internal/storage/dolt/store.go is comment-only.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Gas City Merge Queue <merge-queue@gascity.local>
2026-09-29 08:27:43 -07:00
Jones
89348699b0
fix(doltremote): treat s3:// as a native Dolt remote scheme (#5948)
* fix(doltremote): treat s3:// as a native Dolt remote scheme

s3:// URLs previously survived Normalize only by falling through, and the
SCP heuristic treated any "@" in a URL as an SCP-style git remote, so an
s3 URL with "@" in its path or query string would be rewritten into a
bogus git+ssh remote. Add s3:// to NativeSchemes and anchor SCP detection
to inputs without a "://" scheme that match a user@host:path grammar.

* test(doltremote): pin the s3:// entry and the dotless host:pa@th case

Follow-up to the #5948 review. Deleting "s3://" from NativeSchemes made
no test fail, so TestNativeSchemesContainsEachNativeScheme now asserts
every entry the list holds; removing the s3:// line fails its s3://
subtest.

The base change also flipped a fourth behavior its description did not
list: a dotless pre-colon token whose only "@" sits after the colon
("host:pa@th", "alias:repo@v1") used to classify as SCP-style on the
bare strings.Contains(url, "@") check and normalize to
git+ssh://host/pa@th. It now classifies false and passes through
Normalize unchanged. Both inputs are pinned as rows in
TestIsSCPStyleGitURLRejectsNonSCPInputs; against origin/main's
remote.go they fail.

Normalize's doc comment now lists s3:// with the other native schemes.

* build(bazel): add go_test target for internal/doltremote

The PR adds remote_test.go and remote_invariant_test.go to a package whose
BUILD.bazel (added on main by #6798) declares only a go_library. Generated by
bazel run //:gazelle; no hand-written lines.

* fix(doltremote): guard FromGitURL's SCP split, cross-reference the SCP grammars

Maintainer review fixes for the four non-gating findings in the iteration-1
synthesis (0 blockers, 0 majors; quality scorecard 986/approve). The PR's own
fix is unchanged.

Contract fidelity, the one gate-impact-minor finding: FromGitURL is exported and
cmd/bd's gitURLToDoltRemote calls it directly, bypassing Normalize's
classification. Its first-colon split still rebuilt s3://bucket/team@prod/db
into git+ssh://s3///bucket/team@prod/db, the exact string this PR removes from
Normalize. That split now obeys the same "://" rule as isSCPStyleGitURL.

This takes the finding's second offered arm over its first. Gating on
isSCPStyleGitURL(url) instead changes 17 of 31 inputs across the package's own
corpus, against 9 for the "://" guard; the 8 extra are the SCP hosts that
predicate deliberately declines to classify - IDN hosts, non-ASCII userinfo and
dotless aliases - which FromGitURL converts correctly today.
TestFromGitURLStillConvertsSCPForms pins them, and mutating to the rejected arm
reds exactly those three rows while the new regression pin still passes.

NativeSchemes: the finding's "add az:// and oci:// for consistency" arm is
declined and the documentation arm taken instead. The PR body scopes this change
to s3:// and defers az:// to #6227 explicitly; #6227 is open, and it pairs
NativeSchemes with dolt.IsBackupURL - the site where the gap actually changes
behavior - so adding the entry here would have overridden a tracked contributor
decision while closing only half the bug. oci:// is in neither authority's
native list. The list's doc comment now records that narrowing, points at
remotecache.remoteSchemes as the fuller authority, and states that membership is
inert: every entry contains "://", so isSCPStyleGitURL rejects it and
Normalize's closing "return url" returns the same bytes listed or not. Dropping
gs:// reds one census leaf and no behavioral test, which measures that claim
rather than asserting it. The new FromGitURL table covers az:// and oci://
precisely because the guard is keyed on "://" and not on list membership.

Duplicate SCP grammar: scpStyleGitURLPattern's first alternative is
byte-identical to remotecache.gitSSHPattern, and the whole pattern is a superset
by exactly the user-less dotted-host form - the form on which the two already
disagree in production. Both regexes now cross-reference each other and the
divergence is pinned from each side. Exporting a shared matcher was the other
offered arm; it would have widened remotecache.IsRemoteURL's accept set, a
behavior change in a second package for a non-gating finding.

normalizeRemoteURL's doc comment restated Normalize's rules and had drifted
twice: it never gained s3://, and it named gitURLToDoltRemote as the converter
when the body calls doltremote.Normalize directly. Collapsed it to a reference
so the surface cannot drift again.

Codex's prescribed remedy for the hollow NativeSchemes census subtest is
declined, as the synthesis directs: asserting Normalize(scheme+"bucket/x") per
scheme passes against an empty list, for the same inertness reason above. The
subtest's comment, which claimed to protect a fast path it cannot observe, is
corrected instead.

go test ./internal/doltremote/ ./internal/remotecache/ green; cmd/bd named
selector 56 pass, 0 fail, 0 skip; go build ./..., go vet and gofmt clean; bazel
test passes on both packages; gazelle and go_srcs.py --check report no BUILD
drift.

---------

Co-authored-by: Julian Knutsen <julian@gastownhall.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-29 06:28:57 -07:00
Julian Knutsen
cda2407115
fix(storage): recheck blocked state after commit on the proxied (uow) path and the remaining store routes (#6942)
Extends #6719's post-commit blocked-state recheck (gastownhall/beads#6716) to
every write runner #6719 left uncovered:
- the proxied (uow) write path: every proxied CLI write, bd batch when
  proxied, and bd serve;
- DoltStore.RunInTransaction. It also settles when the regular SQL commit
  lands and only the Dolt commit after it fails (ErrCommitIndeterminate);
- the raw-transaction wisp update, close and delete writers;
- both arms of RemoveDependencyWithOptions;
- the domain/db recomputes that bypassed issueops.
The recording shapes are shared issueops Note* helpers. A failed recheck is
reported through issueops.ReportBlockedRecheckFailure (the
bd.db.blocked_recheck_dropped counter plus a warning) and never returned.

Regression tests fail on main and pass here: a deterministic proxied uow
race in six shapes, RunInTransaction and concurrent wisp-close races,
sqlmock phase tests for the indeterminate commit, and a proxied CLI fan-in
test that runs concurrent `bd close` processes and then checks `bd ready`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 03:07:09 -07:00
Julian Knutsen
51a7c8e324
fix(beads): make an explicit BEADS_DIR authoritative during discovery (#6938)
* fix(beads): make an explicit BEADS_DIR authoritative during discovery

FindBeadsDir ignored a BEADS_DIR that did not hold project files yet
(missing, empty, or uninitialized) and walked up from the current
directory instead. PersistentPreRun then rebound BEADS_DIR to whatever
ancestor workspace the walk found, so:

- `bd init` refused with "already initialized" because of the parent
  workspace instead of initializing the named directory;
- data commands (`bd list`, `bd create`, ...) read and wrote the
  parent's store.

FindBeadsDir now returns "" for such a BEADS_DIR, matching
FindDatabasePath, which already refused to fall back. Commands that
create a workspace (import/setup default path, bootstrap's
fresh-clone synthesis) target the named directory via the new
beads.ExplicitBeadsDir helper instead of CWD. Behaviour with BEADS_DIR
unset is unchanged.

Tests: FindBeadsDir unit cases (missing/empty/non-project BEADS_DIR,
initialized BEADS_DIR, unset BEADS_DIR still walks up), and a bd
subprocess regression in embedded and proxied-server modes (init under
an initialized parent, list refuses, create lands in the new store).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): note that BEADS_DIR at a project root now errors

Review follow-up for the explicit-BEADS_DIR fix: call out the behaviour
change for BEADS_DIR pointing at a project root (or a not-yet-created
.beads), which previously worked only because discovery walked up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:26:09 -07:00
Julian Knutsen
5ac483bc75
fix(show): support bd show --watch under --proxied-server (#6933)
bd show --watch was refused in proxied-server mode (proxy.watch.unsupported). The direct and proxied routes now share one watch loop (2s poll, redraw on id:status:updated_at change, SIGINT/SIGTERM stop); the proxied route opens a short read per render/poll. A missing id now exits 1 on both routes, and failed polls keep the last render quietly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:22:09 -07:00
Julian Knutsen
e3a12f4e5c
fix(init): admit a server workspace whose .beads/dolt is empty so the version marker is written (#6935)
A server-mode workspace with an empty .beads/dolt and no .local_version was refused as a legacy workspace, blocking every command including bd init. An empty directory holds no legacy data, so the guard now admits it (server mode only); bd init writes the marker and an existing workspace in that state self-heals on its next command. Refs #5682.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:11:21 -07:00
Julian Knutsen
2bb5337355
fix(types): one source of truth for issue types across bd types and create (#6934)
bd types and create validation now both resolve custom types through issueops.ComposeCustomTypes in every mode (direct, server, proxied). Server-mode bd types now includes config.yaml types, proxied config set storage-class accepts DB types, and bd types lists the system types (message, molecule, gate, event); JSON gains additive system_types. Custom-type read errors now fail instead of being swallowed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:10:46 -07:00
Julian Knutsen
d803ec9126
fix(dbproxy): retire the proxy when its Dolt backend exits cleanly (#6937)
* fix(dbproxy): retire the proxy when its Dolt backend exits cleanly

DoltServer supervised `dolt sql-server` with cmd.Wait inside an
errgroup, and Running read the errgroup context. errgroup cancels that
context only for a non-nil result, so a backend that shut down
gracefully (dolt exits 0 on SIGTERM) was reported as running forever.
The proxy's backend health watcher never fired: the proxy stayed up and
adoptable in front of a dead store. With --proxied-server-idle-timeout 0
(the setting Gas City uses) it never went away; `bd dolt status` said
"running" and every command, `bd ping` included, failed until
`bd dolt stop`.

The supervising goroutine now reports a clean exit as errBackendExited,
so Running flips on any backend exit and Stop treats it as benign. This
follows the existing proxied lifecycle contract (child death retires
the owned proxy; the next bd invocation starts a fresh proxy/backend
pair) rather than adding in-proxy restarts: spawn, adoption, stop
epochs and identity already live in the on-demand start path, and a
second restart loop inside the proxy would duplicate that and could
mask a crash-looping backend.

`bd dolt status` no longer headlines a proxy whose managed backend is
gone as "running"; it says the proxy is up but not serving and points
at `bd dolt stop` (for proxies from an older bd). The JSON payload is
unchanged. `bd ping` already verifies by running SELECT 1 through the
proxy, so after this fix a successful ping reflects a live pair.

Tests: DoltServer Running goes false after SIGTERM (clean exit) and
SIGKILL, and Stop succeeds; managed-local lane test that SIGTERMs the
backend with idle timeout 0 and requires the proxy to retire and
`bd ping --json` to succeed on a fresh pair; status render case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(dolt status): report running=false for a proxy over a dead managed backend

Review follow-up: the JSON running field now means "serving" (a live proxy
and, on a managed topology, a live dolt behind it), so scripts that key off
running alone are not fooled by a stranded proxy left by an older bd.
proxy_pid/proxy_port and backend_* are unchanged. Adds the PR link to the
CHANGELOG entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): resolve merge markers left by the origin/main merge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:48:15 -07:00
seanmartinsmith
8870c6866d
fix(prime): describe the memory split instead of prohibiting MEMORY.md (#6111)
* fix(prime): describe the memory split instead of prohibiting MEMORY.md

The memory guidance predates harness-native auto memory, whose index file
is also named MEMORY.md and is machine-local rather than the multi-account
fragmentation case the line was written against. As written it tells agents
to file per-operator content in the shared, replicated store - the one place
it does not belong.

Rewrite the four renderings of that sentence to describe the split the two
stores actually have: durable project facts in `bd remember`, per-operator
preferences in the harness's own memory. The fragmentation warning stays,
pointed at the case where it is true.

Refs #5169

Executed-By: pc

* fix(prime): bring the codex template in line, add CHANGELOG entry

Review on #6111 found a fifth rendering of the prohibition:
internal/templates/agents/defaults/beads-section-codex.md:19 says
"do not create ad hoc memory files" without the literal MEMORY.md, so the
grep that scoped the first commit missed it. It ships through bd init for
the codex harness, the same re-introduction path the minimal template was
included for. Reword it to the same split.

Add the CHANGELOG entry under Unreleased / Changed, matching #6011.

Refs #5169

Executed-By: mac

* fix(prime): pin the memory-guidance invariant, drop the storage claim

Maintainer review fixes for the adoption of #6111, iteration 1. Both items are
non-gating (scorecard 981/approve, no blocker or major); they are taken because
the rebased branch needs a maintainer push either way.

Test Evidence Quality (minor): nothing asserted that the four renderings had
stopped prohibiting the harness's own MEMORY.md. The only pin on these bodies
was a presence check for `bd remember`, which passed identically before and
after the rewording, so re-introducing the prohibition at any one site would
have left every test green. Added negative assertions to
TestRenderSectionMinimal and TestCodexSectionBody, plus
TestPrimeMemoryGuidanceDoesNotProhibitHarnessMemory covering both the CLI and
MCP renderings. Asserting the absence of the old prohibition, rather than
pinning the new prose, keeps the guard valid under any future rewording.

The review prescribed `!strings.Contains(body, "MEMORY.md")` at every site. That
is vacuous for the Codex body, which spelled its prohibition "do not create ad
hoc memory files" and never named the file (0 occurrences at ae1a493e0), so that
site asserts both spellings.

Measured, not assumed: restoring all three rendered surfaces to their
upstream-base blobs reds exactly the new assertions -- templates 31 PASS /
2 FAIL, the Codex failure on "ad hoc memory files" and not on MEMORY.md, and
both subtests of the prime pin -- while every incumbent stays green. That same
revert was fully green before this commit.

Debuggability (nit): the full rendering ended "they aren't project knowledge and
beads doesn't store them", which states a capability (`bd remember` will in fact
persist any string handed to it) rather than the intended policy, and was the
odd one out among the four surfaces. Reworded to "so keep them out of beads"
rather than the suggested "so don't put them here": in the rendered text "here"
has no antecedent, and the nearest location named is the harness's own memory,
which would invert the sentence.

Validation: gofmt clean, go build ./... exit 0, go vet clean on both packages,
golangci-lint 2.10.1 reports 0 issues, internal/templates/agents 33P/0F/0S,
prime run-set green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 01:23:19 -07:00
Julian Knutsen
c4b1cb699d
fix(sql): classify bd sql statements with the SQL parser; never drop result sets (#6932)
Proxied bd sql misclassified WITH [RECURSIVE] ... SELECT as a write and silently returned no rows; CALL result sets were dropped on both paths. Classify statements with the dolthub/vitess parser (internal/storage/sqlclass: Read/Write/Mixed); Mixed commits and renders any rows, so no path silently drops a result set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 01:08:10 -07:00
Julian Knutsen
e7138e93af
ci(bazel): server-Dolt storage and proxied tiers on remote execution (#6940)
* test(integration): let SubprocessRunner reuse a prebuilt test binary

BEADS_TEST_SUBPROCESS_BINARY hands SubprocessRunner an already-built test
binary of the package instead of running `go test -c`, which no Bazel
action can do offline (it needs the module source tree and module cache).
A Bazel target passes the running go_test itself: the helper tests
(TestHelperSchemaInit, TestHelperMultiStore) live in the same package.
Unset, behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(dolt): keep a lane's REQUIRE switch out of the leak-probe child

TestSuiteFixtureLeakFailsOwningSuite re-runs the suite with
BEADS_TEST_SKIP=dolt on purpose. When the parent runs under
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 (a fail-closed server lane), the child
inherited it and TestMain exited FATAL before the leak sweep the test
checks. Clear it in the child like the other suite-scoped variables.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(bazel): proxied-server and server-Dolt storage tiers (D6d, D6e)

PR Risk's "Test (Proxied Dolt Cmd N/15)" (also main.yml's) and "Test
(Server Dolt Conformance)" / "Test (Server Dolt Full Suite N/16)" as
Bazel variants against local dolt sql-servers (internal/testutil local
backend, pinned dolt from the test wrapper), fail-closed like the
dolt-server lane:

- //cmd/bd:bd_proxied_test: 15 shards; shard k runs the job's
  proxied-test-shard.sh k+1 15 through go_test_manifest_shard.sh over the
  race bd_test, non-race bd_for_tests as the subprocess bd,
  BEADS_TEST_PROXIED_SERVER=1, GOMAXPROCS=4. Tag dolt-server-proxied,
  --config=doltserver-proxied (the doltserver lane's build).
- //internal/storage/dolt:dolt_server_{conformance,full}_test over
  dolt_race_off (go_test_race_off of dolt_test: the jobs' binary is not
  race); the full suite runs server-storage-test-shard.sh k+1 16 with
  BEADS_TEST_ENV_RUN_DOLT=1 and hands SubprocessRunner its own binary.
  Tag dolt-server-integration, --config=doltserver-integration, whose
  build flags are exactly --config=integration's, so the tier shares that
  lane's compile (race-off deps land where bd_for_tests already is)
  instead of compiling the tagged graph a third time.
- dolt_test gains //internal/storage/schema:migrations as data (the
  PR4107/migration replay tests read ../schema/migrations).
- test_env.sh: BEADS_TEST_GIT_IDENTITY=1 writes the jobs' global git
  identity ("Configure Git"); the git-remote tests commit in fresh repos.
- Both tags join the taxonomy and bazelPRCoreExcludedTags, so prcore/ci
  and integration exclude them.

Per-shard names and statuses equal a replay of the jobs' commands
(container backend) for all 32 jobs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci(bazel): run the proxied and server storage tiers remotely (advisory)

bazel-doltserver gains a second, remote-only step, `bazel test //...
--config=doltserver-proxied` (15 shards of ~5-10 min with a busy dolt
sql-server each do not fit a GitHub-hosted runner; forks and rbe=off keep
the local lane unchanged). bazel-integration gains `bazel test //...
--config=doltserver-integration`, which shares its build flags, so the
server storage tier compiles nothing the integration step has not. Both
steps write their own BEP, run check_testcases.py on it, run even when the
job's first test step failed, and upload logs on failure.

Policy (TestBazelDoltServerTiersMirrorPRRisk): each variant runs its jobs'
shard script with their shard total and has script + manifest in data;
the conformance variant passes the job's flags; the jobs' race/non-race
binaries and switches (BEADS_TEST_PROXIED_SERVER, BEADS_TEST_ENV_RUN_DOLT)
match; doltserver-integration's tags and race equal --config=integration's;
the steps are pinned to their jobs. checkDoltServerRules now holds all
three dolt-server lane tags to the local-backend, fail-closed,
remote-capable rules.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci(bazel): run the proxied and server storage tiers in jobs of their own

Review of D6d/e: as steps of bazel-doltserver and bazel-integration the
tiers inherited those jobs' gating (a caller switching the integration
lane off would drop PR Risk's PR-time server tier; a gate requiring the
dolt-server lane would silently require the proxied tier too) and
lengthened their critical paths.

bazel-proxied (--config=doltserver-proxied, 15 shards) and
bazel-server-storage (--config=doltserver-integration: conformance + 16
shards) are remote-only jobs that need only rbe, each with its own BEP,
check_testcases.py step and log upload, 25-minute test step inside a
30-minute job. bazel-doltserver and bazel-integration are back to their
previous content, including the dolt-server step's 80-minute timeout for
local runs. The server tier shares bazel-integration's compiles through
the remote cache (same build flags).

The proxied tier mirrors PR Risk's race bd-cmd-test; main.yml's twin
job runs build-artifacts' non-race one, so Bazel is the stricter of the
two. Comments now say so, and the policy test pins main.yml's build so a
change there is noticed. Policy: the new jobs are pinned (command,
config, remote-only if, BEP + testcase steps, timeouts, log upload), and
no tier step may run in bazel-integration or bazel-doltserver.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 23:01:40 -07:00
Bùi Phan Viết Cường
5e3deaa18a
test(proxied): un-skip the two bd list subtests that waited for bd dep add proxied support (#6244)
cmd/bd/list_proxied_integration_test.go skipped
ready_parent_tree_excludes_blocked_descendants and
tree_relates_to_does_not_nest_or_drop_epics (the GH#3936 regression) with
a TODO saying `bd dep add` had no usesProxiedServer() dispatch and failed
with "storage is nil" under proxied mode. That dispatch exists now
(cmd/bd/dep.go routes `dep add` to runDepAddProxiedServer), so the skips
only hid coverage.

Port both subtests from their embedded twins in list_embedded_test.go
unchanged apart from the proxied helpers (bdProxiedCreate, bdProxiedDep,
bdProxiedList). Same assertions, same flags, same failure messages.

Run under BEADS_TEST_PROXIED_SERVER=1 against the shared Dolt container:
both subtests pass (0.60s / 0.44s), whole TestProxiedServerList passes.
2026-09-28 15:19:27 -07:00
Vishnu J
9c94613b2b
fix(list): correct --limit help for piped-output default (#6276)
bd list --help claimed an unconditional default of 50 for --limit, but
gatherListInput (cmd/bd/list_input.go) resolves effectiveLimit through
a switch: an explicit --limit wins, then --all is unlimited, then a
configured list.limit applies, then piped stdout (not a terminal) is
unlimited (GH#4094, #4158), then agent mode (BD_AGENT_MODE=1 or
CLAUDE_CODE set) at a terminal is 20, and only then 50. Neither the
piped nor the agent-mode arm was documented, so a script piping
bd list --json | ... or an agent at an interactive terminal could not
tell its actual limit from --help alone.

Reworded the --limit usage string to state those arms in the switch's
order, each with its precondition: an explicit --limit always wins
(so --all --limit 5 is 5, and 0 means unlimited); otherwise --all is
unlimited; otherwise a configured list.limit applies; otherwise
unlimited when piped, else 20 in agent mode at a terminal, else 50.

Added TestListLimitHelpDescribesPipedBehavior, which pins the usage
string verbatim (a substring check would accept a clause scoped wider
than its arm) and, with list.limit configured to 7, checks that
--all --limit 5 resolves to 5, --all to 0, and piped output to 7.

The flag keeps registering workapi.DefaultListLimit, so cobra still
appends "(default 50)" to the line: the registered value is never
consumed at runtime (list_input.go overwrites it with
config.GetInt("list.limit") when the flag is unset), but
internal/httpapi/apigen/types.gen.go documents it as the value the
flag registers, so changing it is out of scope here.

Fixes gastownhall/beads#6069

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 14:14:28 -07:00
ecuthiell
13150ba360
fix(hooks): apply host key identity to Git environment filters (#6321)
* fix(hooks): use host key identity when filtering child environments

Use execenv for the chained-hook guard and export Git routing filters.
Keep their existing per-consumer denylist and valueless GIT_CONFIG prefix
behavior while matching Windows os/exec key identity. Preserve the input
slice and exercise mixed case, Unicode, malformed keys and value handling.

The worktree-removal site from issue6198 remains owned by PR5623. This
stack depends on PR5672 and must not close6198 before both parents land.

* test(hooks): exercise both host key policies through actual filters (saa-cgh.89)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(hooks): share environment entry parsing and clarify serial seam (saa-cgh.89)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* build(bazel): list hook_env_test.go in cmd/bd go_test srcs

The PR's new cmd/bd/hook_env_test.go is untagged but absent from the
gazelle-managed go_test srcs list, so its two pins are invisible to
`bazel test //cmd/bd:bd_test`.

Both review lanes held this at minor on the grounds that untagged srcs
drift is tolerated in this package: three untagged test files
(config_leaked_secret_test.go, init_git_bootstrap_routing_test.go,
init_role_environment_test.go) are likewise unlisted at this PR's base.
That precedent is gone at the merge target. At origin/main 147047e15 the
census is 23 omissions, all 23 //go:build-gated, zero untagged -- main
landed all three rows -- so this file would be the merge target's only
untagged omission.

Two advisory steps in .github/workflows/bazel.yml (absent at this base,
present at the merge target) act on that: `Go test equivalence`
(tools/bazel/equivalence.py, which fails on any Go test `go test` runs
and Bazel did not, including "missing target"; neither new test name is
in equivalence_allowlist.txt) and the `make bazel-sync` drift check. The
job's `if` includes head.repo.fork == true, so it always runs for this
fork PR.

Generated by `bazel run //:gazelle`, which is what the drift step
compares the tree against. Gazelle also emitted the three base-owned
cmd/bd rows and an internal/notion change; all four are already present
at the merge target and were reverted so they merge from main's side.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* build(bazel): sync scripts go_test srcs (adopted base debt, not this PR's change)

scripts/upgrade_smoke_loop_test.go is untagged and absent from the
gazelle-managed go_test srcs in scripts/BUILD.bazel, which reds the
advisory Bazel lane two ways: `Go test equivalence` reports
`TestUpgradeSmokeMultiVersionDispatch` as a test `go test` runs and Bazel
did not, and the `BUILD files in sync` step's own `make bazel-sync` adds
the row and then fails on the drift.

This is NOT introduced by this PR, which touches zero files under
scripts/. The gap is identical at this PR's base fc2351a51c and at HEAD,
and the Bazel lane already fails on main's own pushes at fc2351a51c,
147047e15, 90f8e42f1 and 8c889c1f2 for this same reason -- it currently
reds for every PR in the repo. Carried here because main is unprotected,
so the pre-approval CI gate takes the strict path in which any failing
run blocks, with no base-preexisting bypass.

Generated by `bazel run //:gazelle`; the local drift is byte-identical to
the drift CI reported (9345584 -> 5dfc23e). Kept as its own commit so the
contributor's hook-env work stays separable from adopted base debt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-28 14:13:56 -07:00
Julian Knutsen
6daa06244b
build(bazel): integration-tag lane (--config=integration) matching main.yml (#6916)
* fix(test): keep TestDoltServer_StartStop_UnixSocket's socket path short

t.TempDir() nests the test's name, which alone pushes the socket path past
the 104-byte sun_path guard under any TMPDIR longer than /tmp: the Bazel test
wrapper's per-process TMPDIR (114 bytes) and macOS's /var/folders/... both
silently skipped the test that main.yml's integration job runs. Put the
socket in a short os.MkdirTemp directory instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(testutil): let SubprocessRunner build with a declared go command

SubprocessRunner.Build ran `go` from PATH. Under Bazel there is no Go
toolchain on PATH, so //internal/testutil/integration's
TestBuildErrorIsMaskedByChmod failed there. BEADS_TEST_GO_BINARY, resolved
like any other runfile, now names the go command; unset, it is still `go`.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(bazel): integration-tag lane, --config=integration

main.yml's "Main Linux integration packages (N/6)" and "cmd/bd (N/8)" jobs
(and nightly's Full Test Suite) run every package with
-race -tags=integration,gms_pure_go, no -short and BEADS_TEST_SKIP=dolt.
Bazel never built the 55 `//go:build integration` files: gazelle drops a
file whose constraint names a tag it does not know.

- Root `gazelle:build_tags gms_pure_go,integration`: gazelle now lists the
  integration files in srcs and their imports in deps, and generates
  //internal/testutil/integration (integration files only). rules_go filters
  those files out of every other build, so --config=ci runs what it ran.
- --config=integration sets the tag for the whole build, like `go test
  -tags`, plus the jobs' race, BEADS_TEST_SKIP=dolt, -test.parallel=4 and a
  1200s/19m timeout pair (rbe-west's action limit; the jobs pass 30m). The
  same variants as PR core stay out (requires-docker, embedded, manual), so
  `bazel test //... --config=integration` runs the union of the 14 shards.
  A per-target gotags variant would not save the compile (gotags transitions
  the whole dep graph) and would need a second, duplicated target per package
  plus a tag to drop the plain one from this lane.
- //internal/testutil/integration:integration_test gets the pinned SDK's go
  for SubprocessRunner's `go test -c`.
- TestBazelIntegrationLaneMatchesMainWorkflow pins test:integration to
  main.yml's tags/race/BEADS_TEST_SKIP and gazelle's build_tags to a superset
  of the tags; bazel.yml's `make bazel-sync` diff already fails when a file
  gains the integration tag without a BUILD sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): sync scripts BUILD for upgrade_smoke_loop_test.go

make bazel-sync on current main adds the test file #6398 added.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(bazel): derive the integration lane's tag exclusions from PR core's

After main added the dolt-server tag, test:integration's filter still
selected those targets, and 5 of them fail under BEADS_TEST_SKIP=dolt. The
filter now excludes dolt-server, and the policy test no longer pins one
string: bazelPRCoreExcludedTags (kept equal to the taxonomy entries that say
"excluded from --config=prcore/ci") is the list both lanes check, the
integration lane minus the tags it runs. Every --test_tag_filters in the
lane or a config expanding it must exclude them, and no -test.short,
-test.skip, -test.run or --test_filter may reach it.

New tag integration-only for //internal/testutil/fixtures:fixtures_test and
//internal/testutil/integration:integration_test, whose tests are all
`//go:build integration`: --config=prcore/ci excludes them instead of
running two empty targets; --config=integration runs them. The .bazelrc
notes that ci and integration share bazel-testlogs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(bazel): note shared testlogs and dolt_test's subprocess build

bazel.yml's equivalence step reads bazel-testlogs, which --config=integration
shares with --config=ci, so a job running both lanes must check each right
after its own run. //internal/storage/dolt:dolt_test's SubprocessRunner tests
need a real `go test -c` with a module cache; they stay skipped under the
lane's BEADS_TEST_SKIP=dolt, so the target gets no go SDK data.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 14:11:34 -07:00
Athos Bernardes
fc2351a51c
fix(defer): undefer clears a stray defer_until when status isn't deferred (ga-bq3w5) (#6390)
* fix(defer): undefer clears a stray defer_until when status isn't deferred (ga-bq3w5)

`bd undefer` gated entirely on issue.Status == StatusDeferred. But the
ready-work query hides any issue whose defer_until is in the future
regardless of status, so `bd update <id> --status open --defer <date>`
(an explicit --status wins over --defer's own status=deferred default)
leaves status=open with a live defer_until: permanently invisible to
`bd ready`, with no command able to clear it. `bd undefer` refused with a
technically-true, practically-misleading "is not deferred (status: open)"
and never touched the timestamp actually doing the hiding.

Gate on defer_until instead of status alone: only flip status to open
when the issue really was deferred (mirrors the guard GH#3233 already
gave `bd update --defer=""`), but always clear a stray defer_until so
the issue can return to `bd ready`.

Adds a regression test reproducing the exact shape (status=open + future
defer_until via a single `bd update --status open --defer ...` call).
Confirmed it fails against the pre-fix code and passes with the fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(defer): mirror the undefer defer_until fix to the proxied-server route (ga-bq3w5)

PR review (bee-ghosttrack, round 1): the previous fix only patched the
embedded backend (undefer.go). runUndeferProxiedServer, used by
proxied-server/beads-team-server installs, still gated solely on
status == deferred and still overwrote status unconditionally — the
exact bug survives on that route, and CI treats it as first-class (15
green Proxied Dolt Cmd shards).

Mirror the same gate/write shape into defer_proxied_server.go: only
refuse when status isn't deferred AND there's no defer_until to clear;
only flip status to open when the issue really was deferred.

Also closes the reviewer's MINOR finding: the existing "open" fixture
can't distinguish the conditional status write from an unconditional
one (writing status=open to an already-open issue is a no-op). Adds
an in_progress case to both the embedded and the new proxied test —
confirmed by mutation that it fails against the unconditional-write
code and passes with the fix.

Shortens the undefer.go rationale comment and documents the
clear-without-clobbering behavior in the command's Long description,
per the reviewer's non-blocking nits.

Verified: go build/vet clean; gofmt clean; golangci-lint (native) 0
issues; BEADS_TEST_EMBEDDED_DOLT=1 go test -run TestEmbeddedUndefer
all 5 subtests PASS. The new proxied-server subtest could not be
executed in this sandbox (no Docker available for the shared Dolt
container), but go vet confirms it compiles and type-checks, and it
mirrors the embedded test byte-for-byte in structure. The windows
cross-lint step in `make ci-pr-lint` fails in this sandbox on files
untouched by this diff (confirmed byte-identical to origin/main) —
a pre-existing local environment gap, not a regression.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-28 11:18:25 -07:00