beads/cmd/bd/comment_routed_exact_test.go
Athos Bernardes ab9adc73db
Refuse reserved words and fuzzy id matches on bd comment writes (#5393)
* 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>
2026-10-01 05:04:32 -07:00

127 lines
5 KiB
Go

//go:build cgo
package main
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
// TestResolveAndGetIssueForMutationExactSurfacesRoutedAbbreviationRefusal pins
// the error SELECTION in resolveAndGetIssueForMutationExact, the one part of
// the exact-match contract the rest of this PR's tests cannot reach: they all
// exercise the LOCAL tier, where the refusal is the function's own return
// value. A cross-rig or auto-routed tier mints the same sentinel, and the
// truthful message the comment write paths print (comment.go, comments.go)
// depends on errors.Is seeing it from there too.
//
// The setup is the shape the sentinel exists for: the local store genuinely
// knows nothing about the id, so its error is the plain "no issue found
// matching" — which is FALSE here, because prefix routing finds the
// abbreviation's real target in the other rig and refuses it there.
//
// Both directions are pinned, because either assertion alone passes for the
// wrong reason: an abbreviation of a routed issue must select the ROUTED
// refusal over the local not-found, and an id that names nothing anywhere
// must still come back as a plain not-found rather than claiming an
// abbreviation exists.
//
// NOTE: assigns the dbPath global and uses os.Chdir, so it cannot run in
// parallel (same constraint as TestCheckBeadGateCrossRigPrefixRoute).
func TestResolveAndGetIssueForMutationExactSurfacesRoutedAbbreviationRefusal(t *testing.T) {
ctx := context.Background()
townRoot := t.TempDir()
townBeadsDir := filepath.Join(townRoot, ".beads")
rigBeadsDir := filepath.Join(townRoot, "rig", ".beads")
if err := os.MkdirAll(townBeadsDir, 0o755); err != nil {
t.Fatalf("create town beads dir: %v", err)
}
if err := os.MkdirAll(rigBeadsDir, 0o755); err != nil {
t.Fatalf("create rig beads dir: %v", err)
}
// The town store is the local store the comment write paths hold; it never
// holds the routed id, so it supplies the plain not-found this test is
// about discarding.
townDBPath := filepath.Join(townBeadsDir, "dolt")
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
const routedID = "gt-abcdefgh"
// One character short of routedID: not an exact id anywhere, but a valid
// leading-prefix abbreviation of a real issue in the routed rig.
const routedAbbrev = "gt-abcdefg"
// Routes to the same rig, but names nothing there in either form.
const absentRoutedID = "gt-zzzzzzzz"
rigStore := newTestStoreIsolatedDB(t, filepath.Join(rigBeadsDir, "dolt"), "gt")
if err := rigStore.CreateIssue(ctx, &types.Issue{
ID: routedID,
Title: "Routed comment target",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}, "test"); err != nil {
t.Fatalf("create routed issue %s: %v", routedID, err)
}
// Prefix routing opens the target itself, so hand the database back first.
if err := rigStore.Close(); err != nil {
t.Fatalf("close rig store: %v", err)
}
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(`{"prefix":"gt-","path":"rig"}`), 0o644); err != nil {
t.Fatalf("write routes.jsonl: %v", err)
}
oldDBPath := dbPath
dbPath = townDBPath
t.Cleanup(func() { dbPath = oldDBPath })
oldWD, err := os.Getwd()
if err != nil {
t.Fatalf("get working directory: %v", err)
}
if err := os.Chdir(townRoot); err != nil {
t.Fatalf("change to town root: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWD) })
// Direction 1: the routed tier's refusal must reach the caller, because
// the issue it refuses demonstrably exists.
result, err := resolveAndGetIssueForMutationExact(ctx, townStore, routedAbbrev)
if result != nil {
result.Close()
t.Fatalf("abbreviation %q of routed issue %s resolved instead of being refused", routedAbbrev, routedID)
}
if err == nil {
t.Fatalf("abbreviation %q of routed issue %s returned no error", routedAbbrev, routedID)
}
if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
t.Errorf("routed abbreviation %q error = %v, want one satisfying errors.Is(err, utils.ErrAbbreviatedIDNotAllowed)\n"+
"the comment write paths key their truthful message off this sentinel, so a local not-found here prints "+
"\"no issue found matching\" for an issue the routed rig holds", routedAbbrev, err)
}
// Direction 2: an id that names nothing in either store must NOT be
// reported as an abbreviation refusal — the selection has to be driven by
// the routed error's own sentinel, not by having routed at all.
result, err = resolveAndGetIssueForMutationExact(ctx, townStore, absentRoutedID)
if result != nil {
result.Close()
t.Fatalf("absent routed id %q resolved unexpectedly", absentRoutedID)
}
if err == nil {
t.Fatalf("absent routed id %q returned no error", absentRoutedID)
}
if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
t.Errorf("absent routed id %q error = %v, want NOT an abbreviation refusal", absentRoutedID, err)
}
if !isNotFoundErr(err) {
t.Errorf("absent routed id %q error = %v, want a not-found error", absentRoutedID, err)
}
}