* Refuse reserved words and fuzzy id matches on bd comment writes
bd comment <id> [text...] treated its first argument as an id via the
same abbreviation-tolerant resolver used everywhere else, with no
protection against the id slot holding something that was never meant
to be an id. Two related failure modes came from that:
- "bd comment list <id>", a typo for "bd comments list" (or "bd
comments <id>"), silently ran with id="list" and text="<id>" instead
of erroring.
- If "list" (or any other stray first word) happened to be a
leading-prefix abbreviation of some unrelated issue's hash, the
resolver picked that issue and the comment landed there instead of
failing with "not found". This is exactly what happened in
production: 15+ automated sessions made the "bd comment list <id>"
typo over two days, and because "list" was a leading-prefix
abbreviation of an unrelated wisp's hash ("list3t0"), every one of
them wrote a garbage comment onto that wisp.
Fixes both, independently:
- checkCommentIDNotReservedWord rejects list/add/rm/delete as the id
argument before any resolution is attempted, mirroring the existing
"bd comments list" misplaced-subcommand guard.
- ResolvePartialIDExact (internal/utils) is an exact-match sibling of
ResolvePartialID: identical exact-ID and exact-hash matching
(including a wisp's hash with its "wisp-" infix stripped), but never
falls through to leading-prefix abbreviation matching. bd comment
now resolves through this via a new resolveAndGetIssueForMutationExact,
which keeps the existing cross-rig prefix-routing and contributor
auto-routing fallbacks intact (tightened to exact matching too) so
cross-repo comment writes by full id are unaffected.
Every other caller of the touched shared functions (ResolvePartialID,
resolveAndGetIssueForMutation, resolveViaPrefixRoutingWithAccess,
resolveViaAutoRouting) keeps its exact current behavior — the new exact
variants are additive, and existing call sites were updated to pass an
explicit "false" for the new parameter rather than changing behavior.
Testing: go build/go vet pass across the whole module. The new pure-Go
guard test and a hand-rolled in-memory PartialIDResolverStore test both
run and pass without Docker or a live Dolt server, and the latter
reproduces the original collision (ResolvePartialID) before asserting
the fix (ResolvePartialIDExact) in the same test, so the fixture is
proven to exercise the real failure mode rather than trivially passing.
The Dolt-container-backed table tests (mirroring the existing
TestResolvePartialID_Wisp / TestResolvePartialID suites) could not be
run locally (no Docker in this environment) — they compile and skip
cleanly the same way the pre-existing suite does, and will run for real
in CI.
* fix(ga-wpdum): address steveyegge's PR #5393 review items b/c/d
Review (2026-08-07, posted as a PR comment, not a formal GitHub review —
hence reviewDecision stayed empty) asked for four things before merge; (a)
rebase onto #5369 was already done (2026-09-07, see PR history). This
addresses the rest:
(c) MAJOR — comment writes require an exact id, but a REAL abbreviated id
was refused with "no issue found matching %q", which is false: the issue
exists, only the abbreviation was rejected. ResolvePartialIDExact now
distinguishes the two failure modes via a new sentinel,
ErrAbbreviatedIDNotAllowed, wrapped only when the input would have resolved
via leading-prefix abbreviation. bd comment's RunE checks errors.Is against
it and returns a truthful, actionable message pointing at `bd show <id>`
instead of claiming the issue is missing. Docs (hash-ids.md) and CHANGELOG
updated with the read/write carve-out this creates.
(b) MAJOR — investigated whether the proxied-server comment path needed the
same exact-match treatment. It doesn't: resolveCommentTargetProxied resolves
via workapi.GetIssueOrWisp with the raw id, which bottoms out in
issueSQLRepositoryImpl.Get's plain "WHERE id = ?" — SQL exact equality, with
no abbreviation-matching layer anywhere in that call chain (unlike the
embedded path's utils.ResolvePartialID). Comment writes over the proxied
server were already exact-id-only before this PR. Per the review's own
fallback ("extend exact matching to that path, or document/test the gap
explicitly"), added a regression test locking this in rather than leaving it
implicit.
(d) Added CLI-level (cobra-dispatch, in-process rootCmd.Execute) tests for:
- "rm"/"delete" reserved-word rejection, the two words the #5369-inherited
tests don't cover (only "list"/"add" have hand-written cases).
- The new (c) abbreviation-refusal message end-to-end, including a
same-abbreviation sanity check against `bd show` to prove it's a real,
resolvable abbreviation and not a fixture accident.
Plus a Docker-free fake-store test in internal/utils pinning
ErrAbbreviatedIDNotAllowed's distinguishability from a genuine not-found.
Fixed in the same pass, same class of defect as (c): checkCommentIDNotReservedWord's
message claimed every reserved word is a "misplaced bd comments subcommand" —
true for "list"/"add", false for "rm"/"delete" (no such subcommand exists;
bd has "delete" as a top-level command and "rm" as an alias elsewhere, e.g.
"dep rm"). Message now says "reserved word" generically, true for all four.
Testing: go vet (plain and -tags=integration) clean on cmd/bd and
internal/utils. go test ./internal/utils/... passes including the new
ErrAbbreviatedIDNotAllowed test. go test ./cmd/bd/. (non-integration tag)
passes including both reserved-word cases. The new CLI-level and
proxied-server integration tests need a Dolt test container (Docker) this
environment doesn't have — same limitation the original commit's own
Dolt-backed tests already disclosed; they compile clean under
-tags=integration and skip cleanly the same way the pre-existing suite does.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ga-wpdum): address bee-ghosttrack's R1 review (M1 + the flagged MINOR)
R1 (aec6de4ad, REQUEST-CHANGES) found that CHANGELOG.md and hash-ids.md
claim `bd comments add` is guarded against abbreviated ids and reserved
words exactly like `bd comment`, but the code never extended the guard
to the plural form — `commentsAddCmd` had no Args validator and resolved
through the abbreviation-tolerant `resolveAndGetIssueForMutation`. Per
the reviewer's preferred fix (option ii), extend the guard instead of
softening the docs:
- Add `validateCommentsAddArgs` (mirrors `comment`'s `validateCommentArgs`
minus the singular/plural-confusion special cases) and wire it as
`commentsAddCmd.Args`, so a reserved-word id is refused before either
dispatch branch.
- Switch the embedded-path resolution from `resolveAndGetIssueForMutation`
to `resolveAndGetIssueForMutationExact`, with the same
`errors.Is(ErrAbbreviatedIDNotAllowed)` truthful-message mapping
`comment` already has. (The proxied path already resolved exactly —
it shares `addCommentProxied`/`resolveCommentTargetProxied` with
`comment` — so this closes the embedded-path gap only.)
- Update the one pre-existing test that asserted the old, now-removed
behavior (`PartialIDWithCommentsAdd` expected a genuine abbreviation to
succeed) to assert the refusal instead, and add a CLI-level regression
test mirroring `TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage`.
- Add `TestValidateCommentsAddArgs`, a pure Args-validator unit test
(no store/Docker needed) mirroring `TestValidateCommentArgs`.
Also treats the one MINOR the review flagged as an actual gap (not just
a suggestion): the wisp-branch abbrevOnly tracking in id_parser.go had no
test pinning it — P3 (making the wisp-branch abbrevOnly append a no-op)
went uncaught. Strengthened
TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident's "list"
assertion from a bare `err != nil` to `errors.Is(err,
ErrAbbreviatedIDNotAllowed)`, which is exactly the incident's own shape
in the wisp branch.
CI (PR Core / wrapper timing) is failing on this branch, but independently
confirmed pre-existing and unrelated: `ci-pr-core.sh` runs `go test -race
./...` with no `-timeout` override, so cmd/bd (a large package under
-race) hits Go's default 10-minute per-package ceiling; same-hour green
runs on other PRs measured 11-13.5 min total job time, already at the
edge, and the actively-running test at the deadline
(TestWhereCommand_ReadsPrefixFromEmbeddedStore) is unrelated to this
diff. R1 independently measured the same thing (541.6s/387.0s on other
green runs vs. 600.9s here). Needs a green re-run, not a code fix.
Verified locally (no Docker in this environment, so the two integration-
tagged CLI tests above compile-check clean via `go vet -tags=integration,
gms_pure_go` but run as SKIP rather than PASS; will run for real in CI):
- go build ./...; go vet ./cmd/bd/ ./internal/utils/: clean
- go vet -tags=integration,gms_pure_go ./cmd/bd/: clean
- gofmt -l on all 4 changed/added files: clean
- go test ./internal/utils/... -run ResolvePartialID: PASS
- go test ./cmd/bd/. -run 'TestValidateCommentsAddArgs|TestValidateCommentArgs|TestCheckCommentIDNotReservedWord': PASS
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ga-wpdum): address bee-ghosttrack's R2 review (dead-red fixture + cobra-dispatch wiring test)
R2 (a639234a0, CHANGES_REQUESTED): TestCLI_CommentsAddShortID/PartialIDWithCommentsAdd
was dead-red in its own setup — it only truncated the fixture hash to a
4-char abbreviation when len(hash) > 4, but fresh test DBs mint 3-char
hashes (min_hash_length unset), so shortID always equaled the full hash
and the t.Fatalf guard fired before any of the subtest's real assertions
ran. That meant mutation P-B (reverting comments.go's exact resolver back
to the abbreviation-tolerant one) went uncaught.
Fix: derive the abbreviation as a strict, one-character-shorter leading
prefix of the real hash (hash[:len(hash)-1]), the same derivation
comment_proxied_integration_test.go already uses — correct regardless of
fixture hash length, with a length>=2 guard instead of the old
always-true-in-practice one.
Also closes R2's recommended "NEW MINOR — the guard's wiring is
untested": comments_add_test.go drives validateCommentsAddArgs directly
(catches a gutted body, mutation P-C) but nothing exercised
commentsAddCmd's Args field through real cobra dispatch, so unwiring it
back to cobra.MinimumNArgs(1) left every test green (mutation P-D). Added
TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch, which runs
`bd comments add <reserved-word> ...` through actual rootCmd.Execute()
dispatch for all four reserved words and asserts the bystander issue
receives no comment.
Not touched, per R2: the carried-over m1 (cross-rig abbreviation error
message) — reviewer marked "Not a blocker" — and the CI race-default
timeout on cmd/bd, already diagnosed (R2 + prior PR comment) as
pre-existing infra flakiness needing a fresh run, not a code change.
Verified in this environment (no Docker/testcontainers available, same
disclosed limitation as prior rounds): gofmt clean; go vet -tags=integration
./cmd/bd/... clean (requires CGO_CPPFLAGS/CGO_LDFLAGS/PKG_CONFIG_PATH
pointed at the keg-only icu4c@78 install); go test -tags=integration
-run 'TestCLI_CommentsAddShortID|TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch'
./cmd/bd/ -v passes with all Dolt-backed subtests skipping cleanly
(Docker not available) rather than panicking — confirms both tests compile
and execute up to the container-availability skip. The actual fixture-hash
logic under test only runs where a Dolt container exists (CI); it has not
been exercised against a real container here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* chore(bazel): enumerate the PR's 4 new test files in BUILD.bazel (adopt-pr rebase gate)
Base added cmd/bd/BUILD.bazel and internal/utils/BUILD.bazel enumerates
go_test srcs explicitly, so PR #5393's four new test files were unlisted.
Output of 'make bazel-sync' (gazelle + go_srcs.py + mod tidy), verbatim and
idempotent. Measured: the unrepaired //internal/utils:utils_test binary lists
0 of the PR's 5 TestResolvePartialIDExact* tests while still building green
(a fake green); repaired it lists 5/5.
* fix(review): surface a routed-tier abbreviation refusal on comment writes
Review-loop fixup for PR #5393 (iteration 1). The review approved with no
required changes; these are the non-gating minor plus one of the two nits,
taken because the minor is a user-visible false message on this PR's own
headline contract.
[minor] Contract & Interface Fidelity. resolveAndGetIssueForMutationExact
passes exact=true to all three tiers, so the cross-rig and auto-routed tiers
can mint utils.ErrAbbreviatedIDNotAllowed too -- and both wrappers propagate it
unwrapped (routed.go:303-305) -- but each routed error was bound inside an `if`
statement and discarded, and `return nil, err` returned the LOCAL error. The
consumers' errors.Is (comment.go:158, comments.go:238) was therefore
structurally unable to observe a routed-tier refusal, so `bd comment hr-8wn
"text"` printed `no issue found matching "hr-8wn"` for an issue a routed rig
demonstrably holds -- the exact falsehood the sentinel's own doc condemns, at
the caller that doc names (internal/utils/id_parser.go:33). Both tiers' errors
are now captured and the first abbreviation refusal is returned in preference to
the local not-found. The wrong write was already refused on every tier; only
the message contract was unmet.
The new pin cmd/bd/comment_routed_exact_test.go drives the real seam (local
town store + routed rig + routes.jsonl, mirroring
TestCheckBeadGateCrossRigPrefixRoute) in both directions, because either
assertion alone passes for the wrong reason: an abbreviation of a routed issue
must select the ROUTED refusal, and an id absent everywhere must stay a plain
not-found. Proven non-vacuous by mutation -- dropping only the selection reds
direction 1 with `no issue found matching "gt-abcdefg"`, the original symptom
verbatim, while direction 2 still passes.
[nit] Test Evidence Quality. The proxied regression test asserted only
strings.Contains(stdout+stderr, id), which passes identically on the false and
the truthful message and so locked the local/proxied message asymmetry in where
the suite could not see it. It now asserts the whole message (verified
empirically: `Error: issue pa-2u not found`) and empty stdout, matching the
exact-message norm of the sibling missing-ID subtest. The asymmetry itself is
deliberate and stays: the proxied route resolves through one exact
`WHERE id = ?` and cannot distinguish an abbreviation of a real issue from an
absent id without adding back the abbreviation probing this PR exists to remove
from write paths.
[nit] Release Safety -- DECLINED, measured. The prescribed `### Changed` bullet
belongs at the top of the first `### Changed` block in `## [Unreleased]` (base
CHANGELOG.md:383), and main has since inserted its own bullet at exactly that
anchor (`@@ -384,0 +492,16`, the #6111 entry). Adding it would mint a second
CHANGELOG add/add conflict for the finalize base-refresh on top of the
`### Fixed` re-conflict already predicted by the rebase gate -- not worth it for
an optional nit whose own text says "No code change".
cmd/bd/BUILD.bazel gains one srcs row for the new test file (via make
bazel-sync, a no-op on a second run) so bazel.yml's "BUILD files in sync" gate
stays clean.
Validation: go build ./... rc 0; go vet ./cmd/bd/ ./internal/utils/ rc 0; gofmt
clean; git diff --check clean; cmd/bd selectors 11/11 PASS including base's own
TestMatchPrefixRoute (the GH#5048 longest-prefix union guard) and
TestResolveCloseTargets (the abbreviation-tolerant sibling path);
TestProxiedServerComment 3/3 under BEADS_TEST_PROXIED_SERVER=1.
* test(utils): pin #6215's sentinel guard to the shared resolver (#5393 base refresh)
Rebasing this PR onto current main (e7138e93af -> a1ac9f4dcb, 27 commits) hit
two conflicts. Both are recorded in .gc/reviews/<root>/base-refresh-repair.md;
this commit carries the one piece of the repair that is not simply a replayed
contributor hunk.
The substantive conflict was internal/utils/id_parser.go against ab88b20517
(#6215, "refuse a bare jq/JS sentinel ... as an issue ID", which itself says
Refs #5393). Both sides ADD at the same point -- the diff3 ancestor section is
empty -- so nothing base-owned is rewritten, and the only question is WHERE
#6215's guard lands now that this PR splits the resolver into ResolvePartialID
(abbreviation-tolerant) and ResolvePartialIDExact (exact-only) over a shared
resolvePartialID.
It belongs in the shared body. #6215 put it in ResolvePartialID only because
that was then the repository's single ID-resolution entry point ("One guard
covers the direct, embedded and proxied-server paths uniformly"); this PR adds
a second. Its changelog entry on main states the guarantee directly -- "bd
update null, bd comment null and every other command that resolves an ID now
fail before any lookup, because the guard sits in the shared resolver" -- and
bd comment is precisely what this PR routes through the exact-only path. The
relocation costs no patch delta: the guard re-anchors as unchanged context
after the PR's insertion, so the content-line diff of (old base..old head) vs
(new base..new head) is empty, and the PR's stat is 16 files +1212/-31 before
and after.
Nothing covered that choice, which is why this test exists. #6215's own
id_parser_sentinel_test.go exercises only ResolvePartialID, so the naive
textual resolution -- guard left in the exported wrapper -- keeps every one of
its assertions green while a sentinel reaching the exact path degrades into
`id is a valid abbreviation, but exact-match resolution is required here:
"null" (matches [hq-null3t0])`: it names an unrelated decoy issue and tells
the caller to use the full id, when in truth their selector matched nothing.
Mutation-proved in both directions: with the guard moved into the wrapper
alone, #6215's two tests still PASS and this test FAILs; with the guard deleted
outright, #6215's refusal test and this one both FAIL (so neither is vacuous).
The over-refusal arm mirrors #6215's accepted-inputs test through the exact
path, so hq-null3t0 and the bare hash null3t0 must still resolve.
No new file, so no BUILD.bazel srcs row is owed. 61 PASS / 0 FAIL / 0 SKIP for
-run 'Sentinel|ResolvePartialID' against a real Dolt container.
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>
* fix(utils): refuse a bare jq/JS sentinel as an issue ID
`jq -r` prints the literal string "null" when a selector misses, and JS
tooling prints "undefined". Both are a valid partial-ID shape, so
ResolvePartialID accepted them and resolved them through its leading-prefix
abbreviation branch: any issue whose hash began with the token became the
target, and the write reported success naming an issue the caller never
mentioned.
Reproduced on stock beads at a07794015, embedded Dolt, scratch workspace,
no orchestrator:
bd init --prefix bd
bd create --id bd-null3t0 "decoy: must not be touched"
bd update null --status closed
✓ Updated issue: bd-null3t0 — decoy: must not be touched (exit 0)
HasPrefix), so this needs a hash that begins with the token — the same case
The guard sits in ResolvePartialID rather than in a command because
internal/utils/id_parser.go is the only ID-resolution entry point in the
repository: 52 non-test call sites across 29 files, plus 2 through the
ResolvePartialIDs wrapper, and the four cmd/bd/*_proxied_server.go twins
resolve through the same function. One guard covers the direct, embedded and
proxied-server paths uniformly.
The riskiest thing this does is add a refusal to the resolver every command
shares. An ID that merely contains a token (bd-null, null3t0,
undefined-behavior) is unaffected, abbreviation matching is otherwise
unchanged, and the empty string already failed — it now says why.
Case folding is deliberate: NULL is what SQL-shaped tooling prints.
Whitespace is trimmed for the comparison only, never for resolution.
The tests use a nil store so the ordering is observable: reaching the
"storage is nil" error proves the guard did not fire. Mutation-tested — with
the guard reverted all eight refused inputs fail and the seven accepted
inputs still pass.
Fixes#6214
Refs #5393
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Cherub Kumar
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SDrKFyrfKTKM5J9yFbW7uA
* fix(utils): refuse none/nil too, and list the new test in the Bazel srcs
Maintainer review fixes for #6215, review iteration 1. Both lanes and the
scorecard returned approve with no required changes; this commit takes the two
actionable minors, both of which land inside the PR's own change.
Taken:
- Behavioral Correctness (minor). `bd update None --status closed` still reached
the leading-prefix abbreviation branch: strings.ToLower("None") is "none" and
every character passes looksLikePartialIDHash, so it could silently write to
whichever issue's hash begins "none" and exit 0. `nil` is the same class. That
is the identical silent-wrong-write harm this PR exists to prevent, and the
remedy lands in the switch the PR just added, so "none" and "nil" join the
same case arm and the refused-inputs table.
The error text is generalized with them: "none" is Python and "nil" is
Go/Ruby, so the previous jq/JS-only wording would have mis-described the two
new tokens.
- Change Impact / Blast Radius (minor). The PR adds two TestX functions that
`go list` selects for internal/utils but that Bazel's utils_test target could
not compile or run -- exactly what tools/bazel/equivalence.py reports as
`missing`. Gazelle's verdict, not a hand-guess: `make bazel-sync` produced
exactly `+ "id_parser_sentinel_test.go",` for internal/utils/BUILD.bazel. It
also rewrote 13 other BUILD.bazel files (pre-existing base drift), which is out
of scope here, so that output was reverted and only this PR's row re-applied at
gazelle's chosen slot. utils_test is 10 entries, sorted, no duplicates, all on
disk.
Note the review predicted the regen would also add `+ "//internal/debug",` to
this file's go_library deps "once rebased on main". It did not at this base,
because the import that needs it is not present here -- that dep is
base-owned drift and is already tracked separately.
Over-refusal is guarded, not assumed: the pre-existing accepted-inputs test
(nullos, null3t0) and the whole ResolvePartialID suite -- cross-prefix,
allowed-prefixes, wisp, title-false-positive -- all still pass.
Validation: gofmt clean, go build ./... and CGO_ENABLED=1 go vet ./internal/utils/
clean; 42 PASS / 0 FAIL / 0 SKIP over -run "Sentinel|ResolvePartialID". The new
rows are mutation-proved: dropping "none" from the case arm reds
TestResolvePartialIDRefusesSentinelTokens, and restoring returns rc=0.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Cherub Kumar <5449665+ckumar1@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* ci(bazel): auto-push `make bazel-sync` fixes to PR branches
bazel.yml's BUILD sync step now writes the BUILD.bazel / MODULE.bazel /
MODULE.bazel.lock part of its drift as the bazel-sync-patch artifact
(scripts/ci/bazel-sync-patch.sh) and still fails. The new bazel-autofix.yml
workflow_run job (on "Bazel" and "PR") applies it with
scripts/bazel-autofix-push.sh: a sync commit on same-repo PR branches, an
idempotent apply-recipe comment on fork PRs.
Same security model as docs-autofix: the write-permission side never checks
out or runs PR code, extracts only the two expected regular files, and
refuses any patch naming a path outside an anchored allowlist (no hidden or
`..` segments, nothing under third_party/) or carrying a mode change,
symlink, rename or binary hunk; `git apply --index` and a post-apply check
back that up. Reuses the DOCS_AUTOFIX_TOKEN secret for the push.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): add bazel_autofix_push_test.go to scripts_test
`make bazel-sync` output, produced by scripts/ci/bazel-sync-patch.sh and
applied with scripts/bazel-autofix-push.sh as an end-to-end exercise of the
new autofix path.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(ci): harden the bazel and docs autofix push scripts
Addresses the security review of the autofix pipeline, identically in
scripts/bazel-autofix-push.sh and scripts/docs-autofix-push.sh (the
security-critical functions are now shared verbatim):
- validate_patch refuses ANY "rename "/"copy " header (the legacy
"rename old/new" form slipped past and, on docs-autofix, pushed a
scripts.sh -> docs/cli-reference/x.md rename), checks every "index "
line whatever its ids, takes creations/deletions/renames from
`git apply --summary`, and reads names from `--numstat -z` (which
names only the NEW path of a rename; the old comment was wrong).
- docs-autofix gains the post-apply staged re-check and a --check mode.
- The patch is applied to an index in a bare clone (read-tree +
apply --cached + commit-tree): the PR tree never touches the disk.
All git calls run with core.hooksPath=/dev/null, GIT_LFS_SKIP_SMUDGE=1.
- Push is leased: --force-with-lease=refs/heads/$HEAD_BRANCH:$HEAD_SHA.
- The PR must target this repo, and the head branch must be neither
protected nor under a ruleset per the GitHub API (fail closed), on top
of the name list.
- Only a marker comment written by github-actions[bot] is ever edited.
- bazel-autofix only pushes files in packages the PR changed
(merge-base..head, computed from fetched refs), MODULE files only when
go.mod/go.sum/MODULE changed; base-branch drift is left alone and
listed, and a patch with nothing attributable gets a comment only.
Tests cover each reviewer attack for both scripts (--check and the full
flow against a local bare remote and fake gh), the staged check alone
with the validator disabled, spoofed comments, protection/ruleset/API
errors, the lease, main drift, and symlinked PR trees.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(ci): trigger bazel-autofix on Bazel only; share job-level concurrency
- bazel-autofix.yml triggers only on "Bazel": pr.yml never calls
bazel.yml, so "PR" runs never carry the artifact, and their completions
cancelled real fixes through the workflow-level group. The policy test
now requires the triggering workflow to run on pull_request and upload
the consumed artifact instead of asserting the false claim.
- Both autofix workflows use one job-level concurrency group per head
branch (autofix-<head repo>-<head branch>) without cancel-in-progress:
skipped runs take no part, and the two bots queue instead of racing.
- Base checkouts use persist-credentials: false; docs-autofix extracts
only cli-docs-freshness.patch, as a regular file, outside the workspace.
- Policy tests for the trigger, concurrency scope, checkout, and the
scripts' shared guards (rename/index checks, comment author, lease,
protection lookup, index-only apply, hook-free git).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(ci): tighten autofix attribution, circuit breaker and PR selection
Re-review follow-ups for the bazel and docs autofix push scripts:
- Root package: paths outside any Bazel package (docs/, .github/,
README.md, ...) no longer count as changing //:. Only root-level Go and
build inputs (*.go, *.s, *.c, *.h, *.bzl, go.mod, go.sum, BUILD.bazel,
MODULE.bazel*) make root BUILD.bazel drift the PR's, so main's root
drift is not pushed onto a docs-only PR.
- Circuit breaker: the head subject is read from the fetched commit (no
API), a failed read counts as non-convergent, and the check runs only
once the PR's own staged fix is non-empty. A bot head whose remaining
drift is main's now gets the "files this PR did not change" comment
instead of a wrong "did not converge" one. Same in docs-autofix.
- PR selection: several open PRs can share one head branch. bazel picks
the one whose number matches the artifact metadata (among PRs already
matching head repo/branch/base repo; head sha still verified); without
a unique match both scripts skip instead of taking .[0].
- The privileged clone fetches only the head (and, for bazel, base)
branch into an init'ed bare partial repo instead of cloning every
branch.
- docs-autofix job gets timeout-minutes: 10 (it shares a non-cancelling
concurrency group with bazel-autofix).
Tests: docs-only/README/workflow/Makefile PRs with root drift get no push,
a root Go change gets root BUILD.bazel; breaker cases (bot head with own
vs main drift, unreadable subject) for both scripts; PR selection by
metadata and ambiguity; HEAD_SHA 40-hex guard; staged-check mode arm; a
--summary-only validator copy; both workflows' download steps run as
written against a fake gh (run-scoped artifact listing, only the named
files extracted, symlinked entries refused); timeout asserted for both
jobs.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(ci): bazel-autofix requires bash 4; skip its tests on macOS bash 3.2
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(ci): skip every autofix script test on bash < 4
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): sync internal/utils BUILD with main
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>
* fix(lint): suppress two darwin-only gosec findings and cross-lint the darwin build in CI
scripts/ci/pr-lint.sh lints natively on the ubuntu runner plus one
GOOS=windows CGO_ENABLED=0 cross-lint, so files behind //go:build darwin
(and the !windows && !linux fallbacks) were never linted in CI. Linting the
darwin build reports two gosec findings that are clean on linux:
- internal/config/permissions_open_nonlinux.go: G304 on os.Open(path). The
file comment already explains why it is safe (fixBeadsDirPermissions
re-checks descriptor identity before chmod); it just had no directive.
- internal/utils/path_case_darwin.go: G103 on unsafe.Pointer. A directive
existed but sat on the first line of a multi-line unix.Syscall call,
while gosec reports the argument line four lines down, so it never
covered the finding. It now sits on its own line above the statement,
the placement cmd/bd/nocow_linux.go already uses.
Add a GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 cross-lint block to
pr-lint.sh mirroring the windows block (same flags, same lane scoping,
skipped when the native target already matches), and update the three
places that described the wrapper as two passes: engdocs/LINTING.md,
engdocs/CI_CLEANUP_PLAN.md and the comment in main.yml.
The darwin pass is compile-only on the Linux runner: no macOS runner, no
change to the pr-lint platform column. Like the windows pass it is
CGO_ENABLED=0, so darwin+cgo code stays outside its reach.
* docs(linting): bump the Last reviewed marker alongside the pr-lint change
* feat(ids): say when a partial ID resolved to something else
ResolvePartialID tries an exact match first and only then falls back to
leading-prefix abbreviation (a3f8 -> a3f8e9). Ambiguity is already handled
well: two or more candidates return ErrAmbiguousID naming all of them. But a
*sole* abbreviation match was returned silently, so a caller could act on an
issue it never named with nothing to indicate the substitution.
The case that motivates it: a hierarchical child is a valid leading-prefix
match for its own parent's ID, because "." is a legal ID character and the
prefix test has no boundary. So once a parent ID is vacated — renamed away, or
deleted — `bd show <parent-id>` returns the child, exit 0, no signal. With
exactly one descendant it is silent; with two or more the existing ambiguity
error catches it. The silent case is the dangerous one.
Rather than narrow resolution (e.g. requiring a boundary so a child stops
abbreviating its parent), which changes semantics and risks breaking
legitimate abbreviations, this announces the substitution and leaves the
documented abbreviation UX alone.
Emitted from the resolver, not from individual commands: ResolvePartialID has
64 non-test call sites, so a per-command notice would be applied
inconsistently. One emission point covers all of them, and it sits at the only
return that hands back an issue the caller did not name.
stderr, never stdout, so --json payloads and piped output are byte-for-byte
unchanged. Gated on --quiet and BD_NO_PARTIAL_ID_NOTICE, following the
BD_NO_DEP_TYPE_WARNING precedent in cmd/bd/dep.go. Deliberately not gated on
stderr being a terminal, which is where it departs from that precedent: the
callers most exposed to acting on the wrong issue are scripts, hooks and
agents, and those are exactly the non-TTY ones.
Tests: the gate matrix (quiet, env opt-out, identical/empty resolution), the
message text, and end-to-end resolution over a small in-package fake store —
the existing resolver tests need a live Dolt server and self-skip without one,
so they cannot pin this in CI. Verified the end-to-end test fails without the
emission.
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(changelog): link the partial-ID notice entry to its PR
Matches the surrounding entries, which each cite the PR or issue they came
from. No code change.
Co-Authored-By: Claude <noreply@anthropic.com>
* test(ids): cover the second silent return; disclose the notice's breadth
Review follow-up on #6302.
MAJOR — CHANGELOG understated the scope. The notice fires on every
leading-prefix abbreviation, not only the vacated-parent shape, so the ordinary
documented a3f8 -> bd-a3f8e9 path emits a line too, once per resolved argument.
The entry now says so, and says why the breadth is deliberate: a .-boundary
rule would fix parent/child and leave bd-x.1 -> bd-x.11 just as silent.
MINOR — an emission planted at the in-loop exact-hash return survived the
suite. The suggested repro (prefix-less a3f8e9 -> bd-a3f8e9) does not reach
that return: resolution has TWO fast paths, one on the raw input and one on the
prefix-normalized input, and the normalized one catches that case first. The
in-loop return is reached only CROSS-PREFIX, where the issue's real prefix is
an allowed one other than the configured default, so both fast paths miss and
the search loop matches on hash alone.
TestResolvePartialIDSilentOnCrossPrefixExactHashMatch covers it (configured
prefix bd, allowed hq, store holds hq-a3f8e9, input a3f8e9) and was verified to
fail with that mutant planted and pass without it. The prefix-less case is kept
as its own test, since it pins the normalized fast path staying silent.
TestResolvePartialIDNotifiesOnOrdinaryAbbreviation pins the breadth the
CHANGELOG now discloses.
Also: captureStderr restores os.Stderr from a defer so a panicking test cannot
swallow later tests' output, and closes the read end.
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
* test(testutil): local dolt sql-server backend behind the Dolt test server API
Add a second backend to internal/testutil behind the unchanged container
API (EnsureDoltContainerForTestMain, RequireDoltContainer,
StartIsolatedDoltContainer[Handle], NewContainerProvider,
RestartSharedDoltContainer, DoltContainerCrashed, IsolatedDoltContainer
Stop/Start/CurrentPort/Exec): the test process spawns `dolt sql-server`
from the pinned dolt CLI instead of a dolthub/dolt-sql-server container.
- BEADS_TEST_DOLT_SERVER=local|container selects it; unset keeps plain
`go test` on the container (no behavior change) and makes `bazel test`
use the local backend. Other values fail instead of guessing.
- The CLI (BEADS_TEST_DOLT_BINARY, else PATH) must be the image's version.
- Provisioned like testcontainers' dolt module: root@% (DOLT_ROOT_HOST=%),
database beads_test, user test/test. Clean env, TZ=UTC, GOMAXPROCS=4,
own dolt global config with metrics and the version check disabled.
- Loopback port picked here (dolt rejects -P 0), never 3307, retried when
another process wins the port; readiness requires the server's own
"Server ready" line plus a bounded ping, so a foreign listener on a
contested port cannot pass for it.
- State lives under the TMPDIR captured at package init, outside every
PinSuiteTempRoot root, so suite leak sweeps never see it. The server
stays in the test's process group (bazel's group kill reaps it) with
Pdeathsig on Linux.
- BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 now also makes every TestMain that
only warned about an unavailable server exit 1
(DoltUnavailableForTestMain), plus the shared proxied harness.
- dolt_benchmark_purge_test finds .dolt_dropped_databases relative to
Exec's working directory (the data dir in both backends).
- TestDoltServerFingerprint checks each available backend against one
checked-in fingerprint (users, grants, databases, server variables);
local-backend tests cover the bind-race retry, 3307, crash detection,
Stop/Start, Exec cwd, state outside the suite root, and teardown.
- Bazel: the requires-docker variants pin BEADS_TEST_DOLT_SERVER=container
so the docker lane stays the container A/B control; the test wrapper's
dolt global config disables metrics and the version check.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(testutil): select the local Dolt test server only when asked for
Under Bazel an unset BEADS_TEST_DOLT_SERVER used to mean the local
backend, so every non-ci `bazel test` started servers for Dolt suites no
lane runs with one (//internal/storage/dolt:dolt_test went from a 16 s
skip to a timeout). Unset now means container everywhere: in a Bazel
action without docker that is the pre-existing warn+skip, and only a
target's env or --test_env=BEADS_TEST_DOLT_SERVER=local starts local
servers. Plain `go test` is unchanged.
The docker variants keep their container pin: a rule env beats
--test_env, so a local-backend invocation cannot flip the docker lane.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(testutil): harden the local Dolt test server's host footprint
- DOLT_DISABLE_EVENT_FLUSH=1 for every dolt the backend runs (and in the
Bazel test wrapper): the metrics/versioncheck keys stop network calls
but not the detached `dolt send-metrics` child each command forks on
exit, which re-created the version probe's removed HOME (one leaked
bdt-doltver-* per test process) and raced terminate's RemoveAll.
- Every bdt-dolt-*/bdt-doltver-* root records its owner PID, and the
first use of the backend in a process removes this user's roots whose
owner is dead (the SweepDeadSuiteRoots rule; a copy, since doltserver's
tests import testutil). A panicking, timed-out or killed test binary,
or a package whose TestMain never terminates the singleton, no longer
leaks a 40-100 MB state dir per run.
- secure_file_priv is the state root's sfp/ directory, set through a
per-launch --config file (dolt ignores other flags with --config): a
local server runs as the test user on the host with a passwordless
root@%, so LOAD_FILE / INTO OUTFILE must not reach the user's files.
The fingerprint treats that path as the container's "".
- Fingerprint: character_set_server, collation_server,
max_allowed_packet, transaction_isolation, lower_case_table_names,
lower_case_file_system (compared on Linux only: APFS reports ON),
wait_timeout, innodb_lock_wait_timeout.
- The local backend's own tests skip off Linux (no Pdeathsig, so a
killed test binary would orphan servers on the macOS runners) unless
BEADS_TEST_DOLT_SERVER=local asks for them.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci: compare the container and local Dolt test servers in the domain+uow job
TestDoltServerFingerprint's container half never ran in CI: only the
test-domain-uow job has both the pulled image and the pinned dolt CLI,
and it never ran ./internal/testutil. Run the fingerprint there (with
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 so the container half cannot skip)
so an image bump that drifts the container side fails in the PR.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): add side-by-side Bazel scaffold (module + gazelle)
Add a Bzlmod Bazel build alongside the Go toolchain. `go build` and
`go test` are unchanged; nothing in CI invokes Bazel yet.
- MODULE.bazel: rules_go 0.63.0, gazelle 0.53.0, Go SDK 1.26.7 (matches
the go.mod toolchain directive), go_deps from go.mod.
- ICU policy (engdocs/ICU-POLICY.md): a go-mysql-server gazelle_override
selects the pure-Go regex backend and excludes regex_cgo.go, and
.bazelrc builds with --@rules_go//go/config:tags=gms_pure_go, so no
target depends on go-icu-regex or links libicu.
- third_party/patches: three module_override patches for dolt deps that
ship WORKSPACE-era BUILD files, adapted from the gascity project.
- .bazelrc: prcore/ci test configs (inert for now; they match pr-core's
test selection, not yet its environment isolation) and a generic
remote-exec config with a bounded remote timeout. Executor endpoints and
TLS credentials come only from a gitignored .bazelrc.local/user.bazelrc
or a CI rc outside the workspace.
- .bazelversion pins Bazel 9.2.0; .bazelignore skips separate modules,
non-Go trees, nested agent worktrees (.claude, .worktrees) and local
data/output dirs (.beads, .dolt, dist, .runtime, tmp), so a primary
checkout neither builds nor gazelle-rewrites nested worktree copies.
- Gazelle-generated BUILD.bazel files for every Go package.
- Makefile: `make bazel-sync` (gazelle + bazel mod tidy).
- .gitignore: bazel-* output symlinks and machine-local rc files.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): policy tests for the Bazel configuration
Add scripts/bazel_policy_test.go, plain Go tests that run under both
`go test ./scripts` and `bazel test //scripts:scripts_test`:
- MODULE.bazel go_sdk.download version equals the go.mod toolchain.
- ICU policy: .bazelrc sets gms_pure_go for build, the go-mysql-server
gazelle_override excludes regex_cgo.go, and the root BUILD.bazel
carries `# gazelle:build_tags gms_pure_go`.
- .bazelversion pins an exact Bazel release.
- .bazelrc.local and user.bazelrc are gitignored (parsed from .gitignore
and cross-checked with git check-ignore when in a checkout).
- No remote-execution endpoints or credentials in committed bazelrc-like
files, Markdown docs or .github/**: remote/BES/TLS flags
(--remote_executor, --remote_cache, --bes_backend, --remote_header,
--tls_client_certificate, ...) with a literal value, with or without a
URL scheme, and non-loopback gRPC URLs in rc/.github files. Placeholders,
$VARIABLES, and loopback are allowed; Markdown gRPC URLs (OTel exporter
docs) are not flagged. Skipped outside a git checkout, e.g. in the Bazel
sandbox.
Each check is a pure function also exercised against fixtures that break
the invariant. The files the tests read are declared as data via
//:bazel_policy_files so they resolve from runfiles under Bazel.
scripts/check-build-tags.sh now treats Bazel invocations as governed by
.bazelrc: the shell command segment that invokes Bazel (split on &&, ||,
;, |, $( and backticks) is exempt from the per-line `go` tag check, while
a bare `go` in another segment of the same line is still flagged. When
any scanned file invokes Bazel (or .bazelrc exists) .bazelrc must set
--@rules_go//go/config:tags=gms_pure_go for build.
scripts/check_build_tags_test.go covers both in a temp repository.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(scripts): split bazel lines in pure bash so check-build-tags works with BSD sed
BSD sed (macOS) does not expand \n in s/// replacements, so the segment
split never happened and the Bazel-exemption tests failed on macos-latest.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(scripts): skip check-build-tags tests when bash lacks mapfile
macOS runners use /bin/bash 3.2, which has no mapfile; check-build-tags.sh
has always required bash >= 4, so the new tests are skipped there.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Reader is Lifecycle's read counterpart, built as its mirror image: a role in
the leaf `issueops` package, reached through a capability accessor on the
storage seam, implemented at the same six sites. `Storage` gains
`IssueReader() (issueops.Reader, error)` beside `IssueLifecycle()`, and the
governing rule holds — a new capability got a new role and a new accessor,
not four more methods on an existing one.
SUBSUME, NOT COMPOSE. Reader takes the whole high-level request and performs
filter and default construction INTERNALLY, supplying its own ConfigSource
from the store or unit of work it already holds. Under compose both front
doors would each build a ConfigSource, load config, call a builder and execute
— two callers again, which is the topology that shipped a bare IssueFilter to
a viewer and silently served in_progress rows as "ready". Under subsume the
ritual is not callable from a front door: handlers and RunE bodies can only
say rd.List(ctx, req), so the failure mode is unwritable rather than merely
discouraged.
The three read endpoints are implemented against the frozen OpenAPI v0
document and consume the accessor; the 501 stubs and their self-deleting
exemption list are gone. `bd show --json` reaches the same role through the
same accessor, resolving the canonical id first so fuzzy and cross-repo
lookup stay CLI-local.
The workapi builders are re-typed onto the leaf request types, so there is no
second params struct to drift; both recorded goldens replay byte-identical,
which is the proof the re-typing changed nothing.
Load-bearing details:
- `sort` is forwarded EXPLICITLY as priority when absent. The storage layer
reads an empty policy as hybrid, which demotes older high-priority work and
therefore changes the item SET once a limit truncates — while the document
still reads correctly. Pinned by a handler test on the recorded filter and
by the parity oracle's order assertion.
- The parity oracle compares FULL ITEM JSON, not id sets. An id-set oracle
passes while ready ships a bare Issue against the CLI's IssueWithCounts.
- internal/workapi no longer imports internal/storage/uow; it names the slice
of a unit of work it reads through, so the uow provider can implement the
role without closing an import cycle.
- internal/utils' cgo store test moves to an external test package for the
same reason, with its two unexported-symbol cases split out.
Verified: issueops is still a leaf (internal/types + stdlib only); the
protocol corpus is unchanged structurally and behaviourally under
BEADS_PROTOCOL_REQUIRE_DOLT=1; a real `bd serve` answers all six operations
against a real workspace with CLI and HTTP JSON identical field for field.
- fix CI-red assertion in ready_proxied_integration_test.go (stale
gated-empty-case message)
- CreateIssue now persists issue.Labels through the proxied port
- ensureSubgraphCustomTypes now runs for every cloneSubgraphInto caller,
not just the legacy cloneSubgraph wrapper
- uowMolWriter.DeleteIssue no longer cascades (matches embedded
Transaction.DeleteIssue's single-row semantics)
- mol burn now commits each wisp batch and each persistent molecule in
its own uow.RunTxResult transaction instead of accumulating results
across a single retryable RunTx closure
- add domain SearchIssueIDs end-to-end and route utils.ResolvePartialID
through a narrow PartialIDResolverStore interface; delete the
hand-rolled resolveMolID in favor of the shared resolver everywhere
- wisp gc / wisp gc --closed now emit the same delete-result JSON/text
shape as embedded's deleteBatch
- GetMoleculeProgress/GetMoleculeLastActivity now compute from direct
children via GetDependentsWithMetadata, matching the embedded SQL
semantics (direct children only, real in-progress counts, last-writer
wins) instead of diverging via full-subgraph recursion
- bd ready --gated (proxied) now reuses renderGatedReadyMolecules
instead of an inline renderer that duplicated logic and swallowed
outputJSON errors
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(history): resolve partial/short issue IDs in bd history (#4868)
* fix(history): finish partial-ID resolution — compile against main's runHistory, surface ambiguity, document proxied gap
Rebase the contributor's resolution onto main's history seam, add
utils.ErrAmbiguousID (wrapped %w) so ambiguous prefixes report candidates
instead of "No history found", keep the not-found exit-0 contract
(#3502), and make the proxied-mode skip explicit.
Addresses the 2026-07-23 review on gastownhall/beads#4910.
Agent-Signature: claude-sonnet-5-medium on behalf of maphew
* test(history): assert both candidate IDs in ambiguous-prefix errors
Reviewer finding: a generic ambiguity error without the candidate list
still passed. Assert hi-zzzaaa1 and hi-zzzaaa2 appear in plain stderr and
in the JSON error body (which HandleErrorRespectJSON writes to stdout —
a second re-review round caught the test reading the wrong stream).
Agent-Signature: codex-gpt-5.6-terra-medium on behalf of maphew
Agent-Signature: claude-fable-5-high on behalf of maphew
---------
Co-authored-by: matt wilkie <maphew@gmail.com>
* fix: reject substring matches in ID resolution, require exact hash match only
Previously, bd close/show would silently fuzzy-match a nonexistent ID
to an unrelated issue when the nonexistent ID was a substring of an
existing issue's hash. For example, 'bd close hq-kt8' (nonexistent) would
close 'hq-wisp-j0kt8' because 'kt8' is a substring of 'j0kt8'.
This removes the substring matching fallback from ResolvePartialID(),
keeping only exact prefix + exact hash matching. A partial ID must match
the full issue hash exactly (after prefix handling), not just be a
substring of it.
Fixes GH#4234.
Test case added: substring-match queries now correctly error with
'no issue found' instead of silently matching an unrelated issue.
* fix(resolve): reject interior-substring ID matches, keep leading-prefix resolution
PR gastownhall/beads#4939 fixed the GH#4234 interior-substring hazard
(e.g. "kt8" matching inside "j0kt8") by deleting the strings.Contains
substring checks outright. That regressed the documented leading-prefix
partial-ID UX ("a3f8" -> "a3f8e9...") for every id-resolving command, and
broke TestResolvePartialID_Wisp's bare-hash "partial hash" subtest, per
the 2026-07-23 maintainer review on gastownhall/beads#4939.
Restore both call sites with narrower matching instead of dropping them:
- Main loop: strings.HasPrefix(issueHash, hashPart) instead of Contains.
Keeps leading-prefix resolution live (and with it the sort/ambiguity/
exactMatch machinery the blanket deletion left dead) while rejecting
interior substrings.
- Wisp fallback: strip the literal "wisp-" infix from the extracted hash
before comparing, since wisp IDs are shaped "<prefix>-wisp-<hash>" and
a naive Contains->HasPrefix swap would not match the wisp's bare hash.
Adds a leading-prefix-still-resolves test and a wisp prefix-resolution
test alongside the PR's existing GH#4234 substring-rejection tests.
Agent-Signature: claude-sonnet-5-medium on behalf of maphew
---------
Co-authored-by: matt wilkie <maphew@gmail.com>
TestCanonicalizePath_DoesNotScanAncestorDirectories asserted an absolute
1ms/call budget, which flaked under the suite's own -p 4 -parallel 4 load
(461ms for 200 calls against a 200ms budget) even though the fast path was
working. Compare the two implementations against each other instead: both
pay the same scheduling tax, so the ratio is stable, and the real gap at
this fan-out is ~1000x (19us vs 190ms per call) against a 4x floor.
Also rate the walk over 10 iterations rather than 200 — measuring it 200
times cost the test 99s on its own.
CanonicalizePath sits on the hot path of FindBeadsDir, which every audit
Append and every store open calls. On darwin it walked the path
component-by-component doing an os.ReadDir of EVERY ancestor directory to
recover the authored case. That is O(entries) per ancestor, per call: on a
fleet machine whose $TMPDIR held ~97k leftover test directories one call
cost ~640ms, so internal/audit's 8000-append concurrency test needed ~85
minutes and looked like a deadlock, and internal/storage/embeddeddolt and
cmd/bd blew their package timeouts the same way.
Ask the kernel instead: darwin's F_GETPATH fcntl returns the vnode's true
(authored-case, symlink- and firmlink-resolved) path in one syscall, whose
cost does not depend on directory fan-out. The portable component walk is
kept as the fallback for any error other than a genuine not-exist/ENOTDIR
verdict, and for non-darwin builds.
The dolt events.sendingThread and binlogreplication goroutines named in the
report are red herrings: both park on 'chan receive' when idle, which is
what a goroutine dump at timeout shows, not what caused the timeout.
go test ./internal/audit/... 10m timeout -> ok 1.2s
go test ./internal/storage/embeddeddolt/... 180s timeout -> ok 129.7s
* feat(storage): be-c5p AD-01 isProductionPort + DB-name firewall
Generalize the BEADS_TEST_MODE production-port guard so deployments
on non-3307 ports (BEADS_PRODUCTION_PORT env, BeadsDir/dolt-server.port
file) are also caught, and add a defense-in-depth database-name
firewall that refuses test-named DBs on any server unless the operator
opts into the dedicated test-server lane via BEADS_TEST_SERVER=1.
Both defenses honor BEADS_TEST_SERVER=1 as the single opt-in for
test-server connections, so each test harness flips one env var rather
than each layer reasoning about test/prod independently. Adds benchdb_
to testDatabasePrefixes (per-bench scratch DBs from cmd/bd/dolt.go)
and updates the doc-block to call out the two sibling prefix lists
that need to converge under be-avn.
Test harnesses across cmd/bd, internal/storage/dolt, internal/molecules,
internal/tracker, internal/utils, doctor, doctor/fix, protocol,
regression, and the root suite now set BEADS_TEST_SERVER=1 alongside
BEADS_TEST_MODE=1 in TestMain. The cross-rig integration test that
filters BEADS_* env on subprocess Cmd.Env adds it back explicitly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: release gate PASS for be-c5p-firewall (be-m1u/47dcc380)
* fix(test): adapt store_unit_test.go for BEADS_DOLT_SERVER_PORT (rebase compat)
Tests that exercise applyConfigDefaults now clear BEADS_DOLT_SERVER_PORT (added
to main after this branch was cut) so the legacy BEADS_DOLT_PORT path runs as
intended. Without this, a GC-city environment with BEADS_DOLT_SERVER_PORT set
causes the tests to resolve an unexpected port.
* fix(dolt): stop BEADS_TEST_SERVER=1 from suppressing DefaultSQLPort detection
Restructure productionPortReasons so Rule 1 (cfg.ServerPort ==
DefaultSQLPort) is evaluated unconditionally; BEADS_TEST_SERVER=1 now only
suppresses the BEADS_PRODUCTION_PORT and dolt-server.port heuristics (Rules
2 and 3). isProductionPort loses its independent whole-function bypass and
becomes a thin wrapper. Update doc comments on both functions and the
buildTestModeProductionPortPanic fix list (which no longer lists
BEADS_TEST_SERVER=1 as a fix when port 3307 is the matched reason) to match.
Add TestApplyConfigDefaults_TestModeBlocksProdPort_EvenWithTestServerOptIn
asserting port 3307 is still refused with the opt-in set.
Also: drop a redundant explicit db.Close() in openServerConnection's
firewall-refusal path (already covered by the connReady defer), and fix two
comments that referenced a non-existent uniqueBenchDBName, pointing them at
the real generator (cmd/bd/template_test.go newTemplateBenchmarkStore) with
the correct benchdb_ name format.
Agent-Signature: claude-sonnet-medium on behalf of matt wilkie
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
Roll back the direct adapters, dialect layers, credential handling, dependencies, CI services, and conformance profiles for general-purpose server databases. That support adds operational and testing complexity at odds with our goal of keeping Beads as simple as possible and consuming as few resources as possible.
Keep the Storage and DoltStorage interfaces unchanged. Embedded Dolt, Dolt server, and SQLite remain supported; the MySQL wire driver remains because Dolt server uses it.
Retain legacy metadata identifiers and hidden init flags only as compatibility tombstones. Removed, unknown, or corrupt backend metadata now fails safely across CLI, SDK, bootstrap, doctor, factories, and Dolt administration before storage is opened or modified, with guidance to export using a supporting build and reinitialize via bd help init-safety.
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Test User
Rebase of PR #4601 (feat/choose-your-own-backend) onto current origin/main,
squashed to a single commit because the original 73-commit history built and then
removed the uowStore derisk spike incrementally, which does not replay cleanly
over the 125 commits main has since advanced (notably #4679, the ready-work
counts fix, which merged to main and is now inherited rather than re-applied).
The full pre-rebase history remains on the original branch tip for reference.
Contents (multi-backend feature + the six review follow-ups):
- bd init --backend=postgres|mysql|sqlite provisioning behind the Dolt-parity
seam; the three SQL backends share *sqlkit.Store over pluggable dialects and
carry a generated typed-unsupported shell for the non-core surface.
- Passwords in init DSNs are redacted before persisting to metadata.json (driver
parser + re-parse verification), with a negative-test matrix proving no secret
survives (pgdialect + mysql).
- The uowStore derisk spike and its report artifacts are removed; the shell
generator now lives in internal/storage/unsupportedgen (neutral name).
- Compile-time guard `var _ storage.DoltStorage = (*Store)(nil)` on each backend
plus a regen-idempotence test keep the generated skip lists honest.
- sqlkit exposes CountReadyWork so every SQL backend satisfies
storage.ReadyWorkCounter and inherits the shared page-pushed ready-counts path.
- Commercial/product names scrubbed from the feature's own code for vendor
neutrality.
Rebase reconciliations: adopted main's metadata-load hardening in the store
factories alongside the backend dispatch; combined the config interface
(GetMetadata + ReconcileVersion) and the conformance registrations (ReadyCounts +
Claim/lease); took main's versions of the shared-infra concurrency (uow
doltserver_tx) and delete-cascade (domain/issue_delete) evolutions; implemented
the interface's new UnclaimIssue on sqlkit (delegating to issueops) and added it
to the skip lists.
Verified: go build (cgo + CGO_ENABLED=0) and go vet clean; unit tests
(sqlbuild/issueops/pgdialect/mysql/unsupportedgen) and the SQLite conformance
suite green (RunAll, incl. ReadyCounts equivalence and Claim/lease on the real
sqlkit backend).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Preserve John Zook's ResolvePartialID narrow-projection optimization. The shared searchProjection core keeps SearchIssues and SearchIssueIDs aligned while avoiding full issue hydration for substring fallback; parity tests and benchmarks cover the main store path. Non-blocking tx/sql-server coverage gaps are recorded in the PR thread.
Issue IDs like bd-E.10 now sort after bd-E.9 instead of before bd-E.2.
Adds NaturalCompareIDs to internal/utils and replaces string comparison
in list, graph, swarm, todo, and tree display code.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* ci: install dolt binary on Linux and macOS test runners
Install dolt via the official install.sh on Linux and via Homebrew on
macOS so the main test job can exercise the ~24 test gates that
previously silently skipped on every PR when dolt was absent from PATH.
Matches the installation pattern already used by nightly.yml.
Docker-testcontainer gates (testDoltServerPort == 0 skips) remain
skipped — a known GitHub Actions hang documented in
scripts/repro-dolt-hang/INCIDENT-REPORT.md and nightly.yml:37-41
prevents enabling testcontainers here.
* test: require dolt binary under GITHUB_ACTIONS
Add testutil.RequireDoltBinary: skips when the dolt CLI is absent
locally but fails the test under GITHUB_ACTIONS. Replace bare
exec.LookPath("dolt") skip-gates with the helper so ~24 tests that
previously fell through silently in CI now run — and hard-fail if
the CI workflow ever drops the dolt install step.
tests/regression/regression_test.go uses an inline variant because
its gate lives in TestMain, and internal/remotecache/cache_test.go
duplicates the helper inline to avoid an import cycle
(testutil -> doltutil -> remotecache).
Remove all BEADS_NO_DAEMON env var handling from test files (dead code
since daemon removal in v0.50.0), delete stopRepoDaemon() and daemon
file guards from test setup, remove no-daemon config key from tests,
and update daemon→server wording in docs and comments.
37 files changed, -193 lines net.
Co-Authored-By: davetashner <davetashner@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Make issue ID resolution config-aware by using issue_prefix and
allowed_prefixes as ground truth for prefix detection, instead of
relying solely on heuristics.
Changes:
- Add ExtractIssuePrefixKnown() in issue_id.go: deterministic prefix
extraction that checks known prefixes (longest-first) before falling
back to the existing heuristic ExtractIssuePrefix()
- Add hasKnownPrefix() in id_parser.go: checks if input starts with
any known/allowed prefix
- Modify ResolvePartialID() to read allowed_prefixes from config and
use config-aware detection in both normalization (preventing
accidental prefix prepending) and hash extraction (correct prefix
boundary for multi-hyphen prefixes)
- Do NOT change looksLikePrefixedID() or ExtractIssuePrefix() —
existing heuristic behavior is preserved as fallback
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Migrate 12 TestMain files to use EnsureDoltContainerForTestMain/TerminateDoltContainer
instead of the removed StartTestDoltServer/TestDoltServer API.
Replace testServer.IsCrashed()/CrashError() crash detection with standalone
testutil.DoltContainerCrashed()/DoltContainerCrashError() in 6 test files.
(bd-m7sy)
bd unconditionally ran CREATE DATABASE IF NOT EXISTS on every connection.
When connecting to the wrong server (auto-started from .beads/dolt/ or
Homebrew default), this created an empty shadow database hiding real data.
Changes:
- Add CreateIfMissing field to Config — only bd init sets it true
- SHOW DATABASES LIKE check before CREATE (with underscore escaping)
- Network error handling for SHOW DATABASES failure
- Suppress auto-start when metadata.json has explicit dolt_server_port
- Fix backup git push across .beads/redirect (findGitRoot)
- Fix macOS CanonicalizePath case resolution (walk dirs, not realpath)
- Add CreateIfMissing to all migration and create paths
- 10 regression tests covering guard, auto-start, ReadOnly, underscore
- CHANGELOG and TROUBLESHOOTING docs
Authored by: Aaron Lippold<lippold@gmail.com>
Add TestMain to internal/utils/ that starts an isolated test Dolt server
on a dynamic port, preventing test issues (offlinebrew-, aap-, cr-,
hq-abc12, bd-wisp-t3st) from leaking into the production database on
port 3307.
Changes:
- Add internal/utils/testmain_test.go with isolated test server setup
- Update newTestStore to use testServerPort and unique testdb_ databases
- Register utils-pkg-test-* in orphaned temp dir cleanup list
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/polecats/jasper
Rig: beads
Role: polecats
Two bugs fixed:
1. wispPrefix() generated bd-wisp-wisp-<hash> because IDPrefix='wisp' was
appended via configPrefix+"-"+IDPrefix, then "-wisp" was unconditionally
appended again. Now IDPrefix provides the suffix directly.
2. ResolvePartialID() only searched issues table via SearchIssues; the
DoltStore merges wisps but transaction-level SearchIssues does not.
Added explicit ephemeral fallback search to ensure wisps are always
resolvable by partial ID.
Closes: beads-yzh
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/polecats/obsidian
Rig: beads
Role: polecats
1. FORMATTING: gofmt 14 files.
2. LINT:
- Delete dead code cmd/bd/bootstrap.go (unused bootstrapEmbeddedDolt)
- Prefix unused 'actor' param in wisps.go updateWisp with _
- Prefix unused 'ctx' param in telemetry.go buildTraceProvider with _
3. TESTS: Add skipIfNoDolt to test helpers that call dolt.New() without
a running test server. In CI (no dolt installed), these tests now skip
instead of failing with "server unreachable at 127.0.0.1:3307".
Delete TestOpenFromConfig_Embedded and TestOpenFromConfig_DefaultsToEmbedded
which tested removed embedded Dolt functionality.
Fixed packages: beads_test, cmd/bd, cmd/bd/doctor, cmd/bd/doctor/fix,
internal/tracker, internal/utils
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fix pre-existing test failures from Dolt-Native Pruning phases 1-8.
All internal/* packages and cmd/bd/doctor now pass. Remaining 19
failures in cmd/bd are routing (9), init path checks (7), and tips (3).
Key fixes:
- Remove type assertions on concrete *dolt.DoltStore (not an interface)
- Fix DATETIME timezone bug: normalize timestamps to UTC before storage
- Replace SQLite datetime() syntax with MySQL DATE_SUB() in stale tests
- Remove --backend flag from init test invocations (flag removed)
- Update doctor tests for Dolt-only backend behavior
- Skip/remove tests for removed features (CompactableStorage,
FederatedStorage, ExportToMultiRepo, merge driver, no-db mode)
- Add issue_prefix config in test stores that create issues
- Fix export_hashes → interactions table reference in schema test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
Phase 7 (a5da57e3) deleted internal/storage/factory/ and internal/storage/memory/
but left 30+ files still importing them. This commit fixes all broken references:
- Created internal/storage/dolt/open.go with NewFromConfig/NewFromConfigWithOptions
- Replaced all factory.New/NewFromConfig/NewWithOptions with dolt equivalents
- Broke import cycles in dolt/bootstrap.go (routing/utils/audit → local types)
- Removed dead storage.Config struct
- Converted all test files from memory.New() to dolt.New() test stores
- Removed tests that depended on deleted detectPrefix/LoadFromIssues/mockRemoteStore
46 files changed, 249 insertions(+), 851 deletions(-)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
Strip out the multi-backend storage layer: factory pattern, memory/in-memory
provider, connection string parsing, local provider, and associated tests.
Inline Dolt as the sole storage backend. Part of Dolt-Native Beads v2 epic.
WIP - SQLite removal in progress, more cleanup phases to follow.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
* perf(doctor): fix O(n) full-table scans causing 130s doctor runs
Three performance fixes for bd doctor on large databases (23k+ issues):
1. CheckDuplicateIssues (66s → 10ms): Replace SearchIssues() that loaded
ALL issues into memory with SQL GROUP BY aggregation. The old code
transferred 23k full issue rows (50+ columns) over MySQL wire protocol
just to count duplicates.
2. CheckStaleClosedIssues (57s → 4ms): Replace SearchIssues() that loaded
ALL closed issues with SELECT COUNT(*) SQL query. Same root cause as #1.
3. ResolvePartialID (60s+ → <1s for missing IDs): The substring search
fallback loaded ALL issues when exact match failed. Now passes the hash
as a search query to leverage SQL-level id LIKE filtering instead of
transferring the entire database to Go for in-memory matching.
Total bd doctor runtime: 130s → 6s (22x speedup).
Total gt doctor runtime: infinite hang → 15s.
Root cause: These checks used store.SearchIssues() which does SELECT id
then GetIssuesByIDs() (full row fetch). On Dolt server mode with 23k+
issues, transferring all rows over MySQL wire protocol is catastrophically
slow. SQL aggregation and filtering avoid the data transfer entirely.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test(doctor): add 7 missing tests for performance PR
CheckStaleClosedIssues (6 tests):
- DisabledSmallCount: threshold=0, <10k closed → OK
- DisabledLargeCount: threshold=0, ≥10k closed → warning
- EnabledWithCleanable: threshold=30d, old issues → correct count
- EnabledNoneCleanable: threshold=30d, recent issues → OK
- PinnedExcluded: all pinned → 0 cleanable
- MixedPinnedAndStale: 5 stale + 3 pinned → reports 5
CheckDuplicateIssues (2 tests):
- MultipleDuplicateGroups: 2+ groups → correct groupCount/dupCount
- ZeroDuplicatesNullHandling: SUM() NULL → defaults to 0
ResolvePartialID (1 test):
- TitleFalsePositive: hash in title but different ID → rejected
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Add dec/adr aliases to utils.NormalizeIssueType() so CLI commands
like `bd list --type dec` resolve correctly. Add TypeDecision to
coreWorkTypes so `bd types` lists it. Update remaining help strings
in export, ready, and claude-plugin commands. Add alias test cases.
Co-authored-by: dariye <dariye@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Executed-By: beads/crew/emma
Rig: beads
Role: crew
Merged internal/util (NormalizeIssueType, NormalizeLabels) into
internal/utils package. Updated 8 consumers to import from the
consolidated package. Eliminates the confusing coexistence of
two similarly-named utility packages.
Closes dolt-test-oli
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add test coverage for ExtractIssuePrefix with multi-hyphen prefixes
like 'hacker-news' and 'me-py-toolkit' that were previously parsed
incorrectly when falling back to first-hyphen splitting.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
When issues from different rigs are hydrated into a single database,
each rig may have a different prefix (e.g., "aap-" for argocd, "hq-"
for town-level). Previously, `bd show aap-4ar` would fail when the
configured prefix was "hq-" because the code would incorrectly
normalize to "hq-aap-4ar".
The fix adds a `looksLikePrefixedID()` helper that detects if an input
already has a valid prefix format. If so, we skip prepending the
configured prefix and let the exact match or substring search handle it.
This enables Gas Town's `gt sling` command to resolve beads from any
rig regardless of the town-level prefix configuration.
In dolt-native mode (no issues.jsonl), FindJSONLInDir falls through
to "last resort" and returns the first .jsonl file found. This
caused routes.jsonl to be used as the export target, corrupting it
with issue data and breaking all cross-rig operations.
Fixes: bd-yxyh6
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add nil check at start of ResolvePartialID to return a proper error
instead of panicking when storage interface is nil.
Root cause: When bd refile (or other commands) is called with a nil
storage, calling store.SearchIssues() panics with SIGSEGV. This can
happen when routing fails to initialize storage properly.
Now returns: "cannot resolve issue ID <id>: storage is nil"
Fixes: bd-7ypor
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Centralizes repository context resolution via RepoContext API, fixing bugs where git commands run in the wrong repo when BEADS_DIR points elsewhere or in worktree scenarios.
Use SearchIssues with filter.IDs instead of GetIssue in ResolvePartialID.
This fixes inconsistencies where bd list could find issues that bd show
could not, due to subtle query differences between the two code paths.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
bd sync fails with exit status 128 when the daemon is started from a
terminal with different path casing than what git has stored. This
happens on macOS case-insensitive filesystem when directory names
are renamed (e.g., MyProject to myproject) but terminal sessions
retain the old casing.
The fix uses realpath(1) on macOS to get the true filesystem case
when canonicalizing paths:
- CanonicalizePath() now calls realpath on macOS
- git.GetRepoRoot() canonicalizes repoRoot via canonicalizeCase()
- syncbranch.GetRepoRoot() uses utils.CanonicalizePath()
This ensures git worktree paths match exactly, preventing the
exit status 128 errors from git operations.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Executed-By: beads/crew/dave
Rig: beads
Role: crew
On macOS and Windows, filesystems are typically case-insensitive, so
/Users/foo/Desktop and /Users/foo/desktop refer to the same directory.
The daemon registry and discovery code was doing direct string comparison,
causing path mismatches when the casing differed.
Fix:
- Add NormalizePathForComparison() and PathsEqual() to internal/utils/path.go
- These resolve symlinks and lowercase paths on darwin/windows
- Update all workspace path comparisons in registry.go, discovery.go, and
daemons.go to use PathsEqual()
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>