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>
This commit is contained in:
parent
45a116d1a7
commit
ab9adc73db
16 changed files with 1269 additions and 31 deletions
26
CHANGELOG.md
26
CHANGELOG.md
|
|
@ -166,6 +166,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
(default 24h) controls how often the pause is re-announced. Manual `bd
|
||||
backup` / `bd backup sync` are not capped.
|
||||
|
||||
- **`bd comment`/`bd comments add` refuse an abbreviated id and a reserved
|
||||
word instead of silently resolving one to the wrong issue**
|
||||
([#5393](https://github.com/gastownhall/beads/pull/5393)). `bd comment list
|
||||
<id>`, a typo for `bd comments list`, used to parse as id="list" with no
|
||||
guard on the id slot — and since no issue is ever literally named "list",
|
||||
the default abbreviation-tolerant resolver would fuzzy-match it against
|
||||
whatever existing bead or wisp id happened to start with "list" and write
|
||||
the rest of the command line there as a comment. Confirmed in production:
|
||||
15+ automated sessions made this exact typo over two days and all landed on
|
||||
the same unrelated wisp. `bd comment`'s id positional now (a) refuses the
|
||||
four words a `bd comments <verb>` typo is likely to produce — `list`, `add`,
|
||||
`rm`, `delete` — before any id resolution is attempted, on both the
|
||||
embedded and proxied-server paths, and (b) requires an EXACT id match
|
||||
(`bd-a1b2c3d4`, not `a1b2`) rather than the abbreviation-tolerant matching
|
||||
every other command keeps. The refusal message is truthful about which
|
||||
case applies: a reserved word gets a hint toward `bd comments`; an
|
||||
abbreviation of a REAL issue gets `id abbreviations are not accepted on
|
||||
comment writes; use the full id from \`bd show <id>\`` rather than the
|
||||
generic (and in that case false) "no issue found matching" text a genuine
|
||||
not-found gets. See [Working with
|
||||
IDs](docs/core-concepts/hash-ids.md#working-with-ids) for the full
|
||||
read/write distinction. The proxied-server comment path was investigated
|
||||
separately and found to already be exact-id-only by construction (its
|
||||
resolution never performed abbreviation matching in the first place) — a
|
||||
regression test now locks that in rather than leaving it undocumented.
|
||||
|
||||
- **`bd doctor` no longer flags a `.local_version` that starts with `v`.** The
|
||||
canonical spelling of a Go module version — and the string a build stamped
|
||||
from a Go pseudo-version reports and writes into `.local_version` itself —
|
||||
|
|
|
|||
|
|
@ -559,7 +559,10 @@ go_test(
|
|||
"command_telemetry_test.go",
|
||||
"comment_promote_embedded_test.go",
|
||||
"comment_proxied_integration_test.go",
|
||||
"comment_reserved_word_test.go",
|
||||
"comment_routed_exact_test.go",
|
||||
"comment_test.go",
|
||||
"comments_add_test.go",
|
||||
"comments_cli_embedded_test.go",
|
||||
"comments_test.go",
|
||||
"compact_embedded_test.go",
|
||||
|
|
|
|||
|
|
@ -1525,11 +1525,13 @@ func TestCLI_CommentsSwappedAddRejectedInProxiedServerMode(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestCLI_CommentsAddShortID tests that 'comments add' accepts short IDs (issue #1070)
|
||||
// Most bd commands accept short IDs (e.g., "5wbm") but comments add previously required
|
||||
// full IDs (e.g., "mike.vibe-coding-5wbm"). This test ensures short IDs work.
|
||||
//
|
||||
// Note: Short IDs work because the code calls utils.ResolvePartialID().
|
||||
// TestCLI_CommentsAddShortID tests that 'comments add' accepts a bare full
|
||||
// hash without its issue prefix (e.g. "5wbm" for "mike.vibe-coding-5wbm",
|
||||
// issue #1070) — full IDs used to be required. It does NOT test genuine
|
||||
// abbreviation (a hash shorter than the real one): since PR #5393, comment
|
||||
// writes require an exact id (see resolveAndGetIssueForMutationExact /
|
||||
// utils.ResolvePartialIDExact) and PartialIDWithCommentsAdd below asserts
|
||||
// that a real abbreviation is refused, not accepted.
|
||||
func TestCLI_CommentsAddShortID(t *testing.T) {
|
||||
|
||||
t.Run("ShortIDWithCommentsAdd", func(t *testing.T) {
|
||||
|
|
@ -1582,6 +1584,14 @@ func TestCLI_CommentsAddShortID(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
// PartialIDWithCommentsAdd used to assert that a genuinely abbreviated id
|
||||
// (shorter than the full hash) succeeded on "comments add" — true when
|
||||
// this test was written (issue #1070), but no longer the contract: PR
|
||||
// #5393 review item M1 established that "comments add" must refuse an
|
||||
// abbreviation exactly like "comment" (singular) does (see
|
||||
// TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage), since the two
|
||||
// are documented as guarded twins (CHANGELOG.md, hash-ids.md). This
|
||||
// subtest now asserts the refusal instead of the old silent-accept.
|
||||
t.Run("PartialIDWithCommentsAdd", func(t *testing.T) {
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
|
|
@ -1595,22 +1605,53 @@ func TestCLI_CommentsAddShortID(t *testing.T) {
|
|||
json.Unmarshal([]byte(jsonOut), &issue)
|
||||
fullID := issue["id"].(string)
|
||||
|
||||
// Extract short ID and use only first 4 characters (partial match)
|
||||
// Derive the abbreviation as a strict, one-character-shorter leading
|
||||
// prefix of the real hash — the same derivation
|
||||
// comment_proxied_integration_test.go:247 already uses. The previous
|
||||
// "truncate to 4 chars, only if longer than 4" logic never fired
|
||||
// against a fresh test DB's fixture hashes (min_hash_length unset,
|
||||
// hashes as short as 3 chars), so shortID stayed equal to the full
|
||||
// hash and this subtest was dead-red in its own setup, never reaching
|
||||
// the assertions below (PR #5393 review R2, bee-ghosttrack) — and
|
||||
// mutation P-B (reverting comments.go's resolver back to the
|
||||
// abbreviation-tolerant one) went uncaught as a result.
|
||||
parts := strings.Split(fullID, "-")
|
||||
shortID := parts[len(parts)-1]
|
||||
if len(shortID) > 4 {
|
||||
shortID = shortID[:4] // Use only first 4 chars for partial match
|
||||
hash := parts[len(parts)-1]
|
||||
if len(hash) < 2 {
|
||||
t.Fatalf("test setup: hash %q too short to abbreviate", hash)
|
||||
}
|
||||
shortID := hash[:len(hash)-1]
|
||||
t.Logf("Full ID: %s, Partial ID: %s", fullID, shortID)
|
||||
|
||||
// Add comment using partial ID
|
||||
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", shortID, "Comment via partial ID")
|
||||
// Sanity check: the same abbreviation still works on a READ path
|
||||
// (show), proving this is a real, resolvable abbreviation and not an
|
||||
// accident of the fixture — the refusal below is specific to writes.
|
||||
showOut, showErr, err := runBDInProcessAllowError(t, tmpDir, "show", shortID, "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("comments add with partial ID failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
|
||||
t.Fatalf("fixture sanity check failed: 'bd show %s' unexpectedly failed: %v\nstdout: %s\nstderr: %s", shortID, err, showOut, showErr)
|
||||
}
|
||||
if !strings.Contains(showOut, fullID) {
|
||||
t.Fatalf("fixture sanity check failed: 'bd show %s' did not resolve to %s, got: %s", shortID, fullID, showOut)
|
||||
}
|
||||
|
||||
if !strings.Contains(stdout, "Comment added") {
|
||||
t.Errorf("Expected 'Comment added' in output, got: %s", stdout)
|
||||
// Add comment using partial ID — must now be refused, truthfully.
|
||||
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", shortID, "Comment via partial ID")
|
||||
if err == nil {
|
||||
t.Fatalf("expected non-zero exit for 'bd comments add %s ...' (abbreviation on a write path), got stdout=%q stderr=%q", shortID, stdout, stderr)
|
||||
}
|
||||
combined := stdout + stderr
|
||||
if !strings.Contains(combined, "abbreviations are not accepted") {
|
||||
t.Errorf("expected the truthful abbreviation-refusal message, got stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
if strings.Contains(combined, "not found") {
|
||||
t.Errorf("message must not claim the issue was not found — %s exists, only the abbreviation was refused; got stdout=%q stderr=%q", fullID, stdout, stderr)
|
||||
}
|
||||
|
||||
// Regression check: no comment silently landed on the real issue.
|
||||
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
||||
trimmed := strings.TrimSpace(commentsOut)
|
||||
if trimmed != "[]" && trimmed != "null" {
|
||||
t.Fatalf("expected no comments on %s after rejected abbreviated 'comments add', got: %s", fullID, commentsOut)
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -1810,6 +1851,176 @@ func TestCLI_CommentTextStartingWithReservedWordStillWorks(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestCLI_CommentRmDeleteReservedWordsRejected covers the two reserved words
|
||||
// TestCLI_CommentListMisplacedSyntax/TestCLI_CommentAddMisplacedSyntax do not:
|
||||
// "rm" and "delete" carry no hand-written case in validateCommentArgs (unlike
|
||||
// "list"/"add"), so they fall through to checkCommentIDNotReservedWord's
|
||||
// generic message and, before this test, had no CLI-level (cobra-dispatch)
|
||||
// coverage at all — steveyegge's PR #5393 review (item a) flagged that
|
||||
// generic message as potentially misleading for these two specifically, since
|
||||
// neither is an actual "bd comments" subcommand the way "list"/"add" are.
|
||||
// This pins both halves: the command is rejected, AND — the part that
|
||||
// actually matters — no comment silently lands on an unrelated real issue.
|
||||
func TestCLI_CommentRmDeleteReservedWordsRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, word := range []string{"rm", "delete"} {
|
||||
t.Run(word, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for "+word+"-typo", "-p", "1", "--json")
|
||||
jsonStart := strings.Index(out, "{")
|
||||
if jsonStart < 0 {
|
||||
t.Fatalf("No JSON found in create output: %s", out)
|
||||
}
|
||||
var issue map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
||||
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
||||
}
|
||||
fullID := issue["id"].(string)
|
||||
|
||||
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", word, "accidental stray text")
|
||||
if err == nil {
|
||||
t.Fatalf("expected non-zero exit for 'bd comment %s ...', got stdout=%q stderr=%q", word, stdout, stderr)
|
||||
}
|
||||
combined := stdout + stderr
|
||||
// Must be refused as an id/reserved word — but, unlike "list"/"add",
|
||||
// must NOT claim it is a misplaced "bd comments" subcommand: there is
|
||||
// no "bd comments rm" or "bd comments delete".
|
||||
if !strings.Contains(combined, "not a valid issue id") {
|
||||
t.Errorf("expected a not-a-valid-issue-id refusal, got stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
if strings.Contains(combined, "misplaced") {
|
||||
t.Errorf("message falsely implies %q is a misplaced \"bd comments\" subcommand (it isn't one), got stdout=%q stderr=%q", word, stdout, stderr)
|
||||
}
|
||||
|
||||
// The regression check: the bystander issue must have received NO
|
||||
// comment.
|
||||
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
||||
trimmed := strings.TrimSpace(commentsOut)
|
||||
if trimmed != "[]" && trimmed != "null" {
|
||||
t.Fatalf("expected no comments on bystander issue %s after rejected 'comment %s', got: %s", fullID, word, commentsOut)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch closes PR #5393
|
||||
// review R2's "NEW MINOR — the guard's wiring is untested": comments_add_test.go
|
||||
// unit-tests validateCommentsAddArgs directly, and that catches a gutted
|
||||
// function body (mutation P-C), but nothing drove "bd comments add
|
||||
// <reserved-word> ..." through actual cobra dispatch — unwiring
|
||||
// commentsAddCmd's Args field back to cobra.MinimumNArgs(1) left every
|
||||
// existing test green (mutation P-D). This runs the real command line, the
|
||||
// way a caller or an automated session actually invokes it, for every word in
|
||||
// commentReservedIDWords (validateCommentsAddArgs has no singular/plural
|
||||
// special-casing, unlike "comment"'s validateCommentArgs, so all four take
|
||||
// the same generic-message path and are equally worth covering here).
|
||||
func TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, word := range []string{"list", "add", "rm", "delete"} {
|
||||
t.Run(word, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
out := runBDInProcess(t, tmpDir, "create", "Bystander issue for comments-add "+word+"-typo", "-p", "1", "--json")
|
||||
jsonStart := strings.Index(out, "{")
|
||||
if jsonStart < 0 {
|
||||
t.Fatalf("No JSON found in create output: %s", out)
|
||||
}
|
||||
var issue map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
||||
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
||||
}
|
||||
fullID := issue["id"].(string)
|
||||
|
||||
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", word, "accidental stray text")
|
||||
if err == nil {
|
||||
t.Fatalf("expected non-zero exit for 'bd comments add %s ...', got stdout=%q stderr=%q", word, stdout, stderr)
|
||||
}
|
||||
combined := stdout + stderr
|
||||
if !strings.Contains(combined, "not a valid issue id") {
|
||||
t.Errorf("expected a not-a-valid-issue-id refusal, got stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
|
||||
// The regression check: the bystander issue must have received NO
|
||||
// comment — this is exactly what unwiring commentsAddCmd.Args back
|
||||
// to cobra.MinimumNArgs(1) would silently allow through.
|
||||
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
||||
trimmed := strings.TrimSpace(commentsOut)
|
||||
if trimmed != "[]" && trimmed != "null" {
|
||||
t.Fatalf("expected no comments on bystander issue %s after rejected 'comments add %s', got: %s", fullID, word, commentsOut)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage is the CLI-level
|
||||
// regression test for steveyegge's PR #5393 review item (c): a leading-prefix
|
||||
// abbreviation of a REAL issue's id is refused on comment writes (exact-only
|
||||
// policy, unchanged), but the refusal message must not claim the issue does
|
||||
// not exist — it does, the abbreviation was just refused. Before this fix,
|
||||
// resolveAndGetIssueForMutationExact surfaced ResolvePartialIDExact's plain
|
||||
// "no issue found matching %q", which is false in exactly this case; every
|
||||
// other command family (show/close/update) still accepts the same
|
||||
// abbreviation, so a truthful, distinguishing message matters here more than
|
||||
// most refusals.
|
||||
func TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tmpDir := setupCLITestDB(t)
|
||||
|
||||
out := runBDInProcess(t, tmpDir, "create", "Needs an exact id on comment", "-p", "1", "--json")
|
||||
jsonStart := strings.Index(out, "{")
|
||||
if jsonStart < 0 {
|
||||
t.Fatalf("No JSON found in create output: %s", out)
|
||||
}
|
||||
var issue map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil {
|
||||
t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out)
|
||||
}
|
||||
fullID := issue["id"].(string)
|
||||
if len(fullID) < 4 {
|
||||
t.Fatalf("test setup: generated id %q too short to abbreviate", fullID)
|
||||
}
|
||||
abbrev := fullID[:len(fullID)-1]
|
||||
|
||||
// Sanity check: the same abbreviation still works on a READ path (show),
|
||||
// proving this is a real, resolvable abbreviation and not an accident of
|
||||
// the fixture — the gap this test guards is specific to comment WRITES.
|
||||
showOut, showErr, err := runBDInProcessAllowError(t, tmpDir, "show", abbrev, "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("fixture sanity check failed: 'bd show %s' unexpectedly failed: %v\nstdout: %s\nstderr: %s", abbrev, err, showOut, showErr)
|
||||
}
|
||||
if !strings.Contains(showOut, fullID) {
|
||||
t.Fatalf("fixture sanity check failed: 'bd show %s' did not resolve to %s, got: %s", abbrev, fullID, showOut)
|
||||
}
|
||||
|
||||
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", abbrev, "should not be written")
|
||||
if err == nil {
|
||||
t.Fatalf("expected non-zero exit for 'bd comment %s ...' (abbreviation on a write path), got stdout=%q stderr=%q", abbrev, stdout, stderr)
|
||||
}
|
||||
combined := stdout + stderr
|
||||
if !strings.Contains(combined, "abbreviations are not accepted") {
|
||||
t.Errorf("expected the truthful abbreviation-refusal message, got stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(combined, "bd show") {
|
||||
t.Errorf("expected the message to point at the full id via `bd show`, got stdout=%q stderr=%q", stdout, stderr)
|
||||
}
|
||||
if strings.Contains(combined, "not found") {
|
||||
t.Errorf("message must not claim the issue was not found — %s exists, only the abbreviation was refused; got stdout=%q stderr=%q", fullID, stdout, stderr)
|
||||
}
|
||||
|
||||
// The regression check: no comment silently landed on the real issue.
|
||||
commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json")
|
||||
trimmed := strings.TrimSpace(commentsOut)
|
||||
if trimmed != "[]" && trimmed != "null" {
|
||||
t.Fatalf("expected no comments on %s after rejected abbreviated 'comment', got: %s", fullID, commentsOut)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCLI_CreateRejectsFlagLikeTitles verifies that positional arguments starting
|
||||
// with - or -- are rejected as likely misinterpreted flags (bd-2c0).
|
||||
func TestCLI_CreateRejectsFlagLikeTitles(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -843,7 +843,7 @@ func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, id
|
|||
// Write-intent: a prefix-routed target opens writable so the close
|
||||
// commits on the target head (#4141). Contributor auto-routing below
|
||||
// stays read-only: it hydrates foreign projects that must not be mutated.
|
||||
if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true); err == nil {
|
||||
if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true, false); err == nil {
|
||||
results = append(results, r)
|
||||
continue
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,60 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
// commentReservedIDWords are "comments" subcommand names that must never be
|
||||
// silently accepted as the <id> positional of "bd comment" (singular). They
|
||||
// exist so a typo'd plural form — "bd comment list <id>", meant to be
|
||||
// "bd comments list" / "bd comments <id>" — fails loudly instead of treating
|
||||
// "list" as the id and the real id as comment text.
|
||||
//
|
||||
// This is not a hypothetical: 15+ automated sessions in one deployment made
|
||||
// exactly this typo over two days, and because "list" happened to be a
|
||||
// leading-prefix abbreviation of an unrelated wisp's hash ("list3t0"), each
|
||||
// one silently wrote a garbage comment onto that wisp instead of erroring.
|
||||
// The word list mirrors the real "comments" subcommand (add) plus the other
|
||||
// verbs a "comments <verb>" typo is likely to produce.
|
||||
var commentReservedIDWords = map[string]bool{
|
||||
"list": true,
|
||||
"add": true,
|
||||
"rm": true,
|
||||
"delete": true,
|
||||
}
|
||||
|
||||
// checkCommentIDNotReservedWord rejects an id argument that is one of
|
||||
// commentReservedIDWords, with a message pointing at the "bd comments"
|
||||
// subcommand the caller most likely meant. Pure and side-effect free so it
|
||||
// can run before either the direct or proxied-server RunE branch, and be
|
||||
// unit tested without a store.
|
||||
func checkCommentIDNotReservedWord(id string) error {
|
||||
if !commentReservedIDWords[id] {
|
||||
return nil
|
||||
}
|
||||
// "list" and "add" are genuinely misplaced "bd comments" subcommands, but
|
||||
// "rm" and "delete" are not — there is no "bd comments rm"/"bd comments
|
||||
// delete" (they read as bd's own delete command, or "dep rm"'s pattern,
|
||||
// used in the wrong place). The message below must hold for all four, so
|
||||
// it says "reserved word", never "misplaced bd comments subcommand".
|
||||
return HandleErrorRespectJSON(`%q is not a valid issue id — bd reserves it as a command/subcommand word (a real id never collides with one), so it is refused as an id instead of silently resolved as one.
|
||||
|
||||
To comment on an issue:
|
||||
bd comment <issue-id> "text"
|
||||
bd comments add <issue-id> "text"
|
||||
|
||||
To list comments:
|
||||
bd comments <issue-id>
|
||||
|
||||
See: bd comment --help`, id)
|
||||
}
|
||||
|
||||
// validateCommentArgs runs as cobra's Args validation for the singular
|
||||
// "comment" shorthand, before RunE's usesProxiedServer() dispatch and (on
|
||||
// the local/embedded path) before the id ever reaches ResolvePartialID's
|
||||
|
|
@ -45,7 +92,15 @@ To add a comment:
|
|||
|
||||
See: bd comment --help`)
|
||||
}
|
||||
return nil
|
||||
// The two cases above carry hand-written messages for the two typos that
|
||||
// were actually reported, both real "bd comments" subcommands. The
|
||||
// remaining reserved words ("rm", "delete") are not "bd comments"
|
||||
// subcommands — they collide with words bd uses elsewhere ("bd delete",
|
||||
// "dep rm") — so they get checkCommentIDNotReservedWord's word-agnostic
|
||||
// generic message instead of a claim that would be false for them.
|
||||
// Keeping the whole set in commentReservedIDWords also keeps the check
|
||||
// unit-testable on its own.
|
||||
return checkCommentIDNotReservedWord(args[0])
|
||||
}
|
||||
|
||||
var commentCmd = &cobra.Command{
|
||||
|
|
@ -96,11 +151,18 @@ To list comments on an issue, use the plural form: bd comments <id>`,
|
|||
|
||||
ctx := rootCtx
|
||||
|
||||
result, err := resolveAndGetIssueForMutation(ctx, store, id)
|
||||
result, err := resolveAndGetIssueForMutationExact(ctx, store, id)
|
||||
if err != nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
// The issue does exist — id just isn't its full form — so
|
||||
// "resolving %s: %v"'s generic wording (and the "no issue
|
||||
// found matching" text underneath a plain not-found) would be
|
||||
// false here. Say what actually happened instead.
|
||||
return HandleErrorRespectJSON("id abbreviations are not accepted on comment writes; use the full id from `bd show %s`", id)
|
||||
}
|
||||
return HandleErrorRespectJSON("resolving %s: %v", id, err)
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
|
|
|
|||
|
|
@ -216,6 +216,75 @@ func TestProxiedServerComment(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
// TestProxiedServerComment/comment_write_never_resolves_abbreviated_id is
|
||||
// the "document/test the gap explicitly" half of steveyegge's PR #5393
|
||||
// review item (b): "the proxied-server path is untouched by the
|
||||
// exact-match fix... extend exact matching to that path, or document/test
|
||||
// the gap explicitly."
|
||||
//
|
||||
// Investigation (not just this test) found there is no gap to extend
|
||||
// matching to: resolveCommentTargetProxied (comments_proxied_server.go)
|
||||
// resolves via workapi.GetIssueOrWisp with the RAW id, which bottoms out
|
||||
// in issueSQLRepositoryImpl.Get's plain "WHERE id = ?" (SQL exact
|
||||
// equality — internal/storage/domain/db/issue.go). Unlike the embedded
|
||||
// path (resolveAndGetIssueWithRouting -> utils.ResolvePartialID), nothing
|
||||
// in this call chain ever performed leading-prefix abbreviation matching
|
||||
// — comment's proxied writes were exact-id-only before PR #5393 and
|
||||
// remain so. This test locks that in as a regression guard: an
|
||||
// abbreviation of a REAL issue's id must be refused (not silently
|
||||
// resolved to it, and not silently resolved to an unrelated bystander
|
||||
// issue) when running against a real proxied server, the same way it
|
||||
// already is against the embedded store.
|
||||
t.Run("comment_write_never_resolves_abbreviated_id", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "pa")
|
||||
target := bdProxiedCreate(t, bd, p.dir, "Needs exact id on comment (proxied)")
|
||||
bystander := bdProxiedCreate(t, bd, p.dir, "Bystander issue (proxied)")
|
||||
|
||||
if len(target.ID) < 4 {
|
||||
t.Fatalf("test setup: generated id %q too short to abbreviate", target.ID)
|
||||
}
|
||||
abbrev := target.ID[:len(target.ID)-1]
|
||||
|
||||
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "comment", abbrev, "should not land anywhere")
|
||||
if err == nil {
|
||||
t.Fatalf("bd comment %s unexpectedly succeeded in proxied mode\nstdout:\n%s\nstderr:\n%s", abbrev, stdout, stderr)
|
||||
}
|
||||
// Asserted as the whole message, not strings.Contains(id): the proxied
|
||||
// route resolves through one exact "WHERE id = ?", so it cannot tell an
|
||||
// abbreviation of a real issue from an id that names nothing, and it
|
||||
// deliberately keeps the same "not found" wording for both — where the
|
||||
// embedded route says "id abbreviations are not accepted on comment
|
||||
// writes" (comment.go). Giving the proxied plane the truthful wording
|
||||
// would mean probing for abbreviation matches on a write path, which is
|
||||
// the resolution behaviour this PR exists to remove. A Contains(id)
|
||||
// assertion passes on either wording, so it would leave that asymmetry
|
||||
// untested; pinning the exact text makes it a deliberate choice that
|
||||
// breaks loudly if either side moves.
|
||||
if got, want := strings.TrimSpace(stderr), "Error: issue "+abbrev+" not found"; got != want {
|
||||
t.Errorf("abbreviated-ID stderr = %q, want %q", got, want)
|
||||
}
|
||||
if stdout != "" {
|
||||
t.Errorf("abbreviated-ID stdout = %q, want empty", stdout)
|
||||
}
|
||||
|
||||
// The regression check: neither the abbreviation's real target nor an
|
||||
// unrelated bystander received a comment.
|
||||
for _, id := range []string{target.ID, bystander.ID} {
|
||||
commentsOut, commentsErr, cErr := bdProxiedRunBuffers(t, bd, p.dir, "comments", "--json", id)
|
||||
if cErr != nil {
|
||||
t.Fatalf("bd comments --json %s failed: %v\nstdout:\n%s\nstderr:\n%s", id, cErr, commentsOut, commentsErr)
|
||||
}
|
||||
var comments []types.Comment
|
||||
if err := json.Unmarshal([]byte(commentsOut), &comments); err != nil {
|
||||
t.Fatalf("decode comments JSON for %s: %v\nraw: %q", id, err, commentsOut)
|
||||
}
|
||||
if len(comments) != 0 {
|
||||
t.Fatalf("expected no comments on %s after rejected abbreviated 'comment', got: %v", id, comments)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("wisp_comments_add_round_trip_and_physical_routing", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "wa")
|
||||
|
|
|
|||
46
cmd/bd/comment_reserved_word_test.go
Normal file
46
cmd/bd/comment_reserved_word_test.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCheckCommentIDNotReservedWord covers a real incident: "bd comment list
|
||||
// <id>", a typo for "bd comments list", must be rejected before any id
|
||||
// resolution is attempted — not silently treat "list" as the id.
|
||||
func TestCheckCommentIDNotReservedWord(t *testing.T) {
|
||||
reserved := []string{"list", "add", "rm", "delete"}
|
||||
for _, word := range reserved {
|
||||
t.Run("rejects reserved word "+word, func(t *testing.T) {
|
||||
var err error
|
||||
stderr := captureStderr(t, func() {
|
||||
err = checkCommentIDNotReservedWord(word)
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("checkCommentIDNotReservedWord(%q) = nil; want error", word)
|
||||
}
|
||||
if !strings.Contains(stderr, "bd comments") {
|
||||
t.Errorf("checkCommentIDNotReservedWord(%q) printed %q; want a hint mentioning bd comments", word, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
happyPath := []string{
|
||||
"bd-123",
|
||||
"a3f8e9",
|
||||
"ga-wisp-list3t0", // full id containing "list" as a substring must NOT be rejected
|
||||
"listicle-42", // starts with "list" but is not the literal reserved word
|
||||
"LIST", // reserved-word check is intentionally case-sensitive: real ids are lowercase hashes
|
||||
}
|
||||
for _, id := range happyPath {
|
||||
t.Run("allows real id "+id, func(t *testing.T) {
|
||||
var err error
|
||||
captureStderr(t, func() {
|
||||
err = checkCommentIDNotReservedWord(id)
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("checkCommentIDNotReservedWord(%q) = %v; want nil (happy path must stay intact)", id, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
127
cmd/bd/comment_routed_exact_test.go
Normal file
127
cmd/bd/comment_routed_exact_test.go
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
//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)
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
|
|
@ -10,6 +11,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/uimd"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
|
|
@ -165,6 +167,21 @@ See: bd comments --help`)
|
|||
},
|
||||
}
|
||||
|
||||
// validateCommentsAddArgs runs as cobra's Args validation for "comments add",
|
||||
// the plural twin of "comment"'s validateCommentArgs. It exists for the same
|
||||
// reason: an id argument that IS a reserved word (see
|
||||
// commentReservedIDWords) must never reach either dispatch branch (local or
|
||||
// proxied) or fuzzy resolution, where it could silently land on an unrelated
|
||||
// issue instead of erroring. Unlike validateCommentArgs, there is no
|
||||
// singular/plural confusion to special-case here — "comments add" is already
|
||||
// the plural form — so this only runs the word-agnostic generic check.
|
||||
func validateCommentsAddArgs(cmd *cobra.Command, args []string) error {
|
||||
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
return checkCommentIDNotReservedWord(args[0])
|
||||
}
|
||||
|
||||
var commentsAddCmd = &cobra.Command{
|
||||
Use: "add [issue-id] [text...]",
|
||||
Short: "Add a comment to an issue",
|
||||
|
|
@ -176,7 +193,7 @@ Examples:
|
|||
|
||||
# Add a comment from a file
|
||||
bd comments add bd-123 -f notes.txt`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Args: validateCommentsAddArgs,
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
|
|
@ -213,11 +230,19 @@ Examples:
|
|||
}
|
||||
ctx := rootCtx
|
||||
|
||||
result, err := resolveAndGetIssueForMutation(ctx, store, issueID)
|
||||
result, err := resolveAndGetIssueForMutationExact(ctx, store, issueID)
|
||||
if err != nil {
|
||||
if result != nil {
|
||||
result.Close()
|
||||
}
|
||||
if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
// The issue does exist — id just isn't its full form — so
|
||||
// "resolving %s: %v"'s generic wording (and the "no issue
|
||||
// found matching" text underneath a plain not-found) would be
|
||||
// false here. Say what actually happened instead, matching
|
||||
// "bd comment"'s truthful message.
|
||||
return HandleErrorRespectJSON("id abbreviations are not accepted on comment writes; use the full id from `bd show %s`", issueID)
|
||||
}
|
||||
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
|
|
|
|||
43
cmd/bd/comments_add_test.go
Normal file
43
cmd/bd/comments_add_test.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestValidateCommentsAddArgs is a pure unit test for "comments add"'s Args
|
||||
// guard — it calls the validator directly with no store, no Dolt, and no
|
||||
// cobra dispatch, so it runs regardless of cgo/Docker availability. Mirrors
|
||||
// TestValidateCommentArgs (the singular "comment" sibling in comment_test.go)
|
||||
// for the plural form: PR #5393 review item M1 established that "comments
|
||||
// add" must reject a reserved-word id exactly like "comment" does, since the
|
||||
// two are documented as guarded twins (CHANGELOG.md, hash-ids.md).
|
||||
func TestValidateCommentsAddArgs(t *testing.T) {
|
||||
origJSONOutput := jsonOutput
|
||||
jsonOutput = false
|
||||
t.Cleanup(func() { jsonOutput = origJSONOutput })
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "bare list is rejected", args: []string{"list", "some text"}, wantErr: true},
|
||||
{name: "bare add is rejected", args: []string{"add", "some text"}, wantErr: true},
|
||||
{name: "bare rm is rejected", args: []string{"rm", "some text"}, wantErr: true},
|
||||
{name: "bare delete is rejected", args: []string{"delete", "some text"}, wantErr: true},
|
||||
{name: "real id with text starting with the word list is fine", args: []string{"test-abc123", "list", "of", "things", "to", "do"}, wantErr: false},
|
||||
{name: "real id with text starting with the word add is fine", args: []string{"test-abc123", "add", "one", "more", "item"}, wantErr: false},
|
||||
{name: "real id alone (text comes from --stdin/--file) is fine", args: []string{"test-abc123"}, wantErr: false},
|
||||
{name: "no args at all is rejected by the base MinimumNArgs check", args: []string{}, wantErr: true},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := validateCommentsAddArgs(commentsAddCmd, tc.args)
|
||||
if tc.wantErr && err == nil {
|
||||
t.Fatalf("validateCommentsAddArgs(%q): expected an error, got nil", tc.args)
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Fatalf("validateCommentsAddArgs(%q): expected no error, got %v", tc.args, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
112
cmd/bd/routed.go
112
cmd/bd/routed.go
|
|
@ -78,7 +78,7 @@ func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage
|
|||
// This handles cross-rig lookups where the ID's prefix maps to a different
|
||||
// database (e.g., hr-8wn.1 routes to the herald rig's database).
|
||||
if isNotFoundErr(err) {
|
||||
if prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, writablePrefixRoute); prefixErr == nil {
|
||||
if prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, writablePrefixRoute, false); prefixErr == nil {
|
||||
return prefixResult, nil
|
||||
}
|
||||
}
|
||||
|
|
@ -87,7 +87,7 @@ func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage
|
|||
// Auto-routed stores stay read-only even for write-intent callers (writablePrefixRoute):
|
||||
// this path hydrates foreign contributor projects, which must never be mutated.
|
||||
if isNotFoundErr(err) {
|
||||
if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id); autoErr == nil {
|
||||
if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, false); autoErr == nil {
|
||||
return autoResult, nil
|
||||
}
|
||||
}
|
||||
|
|
@ -117,16 +117,102 @@ func resolveAndGetFromStore(ctx context.Context, s storage.DoltStorage, id strin
|
|||
}, nil
|
||||
}
|
||||
|
||||
// resolveAndGetFromStoreExact is resolveAndGetFromStore's exact-match sibling:
|
||||
// it requires utils.ResolvePartialIDExact instead of the default abbreviation-
|
||||
// tolerant resolver, so a non-exact candidate (e.g. a reserved word that
|
||||
// happens to be a leading-prefix abbreviation of some issue's hash) is
|
||||
// reported as "not found" rather than silently resolved.
|
||||
func resolveAndGetFromStoreExact(ctx context.Context, s storage.DoltStorage, id string, routed bool) (*RoutedResult, error) {
|
||||
resolvedID, err := utils.ResolvePartialIDExact(ctx, s, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
issue, err := s.GetIssue(ctx, resolvedID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &RoutedResult{
|
||||
Issue: issue,
|
||||
Store: s,
|
||||
Routed: routed,
|
||||
ResolvedID: resolvedID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// resolveAndGetIssueForMutationExact resolves an issue like
|
||||
// resolveAndGetIssueForMutation, but requires an EXACT id match against each
|
||||
// store it tries (no leading-prefix abbreviation matching) — see
|
||||
// utils.ResolvePartialIDExact. Cross-rig prefix routing and contributor
|
||||
// auto-routing are still attempted as fallbacks exactly as before if the
|
||||
// local store doesn't have the issue at all; only the per-store resolution
|
||||
// within each tier is tightened. Used by write paths where an id argument
|
||||
// that doesn't exactly name a real issue must error out instead of silently
|
||||
// mutating whatever it fuzzy-matches (`bd comment list <id>`, a typo for
|
||||
// `bd comments list`, was silently resolving "list" to a wisp whose hash
|
||||
// happened to start with "list").
|
||||
func resolveAndGetIssueForMutationExact(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
|
||||
result, err := resolveAndGetFromStoreExact(ctx, localStore, id, false)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// The routed tiers resolve with utils.ResolvePartialIDExact too, so each
|
||||
// can mint utils.ErrAbbreviatedIDNotAllowed of its own — the abbreviation
|
||||
// names a real issue in the routed rig rather than here — and both
|
||||
// wrappers hand that error back unwrapped. Keep the first such refusal:
|
||||
// the local error is only a plain not-found, and returning it would tell
|
||||
// the caller no issue matches an id a routed store demonstrably holds,
|
||||
// which is exactly the falsehood the sentinel exists to prevent.
|
||||
var abbrevErr error
|
||||
|
||||
if isNotFoundErr(err) {
|
||||
prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, true, true)
|
||||
if prefixErr == nil {
|
||||
return prefixResult, nil
|
||||
}
|
||||
if errors.Is(prefixErr, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
abbrevErr = prefixErr
|
||||
}
|
||||
}
|
||||
|
||||
if isNotFoundErr(err) {
|
||||
autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, true)
|
||||
if autoErr == nil {
|
||||
return autoResult, nil
|
||||
}
|
||||
if abbrevErr == nil && errors.Is(autoErr, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
abbrevErr = autoErr
|
||||
}
|
||||
}
|
||||
|
||||
if abbrevErr != nil {
|
||||
return nil, abbrevErr
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// resolveViaAutoRouting attempts to find an issue using contributor auto-routing.
|
||||
// This is the fallback when the local store doesn't have the issue (GH#2345).
|
||||
// Returns a RoutedResult if the issue is found in the auto-routed store.
|
||||
func resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
|
||||
//
|
||||
// exact selects utils.ResolvePartialIDExact over the default abbreviation-
|
||||
// tolerant resolver for the auto-routed store lookup, mirroring the local-store
|
||||
// distinction in resolveAndGetFromStore vs resolveAndGetFromStoreExact.
|
||||
func resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage, id string, exact bool) (*RoutedResult, error) {
|
||||
routedStore, routed, _, err := openRoutedReadStore(ctx, localStore)
|
||||
if err != nil || !routed {
|
||||
return nil, fmt.Errorf("no auto-routed store available")
|
||||
}
|
||||
|
||||
result, err := resolveAndGetFromStore(ctx, routedStore, id, true)
|
||||
var result *RoutedResult
|
||||
if exact {
|
||||
result, err = resolveAndGetFromStoreExact(ctx, routedStore, id, true)
|
||||
} else {
|
||||
result, err = resolveAndGetFromStore(ctx, routedStore, id, true)
|
||||
}
|
||||
if err != nil {
|
||||
_ = routedStore.Close()
|
||||
return nil, err
|
||||
|
|
@ -152,14 +238,17 @@ type prefixRoute struct {
|
|||
// The read-only open guarantees a routed read cannot mutate the target; mutation
|
||||
// commands must route through resolveViaPrefixRoutingWithAccess with writable=true.
|
||||
func resolveViaPrefixRouting(ctx context.Context, id string) (*RoutedResult, error) {
|
||||
return resolveViaPrefixRoutingWithAccess(ctx, id, false)
|
||||
return resolveViaPrefixRoutingWithAccess(ctx, id, false, false)
|
||||
}
|
||||
|
||||
// resolveViaPrefixRoutingWithAccess is the shared implementation that selects the
|
||||
// store-open mode. writable opens the routed target writable, behaving like running
|
||||
// the command inside that rig; false keeps the read-only open that guarantees a
|
||||
// routed read cannot mutate the target (bd-6dnrw.32).
|
||||
func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable bool) (*RoutedResult, error) {
|
||||
// routed read cannot mutate the target (bd-6dnrw.32). exact selects
|
||||
// utils.ResolvePartialIDExact over the default abbreviation-tolerant resolver for
|
||||
// the routed store lookup, mirroring resolveAndGetFromStore vs
|
||||
// resolveAndGetFromStoreExact.
|
||||
func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable bool, exact bool) (*RoutedResult, error) {
|
||||
if strings.Index(id, "-") <= 0 {
|
||||
return nil, fmt.Errorf("no prefix in ID %q", id)
|
||||
}
|
||||
|
|
@ -225,7 +314,12 @@ func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable
|
|||
return nil, fmt.Errorf("opening routed store for %s: %w", matchedRoute.Path, openErr)
|
||||
}
|
||||
|
||||
result, err := resolveAndGetFromStore(ctx, targetStore, id, true)
|
||||
var result *RoutedResult
|
||||
if exact {
|
||||
result, err = resolveAndGetFromStoreExact(ctx, targetStore, id, true)
|
||||
} else {
|
||||
result, err = resolveAndGetFromStore(ctx, targetStore, id, true)
|
||||
}
|
||||
if err != nil {
|
||||
_ = targetStore.Close()
|
||||
return nil, err
|
||||
|
|
@ -326,7 +420,7 @@ func getIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id
|
|||
|
||||
// If not found via prefix routing, try contributor auto-routing as fallback (GH#2345).
|
||||
if isNotFoundErr(err) {
|
||||
if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id); autoErr == nil {
|
||||
if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, false); autoErr == nil {
|
||||
return autoResult, nil
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,6 +118,31 @@ bd show bd-a1b2c3d4
|
|||
bd list --full-ids
|
||||
```
|
||||
|
||||
### `bd comment` requires the full id
|
||||
|
||||
Every command above resolves an abbreviation the same way — but `bd comment
|
||||
<id> "text"` (and its `bd comments add` twin) is the one deliberate exception:
|
||||
it accepts only a full, exact id, never an abbreviation. This is a policy
|
||||
trade for an agent fleet, not an oversight: an abbreviation that happens to be
|
||||
a leading-prefix match for the wrong issue would silently write the comment
|
||||
there instead of erroring, and a comment write has no confirmation step to
|
||||
catch it before the message lands on the wrong issue. Reads and every other
|
||||
mutation (`show`, `close`, `update`, …) keep accepting abbreviations as
|
||||
documented above.
|
||||
|
||||
```bash
|
||||
bd show a1b2 # OK — abbreviation resolves for reads
|
||||
bd close a1b2 # OK — abbreviation resolves for other writes
|
||||
bd comment a1b2 "text" # refused — comment writes require the full id
|
||||
bd comment bd-a1b2c3d4 "text" # OK — use the full id from `bd show`
|
||||
```
|
||||
|
||||
A reserved word (`list`, `add`, `rm`, `delete`) as the id positional is
|
||||
refused the same way, for a related reason: `bd comment list "text"` almost
|
||||
always means the caller confused the singular shorthand with the plural `bd
|
||||
comments list`/`bd comments add <id> "text"`, not that an issue is literally
|
||||
named `list`.
|
||||
|
||||
## Migration from Sequential IDs
|
||||
|
||||
If migrating from a system with sequential IDs:
|
||||
|
|
@ -132,7 +157,9 @@ bd show bd-new --json | jq '.original_id'
|
|||
|
||||
## Best Practices
|
||||
|
||||
1. **Use short references** - `bd-a1b2` is usually unique enough
|
||||
1. **Use short references** - `bd-a1b2` is usually unique enough, except on
|
||||
`bd comment` writes, which require the full id (see
|
||||
[Working with IDs](#working-with-ids) above)
|
||||
2. **Use `--json` for scripts** - Parse full ID programmatically
|
||||
3. **Reference by hash in commits** - `Fixed bd-a1b2` in commit messages
|
||||
4. **Let hierarchies form naturally** - Create epics, add children as needed
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ go_library(
|
|||
go_test(
|
||||
name = "utils_test",
|
||||
srcs = [
|
||||
"id_parser_exact_test.go",
|
||||
"id_parser_fake_test.go",
|
||||
"id_parser_prefix_test.go",
|
||||
"id_parser_sentinel_test.go",
|
||||
"id_parser_test.go",
|
||||
|
|
|
|||
|
|
@ -19,6 +19,20 @@ import (
|
|||
// "not found" and surface the candidate list instead of a generic failure.
|
||||
var ErrAmbiguousID = errors.New("ambiguous issue ID")
|
||||
|
||||
// ErrAbbreviatedIDNotAllowed is the sentinel wrapped into the error
|
||||
// ResolvePartialIDExact returns when the input does not exactly name an
|
||||
// issue but WOULD have resolved via leading-prefix abbreviation matching —
|
||||
// the behavior ResolvePartialID allows and exact-only callers refuse.
|
||||
//
|
||||
// Distinguishing this from "no such issue at all" matters because the two
|
||||
// are not the same failure: an abbreviation that matches a real issue is
|
||||
// proof the issue exists, so telling the caller "no issue found matching"
|
||||
// (the message a genuine not-found gets) is false. Exact-only callers use
|
||||
// errors.Is(err, ErrAbbreviatedIDNotAllowed) to give a truthful, actionable
|
||||
// message instead ("id abbreviations are not accepted here; use the full
|
||||
// id") — see bd comment's resolveAndGetIssueForMutationExact caller.
|
||||
var ErrAbbreviatedIDNotAllowed = errors.New("id is a valid abbreviation, but exact-match resolution is required here")
|
||||
|
||||
type PartialIDResolverStore interface {
|
||||
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error)
|
||||
SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error)
|
||||
|
|
@ -53,6 +67,29 @@ func parseIssueID(input string, prefix string) string {
|
|||
// - No issue found matching the ID
|
||||
// - Multiple issues match (ambiguous prefix)
|
||||
func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input string) (string, error) {
|
||||
return resolvePartialID(ctx, store, input, true)
|
||||
}
|
||||
|
||||
// ResolvePartialIDExact resolves an issue ID like ResolvePartialID, but never
|
||||
// falls back to leading-prefix abbreviation matching (e.g. "a3f8" ->
|
||||
// "a3f8e9...", or a wisp's stripped hash "list" -> "list3t0") — only a full
|
||||
// exact ID or exact hash match (with or without a "wisp-" infix) succeeds.
|
||||
//
|
||||
// Intended for write paths where a mistyped or coincidentally-prefix-matching
|
||||
// argument must return "not found" instead of silently mutating an unrelated
|
||||
// issue (e.g. `bd comment list <id>`, a typo for `bd comments list`, was
|
||||
// silently fuzzy-resolving "list" to a wisp whose hash happened to start with
|
||||
// "list" and writing the rest of the command line to it as a comment).
|
||||
//
|
||||
// When the input matches nothing exactly but WOULD have resolved via
|
||||
// leading-prefix abbreviation, the returned error wraps
|
||||
// ErrAbbreviatedIDNotAllowed rather than being indistinguishable from a
|
||||
// genuine not-found — see that sentinel's doc comment.
|
||||
func ResolvePartialIDExact(ctx context.Context, store PartialIDResolverStore, input string) (string, error) {
|
||||
return resolvePartialID(ctx, store, input, false)
|
||||
}
|
||||
|
||||
func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input string, allowAbbrev bool) (string, error) {
|
||||
// Refuse before any lookup: these tokens are a valid partial-ID shape, so
|
||||
// they otherwise reach the leading-prefix abbreviation branch below.
|
||||
switch strings.ToLower(strings.TrimSpace(input)) {
|
||||
|
|
@ -153,6 +190,10 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
|
|||
|
||||
var matches []string
|
||||
var exactMatch string
|
||||
// abbrevOnly collects candidates that matched ONLY via leading-prefix
|
||||
// abbreviation while allowAbbrev is false — never resolved to, only used
|
||||
// to make the final "not found" error truthful (see ErrAbbreviatedIDNotAllowed).
|
||||
var abbrevOnly []string
|
||||
|
||||
for _, id := range ids {
|
||||
// Check for exact full ID match first (case: user typed full ID with different prefix)
|
||||
|
|
@ -179,7 +220,14 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
|
|||
// Leading-prefix abbreviation (documented UX, e.g. "a3f8" -> "a3f8e9...").
|
||||
// HasPrefix rather than Contains: reject interior-substring matches
|
||||
// like "kt8" inside "j0kt8" (GH#4234).
|
||||
matches = append(matches, id)
|
||||
if allowAbbrev {
|
||||
matches = append(matches, id)
|
||||
} else {
|
||||
// Exact-only callers must never silently resolve to this
|
||||
// candidate, but its existence is what makes "no issue found
|
||||
// matching" false below — track it instead of discarding it.
|
||||
abbrevOnly = append(abbrevOnly, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -214,7 +262,11 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
|
|||
if wHash == hashPart || wispHash == hashPart {
|
||||
exactMatch = wID
|
||||
} else if strings.HasPrefix(wispHash, hashPart) {
|
||||
matches = append(matches, wID)
|
||||
if allowAbbrev {
|
||||
matches = append(matches, wID)
|
||||
} else {
|
||||
abbrevOnly = append(abbrevOnly, wID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if exactMatch != "" {
|
||||
|
|
@ -224,6 +276,16 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
|
|||
}
|
||||
|
||||
if len(matches) == 0 {
|
||||
if !allowAbbrev && len(abbrevOnly) > 0 {
|
||||
// The input matched nothing exactly, but it IS a valid leading-
|
||||
// prefix abbreviation of at least one real issue — telling the
|
||||
// caller "no issue found" here would be false. Report the
|
||||
// truthful reason instead so an exact-only caller (comment.go's
|
||||
// resolveAndGetIssueForMutationExact) can surface an accurate,
|
||||
// actionable message rather than claiming the issue is missing.
|
||||
sort.Strings(abbrevOnly)
|
||||
return "", fmt.Errorf("%w: %q (matches %v)", ErrAbbreviatedIDNotAllowed, input, abbrevOnly)
|
||||
}
|
||||
return "", fmt.Errorf("no issue found matching %q", input)
|
||||
}
|
||||
|
||||
|
|
|
|||
208
internal/utils/id_parser_exact_test.go
Normal file
208
internal/utils/id_parser_exact_test.go
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
//go:build cgo
|
||||
|
||||
package utils_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
// TestResolvePartialIDExact_RejectsAbbreviationAcceptsExact reuses the same
|
||||
// fixture shape as TestResolvePartialID (full/partial/hierarchical/substring
|
||||
// issues) to show ResolvePartialIDExact keeps every exact-match case working
|
||||
// identically to ResolvePartialID, while every leading-prefix-abbreviation
|
||||
// case — which ResolvePartialID happily resolves — now errors instead of
|
||||
// silently picking a candidate.
|
||||
func TestResolvePartialIDExact_RejectsAbbreviationAcceptsExact(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newTestStore(t)
|
||||
|
||||
prefixIssue := &types.Issue{
|
||||
ID: "bd-a3f8e9",
|
||||
Title: "Prefix resolution target",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
plainIssue := &types.Issue{
|
||||
ID: "bd-1",
|
||||
Title: "Plain issue",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, prefixIssue, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.CreateIssue(ctx, plainIssue, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "bd-"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
shouldError bool
|
||||
}{
|
||||
{
|
||||
name: "exact match with prefix still resolves",
|
||||
input: "bd-1",
|
||||
expected: "bd-1",
|
||||
},
|
||||
{
|
||||
name: "exact match without prefix still resolves",
|
||||
input: "1",
|
||||
expected: "bd-1",
|
||||
},
|
||||
{
|
||||
name: "exact full hash still resolves",
|
||||
input: "a3f8e9",
|
||||
expected: "bd-a3f8e9",
|
||||
},
|
||||
{
|
||||
name: "leading-prefix abbreviation now errors (was silently accepted by ResolvePartialID)",
|
||||
input: "a3f8",
|
||||
shouldError: true,
|
||||
},
|
||||
{
|
||||
name: "nonexistent issue still errors",
|
||||
input: "bd-999",
|
||||
shouldError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := utils.ResolvePartialIDExact(ctx, store, tt.input)
|
||||
if tt.shouldError {
|
||||
if err == nil {
|
||||
t.Fatalf("utils.ResolvePartialIDExact(%q) = %q, nil; want error", tt.input, result)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("utils.ResolvePartialIDExact(%q) unexpected error: %v", tt.input, err)
|
||||
}
|
||||
if result != tt.expected {
|
||||
t.Errorf("utils.ResolvePartialIDExact(%q) = %q; want %q", tt.input, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePartialIDExact_Wisp is a direct regression test for the
|
||||
// reported incident: a wisp's stripped hash ("t3st" from "bd-wisp-t3st")
|
||||
// must still resolve exactly (that's a real, deliberate exact-match
|
||||
// convenience — referencing a wisp without typing "wisp-"), but a
|
||||
// leading-prefix abbreviation of that hash ("t3s", or the real incident's
|
||||
// "list" against "list3t0") must now error instead of silently landing on
|
||||
// the wisp.
|
||||
func TestResolvePartialIDExact_Wisp(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newTestStore(t)
|
||||
|
||||
wisp := &types.Issue{
|
||||
ID: "bd-wisp-t3st",
|
||||
Title: "Test wisp",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
Ephemeral: true,
|
||||
}
|
||||
if err := store.CreateIssue(ctx, wisp, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
shouldError bool
|
||||
}{
|
||||
{
|
||||
name: "full wisp ID still resolves exactly",
|
||||
input: "bd-wisp-t3st",
|
||||
expected: "bd-wisp-t3st",
|
||||
},
|
||||
{
|
||||
name: "wisp prefix with full hash still resolves exactly",
|
||||
input: "wisp-t3st",
|
||||
expected: "bd-wisp-t3st",
|
||||
},
|
||||
{
|
||||
name: "bare full hash still resolves exactly (wisp- infix stripped, but hash is complete)",
|
||||
input: "t3st",
|
||||
expected: "bd-wisp-t3st",
|
||||
},
|
||||
{
|
||||
name: "leading-prefix abbreviation of the wisp hash now errors",
|
||||
input: "t3s",
|
||||
shouldError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := utils.ResolvePartialIDExact(ctx, store, tt.input)
|
||||
if tt.shouldError {
|
||||
if err == nil {
|
||||
t.Fatalf("utils.ResolvePartialIDExact(%q) = %q, nil; want error", tt.input, result)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("utils.ResolvePartialIDExact(%q) unexpected error: %v", tt.input, err)
|
||||
}
|
||||
if result != tt.expected {
|
||||
t.Errorf("utils.ResolvePartialIDExact(%q) = %q; want %q", tt.input, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePartialIDExact_ReservedWordDoesNotCollideWithWisp is the exact
|
||||
// shape of the real incident: a wisp whose hash happens to start with a
|
||||
// word a caller might type by accident. Even without the CLI-level
|
||||
// reserved-word guard, ResolvePartialIDExact alone must refuse to resolve
|
||||
// "list" against a wisp hashed "list3t0".
|
||||
func TestResolvePartialIDExact_ReservedWordDoesNotCollideWithWisp(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newTestStore(t)
|
||||
|
||||
wisp := &types.Issue{
|
||||
ID: "bd-wisp-list3t0",
|
||||
Title: "Unrelated wisp (order:dolt-health)",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
Ephemeral: true,
|
||||
}
|
||||
if err := store.CreateIssue(ctx, wisp, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result, err := utils.ResolvePartialIDExact(ctx, store, "list"); err == nil {
|
||||
t.Fatalf(`utils.ResolvePartialIDExact("list") = %q, nil; want "not found" error, not a silent match onto %s`, result, wisp.ID)
|
||||
}
|
||||
|
||||
// Sanity check against the OLD behavior: ResolvePartialID (still the
|
||||
// default for read paths) is documented to resolve this via the leading-
|
||||
// prefix abbreviation branch — confirms the fixture actually reproduces
|
||||
// the incident's collision instead of trivially not matching anything.
|
||||
if result, err := utils.ResolvePartialID(ctx, store, "list"); err != nil || result != wisp.ID {
|
||||
t.Fatalf("fixture sanity check failed: utils.ResolvePartialID(%q) = (%q, %v); want (%q, nil) — the incident's collision did not reproduce", "list", result, err, wisp.ID)
|
||||
}
|
||||
}
|
||||
233
internal/utils/id_parser_fake_test.go
Normal file
233
internal/utils/id_parser_fake_test.go
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
package utils_test
|
||||
|
||||
// Fake, in-memory implementation of utils.PartialIDResolverStore. Unlike the
|
||||
// other tests in this package, this one needs no cgo, no Dolt binary, and no
|
||||
// Docker test container — it exercises ResolvePartialID/ResolvePartialIDExact
|
||||
// against a hand-rolled store, so it can actually run in any environment
|
||||
// (including ones where the Docker-backed newTestStore tests in
|
||||
// id_parser_test.go / id_parser_exact_test.go skip themselves).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
type fakeIssue struct {
|
||||
id string
|
||||
ephemeral bool
|
||||
}
|
||||
|
||||
// fakeResolverStore is a minimal PartialIDResolverStore backed by a plain
|
||||
// slice, replicating just enough of the real store's query semantics for
|
||||
// ResolvePartialID/ResolvePartialIDExact: exact-ID lookup (SearchIssues with
|
||||
// filter.IDs) and substring "LIKE"-style search optionally scoped to
|
||||
// ephemeral issues (SearchIssueIDs).
|
||||
type fakeResolverStore struct {
|
||||
issues []fakeIssue
|
||||
config map[string]string
|
||||
}
|
||||
|
||||
func (f *fakeResolverStore) SearchIssues(_ context.Context, _ string, filter types.IssueFilter) ([]*types.Issue, error) {
|
||||
var out []*types.Issue
|
||||
for _, iss := range f.issues {
|
||||
if len(filter.IDs) > 0 && !containsStr(filter.IDs, iss.id) {
|
||||
continue
|
||||
}
|
||||
out = append(out, &types.Issue{ID: iss.id, Ephemeral: iss.ephemeral})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeResolverStore) SearchIssueIDs(_ context.Context, query string, filter types.IssueFilter) ([]string, error) {
|
||||
var out []string
|
||||
for _, iss := range f.issues {
|
||||
if filter.Ephemeral != nil && iss.ephemeral != *filter.Ephemeral {
|
||||
continue
|
||||
}
|
||||
if query != "" && !strings.Contains(iss.id, query) {
|
||||
continue
|
||||
}
|
||||
out = append(out, iss.id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeResolverStore) GetConfig(_ context.Context, key string) (string, error) {
|
||||
return f.config[key], nil
|
||||
}
|
||||
|
||||
func containsStr(haystack []string, needle string) bool {
|
||||
for _, s := range haystack {
|
||||
if s == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident is a
|
||||
// Docker-free, always-runnable reproduction of a real incident:
|
||||
// "bd comment list <id>" (a typo for "bd comments list") resolved "list"
|
||||
// against a wisp "hq-wisp-list3t0" via leading-prefix abbreviation and wrote
|
||||
// the rest of the command line to it as a comment. It asserts three things
|
||||
// in one place: (1) the fixture genuinely reproduces the old collision via
|
||||
// ResolvePartialID, (2) ResolvePartialIDExact refuses the same input, and
|
||||
// (3) ResolvePartialIDExact still resolves genuinely exact references
|
||||
// (happy path untouched).
|
||||
func TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &fakeResolverStore{
|
||||
issues: []fakeIssue{
|
||||
{id: "hq-wisp-list3t0", ephemeral: true},
|
||||
{id: "hq-165vq", ephemeral: false},
|
||||
},
|
||||
config: map[string]string{"issue_prefix": "hq"},
|
||||
}
|
||||
|
||||
// Sanity check: confirm the fixture reproduces the OLD (still-default,
|
||||
// still-correct-for-read-paths) fuzzy behavior before asserting the fix.
|
||||
gotFuzzy, err := utils.ResolvePartialID(ctx, store, "list")
|
||||
if err != nil || gotFuzzy != "hq-wisp-list3t0" {
|
||||
t.Fatalf("fixture sanity check failed: ResolvePartialID(%q) = (%q, %v); want (%q, nil) — incident did not reproduce",
|
||||
"list", gotFuzzy, err, "hq-wisp-list3t0")
|
||||
}
|
||||
|
||||
// The fix: the write-path resolver must refuse the same input instead of
|
||||
// silently landing on the unrelated wisp. Asserting errors.Is (not just
|
||||
// err != nil) pins the WISP branch's abbrevOnly tracking specifically:
|
||||
// without it, "list" still fails (via the generic "no issue found"
|
||||
// fallback), so a regression that silently drops the wisp-branch
|
||||
// abbrevOnly candidate — reintroducing this exact incident's false
|
||||
// not-found — would pass this test undetected.
|
||||
if got, err := utils.ResolvePartialIDExact(ctx, store, "list"); err == nil {
|
||||
t.Fatalf(`ResolvePartialIDExact("list") = (%q, nil); want a "not found" error, not a silent match onto hq-wisp-list3t0`, got)
|
||||
} else if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
t.Fatalf(`ResolvePartialIDExact("list") error = %v; want errors.Is(err, ErrAbbreviatedIDNotAllowed) — "list" IS a valid leading-prefix abbreviation of hq-wisp-list3t0, so the error must say so truthfully, not fall back to a generic "no issue found"`, err)
|
||||
}
|
||||
|
||||
// Happy path: an id that genuinely, exactly names an issue must still
|
||||
// resolve under the exact-only resolver.
|
||||
if got, err := utils.ResolvePartialIDExact(ctx, store, "hq-165vq"); err != nil || got != "hq-165vq" {
|
||||
t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil)", "hq-165vq", got, err, "hq-165vq")
|
||||
}
|
||||
if got, err := utils.ResolvePartialIDExact(ctx, store, "165vq"); err != nil || got != "hq-165vq" {
|
||||
t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil) — bare full hash must still resolve exactly", "165vq", got, err, "hq-165vq")
|
||||
}
|
||||
if got, err := utils.ResolvePartialIDExact(ctx, store, "hq-wisp-list3t0"); err != nil || got != "hq-wisp-list3t0" {
|
||||
t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil) — full wisp id must still resolve exactly", "hq-wisp-list3t0", got, err, "hq-wisp-list3t0")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePartialIDExact_AbbreviationRefusalIsDistinguishableFromNotFound
|
||||
// is a Docker-free regression test for the follow-up steveyegge's PR #5393
|
||||
// review flagged (item c): an abbreviation that DOES match a real issue must
|
||||
// error differently from an input that matches nothing at all, because "no
|
||||
// issue found matching %q" is false in the first case — the issue exists,
|
||||
// only the abbreviation was refused. Exact-only callers (bd comment) use
|
||||
// errors.Is(err, ErrAbbreviatedIDNotAllowed) to tell the two apart and give a
|
||||
// truthful, actionable message instead of claiming the issue is missing.
|
||||
func TestResolvePartialIDExact_AbbreviationRefusalIsDistinguishableFromNotFound(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &fakeResolverStore{
|
||||
issues: []fakeIssue{
|
||||
{id: "hq-a3f8e9", ephemeral: false},
|
||||
},
|
||||
config: map[string]string{"issue_prefix": "hq"},
|
||||
}
|
||||
|
||||
// A real, valid leading-prefix abbreviation of an existing issue: must
|
||||
// wrap ErrAbbreviatedIDNotAllowed, not a plain "not found".
|
||||
got, err := utils.ResolvePartialIDExact(ctx, store, "a3f8")
|
||||
if err == nil {
|
||||
t.Fatalf(`ResolvePartialIDExact("a3f8") = (%q, nil); want an ErrAbbreviatedIDNotAllowed error — "a3f8" is a real abbreviation of hq-a3f8e9`, got)
|
||||
}
|
||||
if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
t.Errorf(`ResolvePartialIDExact("a3f8") error = %q; want it to wrap ErrAbbreviatedIDNotAllowed (errors.Is)`, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "no issue found matching") {
|
||||
t.Errorf(`ResolvePartialIDExact("a3f8") error = %q; must NOT claim "no issue found" — hq-a3f8e9 exists`, err)
|
||||
}
|
||||
|
||||
// An input that matches nothing at all, not even via abbreviation: must
|
||||
// stay a plain not-found, and must NOT wrap ErrAbbreviatedIDNotAllowed —
|
||||
// proves the two failure modes are genuinely distinguishable, not just
|
||||
// differently worded copies of the same check.
|
||||
got, err = utils.ResolvePartialIDExact(ctx, store, "zzzzzz")
|
||||
if err == nil {
|
||||
t.Fatalf(`ResolvePartialIDExact("zzzzzz") = (%q, nil); want a not-found error`, got)
|
||||
}
|
||||
if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
t.Errorf(`ResolvePartialIDExact("zzzzzz") error = %q; want a plain not-found, not ErrAbbreviatedIDNotAllowed — nothing matches "zzzzzz" even via abbreviation`, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "no issue found matching") {
|
||||
t.Errorf(`ResolvePartialIDExact("zzzzzz") error = %q; want the genuine "no issue found matching" wording`, err)
|
||||
}
|
||||
|
||||
// Sanity: the exact id still resolves under the same store/config,
|
||||
// confirming the fixture didn't accidentally break the happy path.
|
||||
if got, err := utils.ResolvePartialIDExact(ctx, store, "hq-a3f8e9"); err != nil || got != "hq-a3f8e9" {
|
||||
t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil)", "hq-a3f8e9", got, err, "hq-a3f8e9")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePartialIDExact_RefusesSentinelTokens pins where #6215's bare-
|
||||
// sentinel guard has to live once this PR splits the resolver in two.
|
||||
//
|
||||
// #6215 (base) refuses "null"/"undefined"/"none"/"nil"/"" before any lookup,
|
||||
// and put that guard in ResolvePartialID because it was then the only
|
||||
// ID-resolution entry point in the repository. This PR adds a second one,
|
||||
// ResolvePartialIDExact, so the guard belongs in the shared resolvePartialID
|
||||
// body — which is what keeps #6215's own stated guarantee ("bd update null,
|
||||
// bd comment null and every other command that resolves an ID now fail before
|
||||
// any lookup") true for the comment write paths this PR routes through the
|
||||
// exact-only resolver.
|
||||
//
|
||||
// Nothing else covers that: #6215's id_parser_sentinel_test.go exercises only
|
||||
// ResolvePartialID, so leaving the guard in the exported wrapper alone keeps
|
||||
// every one of its assertions green while a sentinel reaching the exact path
|
||||
// degrades into an ErrAbbreviatedIDNotAllowed that names an unrelated decoy
|
||||
// issue — telling the caller to "use the full id" for a token that is really
|
||||
// just their selector having matched nothing.
|
||||
func TestResolvePartialIDExact_RefusesSentinelTokens(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
// hq-null3t0 is #6215's own decoy shape: a real issue whose hash begins
|
||||
// with "null", so an unguarded sentinel is a live abbreviation match here
|
||||
// rather than a plain not-found.
|
||||
store := &fakeResolverStore{
|
||||
issues: []fakeIssue{
|
||||
{id: "hq-null3t0", ephemeral: false},
|
||||
{id: "hq-165vq", ephemeral: false},
|
||||
},
|
||||
config: map[string]string{"issue_prefix": "hq"},
|
||||
}
|
||||
|
||||
for _, input := range []string{"null", "NULL", " null ", "undefined", "none", "nil", "", " "} {
|
||||
got, err := utils.ResolvePartialIDExact(ctx, store, input)
|
||||
if err == nil {
|
||||
t.Errorf("ResolvePartialIDExact(%q) = (%q, nil); want #6215's sentinel refusal", input, got)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(err.Error(), "refusing") {
|
||||
t.Errorf("ResolvePartialIDExact(%q) error = %q; want #6215's sentinel refusal (guard did not fire on the exact path)", input, err)
|
||||
}
|
||||
if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
t.Errorf("ResolvePartialIDExact(%q) error = %q; a tooling sentinel must be refused as such, not reported as a refused abbreviation of hq-null3t0", input, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "hq-null3t0") {
|
||||
t.Errorf("ResolvePartialIDExact(%q) error = %q; must not name the decoy issue", input, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Over-refusal guard, the twin of #6215's accepted-inputs test: an id that
|
||||
// merely CONTAINS a sentinel token must still resolve exactly.
|
||||
for _, input := range []string{"hq-null3t0", "null3t0"} {
|
||||
if got, err := utils.ResolvePartialIDExact(ctx, store, input); err != nil || got != "hq-null3t0" {
|
||||
t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil) — the guard must match the whole token, not a prefix", input, got, err, "hq-null3t0")
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue