beads/cmd/bd/comments.go
Athos Bernardes ab9adc73db
Refuse reserved words and fuzzy id matches on bd comment writes (#5393)
* Refuse reserved words and fuzzy id matches on bd comment writes

bd comment <id> [text...] treated its first argument as an id via the
same abbreviation-tolerant resolver used everywhere else, with no
protection against the id slot holding something that was never meant
to be an id. Two related failure modes came from that:

- "bd comment list <id>", a typo for "bd comments list" (or "bd
  comments <id>"), silently ran with id="list" and text="<id>" instead
  of erroring.
- If "list" (or any other stray first word) happened to be a
  leading-prefix abbreviation of some unrelated issue's hash, the
  resolver picked that issue and the comment landed there instead of
  failing with "not found". This is exactly what happened in
  production: 15+ automated sessions made the "bd comment list <id>"
  typo over two days, and because "list" was a leading-prefix
  abbreviation of an unrelated wisp's hash ("list3t0"), every one of
  them wrote a garbage comment onto that wisp.

Fixes both, independently:

- checkCommentIDNotReservedWord rejects list/add/rm/delete as the id
  argument before any resolution is attempted, mirroring the existing
  "bd comments list" misplaced-subcommand guard.
- ResolvePartialIDExact (internal/utils) is an exact-match sibling of
  ResolvePartialID: identical exact-ID and exact-hash matching
  (including a wisp's hash with its "wisp-" infix stripped), but never
  falls through to leading-prefix abbreviation matching. bd comment
  now resolves through this via a new resolveAndGetIssueForMutationExact,
  which keeps the existing cross-rig prefix-routing and contributor
  auto-routing fallbacks intact (tightened to exact matching too) so
  cross-repo comment writes by full id are unaffected.

Every other caller of the touched shared functions (ResolvePartialID,
resolveAndGetIssueForMutation, resolveViaPrefixRoutingWithAccess,
resolveViaAutoRouting) keeps its exact current behavior — the new exact
variants are additive, and existing call sites were updated to pass an
explicit "false" for the new parameter rather than changing behavior.

Testing: go build/go vet pass across the whole module. The new pure-Go
guard test and a hand-rolled in-memory PartialIDResolverStore test both
run and pass without Docker or a live Dolt server, and the latter
reproduces the original collision (ResolvePartialID) before asserting
the fix (ResolvePartialIDExact) in the same test, so the fixture is
proven to exercise the real failure mode rather than trivially passing.
The Dolt-container-backed table tests (mirroring the existing
TestResolvePartialID_Wisp / TestResolvePartialID suites) could not be
run locally (no Docker in this environment) — they compile and skip
cleanly the same way the pre-existing suite does, and will run for real
in CI.

* fix(ga-wpdum): address steveyegge's PR #5393 review items b/c/d

Review (2026-08-07, posted as a PR comment, not a formal GitHub review —
hence reviewDecision stayed empty) asked for four things before merge; (a)
rebase onto #5369 was already done (2026-09-07, see PR history). This
addresses the rest:

(c) MAJOR — comment writes require an exact id, but a REAL abbreviated id
was refused with "no issue found matching %q", which is false: the issue
exists, only the abbreviation was rejected. ResolvePartialIDExact now
distinguishes the two failure modes via a new sentinel,
ErrAbbreviatedIDNotAllowed, wrapped only when the input would have resolved
via leading-prefix abbreviation. bd comment's RunE checks errors.Is against
it and returns a truthful, actionable message pointing at `bd show <id>`
instead of claiming the issue is missing. Docs (hash-ids.md) and CHANGELOG
updated with the read/write carve-out this creates.

(b) MAJOR — investigated whether the proxied-server comment path needed the
same exact-match treatment. It doesn't: resolveCommentTargetProxied resolves
via workapi.GetIssueOrWisp with the raw id, which bottoms out in
issueSQLRepositoryImpl.Get's plain "WHERE id = ?" — SQL exact equality, with
no abbreviation-matching layer anywhere in that call chain (unlike the
embedded path's utils.ResolvePartialID). Comment writes over the proxied
server were already exact-id-only before this PR. Per the review's own
fallback ("extend exact matching to that path, or document/test the gap
explicitly"), added a regression test locking this in rather than leaving it
implicit.

(d) Added CLI-level (cobra-dispatch, in-process rootCmd.Execute) tests for:
  - "rm"/"delete" reserved-word rejection, the two words the #5369-inherited
    tests don't cover (only "list"/"add" have hand-written cases).
  - The new (c) abbreviation-refusal message end-to-end, including a
    same-abbreviation sanity check against `bd show` to prove it's a real,
    resolvable abbreviation and not a fixture accident.
Plus a Docker-free fake-store test in internal/utils pinning
ErrAbbreviatedIDNotAllowed's distinguishability from a genuine not-found.

Fixed in the same pass, same class of defect as (c): checkCommentIDNotReservedWord's
message claimed every reserved word is a "misplaced bd comments subcommand" —
true for "list"/"add", false for "rm"/"delete" (no such subcommand exists;
bd has "delete" as a top-level command and "rm" as an alias elsewhere, e.g.
"dep rm"). Message now says "reserved word" generically, true for all four.

Testing: go vet (plain and -tags=integration) clean on cmd/bd and
internal/utils. go test ./internal/utils/... passes including the new
ErrAbbreviatedIDNotAllowed test. go test ./cmd/bd/. (non-integration tag)
passes including both reserved-word cases. The new CLI-level and
proxied-server integration tests need a Dolt test container (Docker) this
environment doesn't have — same limitation the original commit's own
Dolt-backed tests already disclosed; they compile clean under
-tags=integration and skip cleanly the same way the pre-existing suite does.

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

* fix(ga-wpdum): address bee-ghosttrack's R1 review (M1 + the flagged MINOR)

R1 (aec6de4ad, REQUEST-CHANGES) found that CHANGELOG.md and hash-ids.md
claim `bd comments add` is guarded against abbreviated ids and reserved
words exactly like `bd comment`, but the code never extended the guard
to the plural form — `commentsAddCmd` had no Args validator and resolved
through the abbreviation-tolerant `resolveAndGetIssueForMutation`. Per
the reviewer's preferred fix (option ii), extend the guard instead of
softening the docs:

- Add `validateCommentsAddArgs` (mirrors `comment`'s `validateCommentArgs`
  minus the singular/plural-confusion special cases) and wire it as
  `commentsAddCmd.Args`, so a reserved-word id is refused before either
  dispatch branch.
- Switch the embedded-path resolution from `resolveAndGetIssueForMutation`
  to `resolveAndGetIssueForMutationExact`, with the same
  `errors.Is(ErrAbbreviatedIDNotAllowed)` truthful-message mapping
  `comment` already has. (The proxied path already resolved exactly —
  it shares `addCommentProxied`/`resolveCommentTargetProxied` with
  `comment` — so this closes the embedded-path gap only.)
- Update the one pre-existing test that asserted the old, now-removed
  behavior (`PartialIDWithCommentsAdd` expected a genuine abbreviation to
  succeed) to assert the refusal instead, and add a CLI-level regression
  test mirroring `TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage`.
- Add `TestValidateCommentsAddArgs`, a pure Args-validator unit test
  (no store/Docker needed) mirroring `TestValidateCommentArgs`.

Also treats the one MINOR the review flagged as an actual gap (not just
a suggestion): the wisp-branch abbrevOnly tracking in id_parser.go had no
test pinning it — P3 (making the wisp-branch abbrevOnly append a no-op)
went uncaught. Strengthened
TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident's "list"
assertion from a bare `err != nil` to `errors.Is(err,
ErrAbbreviatedIDNotAllowed)`, which is exactly the incident's own shape
in the wisp branch.

CI (PR Core / wrapper timing) is failing on this branch, but independently
confirmed pre-existing and unrelated: `ci-pr-core.sh` runs `go test -race
./...` with no `-timeout` override, so cmd/bd (a large package under
-race) hits Go's default 10-minute per-package ceiling; same-hour green
runs on other PRs measured 11-13.5 min total job time, already at the
edge, and the actively-running test at the deadline
(TestWhereCommand_ReadsPrefixFromEmbeddedStore) is unrelated to this
diff. R1 independently measured the same thing (541.6s/387.0s on other
green runs vs. 600.9s here). Needs a green re-run, not a code fix.

Verified locally (no Docker in this environment, so the two integration-
tagged CLI tests above compile-check clean via `go vet -tags=integration,
gms_pure_go` but run as SKIP rather than PASS; will run for real in CI):
- go build ./...; go vet ./cmd/bd/ ./internal/utils/: clean
- go vet -tags=integration,gms_pure_go ./cmd/bd/: clean
- gofmt -l on all 4 changed/added files: clean
- go test ./internal/utils/... -run ResolvePartialID: PASS
- go test ./cmd/bd/. -run 'TestValidateCommentsAddArgs|TestValidateCommentArgs|TestCheckCommentIDNotReservedWord': PASS

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

* fix(ga-wpdum): address bee-ghosttrack's R2 review (dead-red fixture + cobra-dispatch wiring test)

R2 (a639234a0, CHANGES_REQUESTED): TestCLI_CommentsAddShortID/PartialIDWithCommentsAdd
was dead-red in its own setup — it only truncated the fixture hash to a
4-char abbreviation when len(hash) > 4, but fresh test DBs mint 3-char
hashes (min_hash_length unset), so shortID always equaled the full hash
and the t.Fatalf guard fired before any of the subtest's real assertions
ran. That meant mutation P-B (reverting comments.go's exact resolver back
to the abbreviation-tolerant one) went uncaught.

Fix: derive the abbreviation as a strict, one-character-shorter leading
prefix of the real hash (hash[:len(hash)-1]), the same derivation
comment_proxied_integration_test.go already uses — correct regardless of
fixture hash length, with a length>=2 guard instead of the old
always-true-in-practice one.

Also closes R2's recommended "NEW MINOR — the guard's wiring is
untested": comments_add_test.go drives validateCommentsAddArgs directly
(catches a gutted body, mutation P-C) but nothing exercised
commentsAddCmd's Args field through real cobra dispatch, so unwiring it
back to cobra.MinimumNArgs(1) left every test green (mutation P-D). Added
TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch, which runs
`bd comments add <reserved-word> ...` through actual rootCmd.Execute()
dispatch for all four reserved words and asserts the bystander issue
receives no comment.

Not touched, per R2: the carried-over m1 (cross-rig abbreviation error
message) — reviewer marked "Not a blocker" — and the CI race-default
timeout on cmd/bd, already diagnosed (R2 + prior PR comment) as
pre-existing infra flakiness needing a fresh run, not a code change.

Verified in this environment (no Docker/testcontainers available, same
disclosed limitation as prior rounds): gofmt clean; go vet -tags=integration
./cmd/bd/... clean (requires CGO_CPPFLAGS/CGO_LDFLAGS/PKG_CONFIG_PATH
pointed at the keg-only icu4c@78 install); go test -tags=integration
-run 'TestCLI_CommentsAddShortID|TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch'
./cmd/bd/ -v passes with all Dolt-backed subtests skipping cleanly
(Docker not available) rather than panicking — confirms both tests compile
and execute up to the container-availability skip. The actual fixture-hash
logic under test only runs where a Dolt container exists (CI); it has not
been exercised against a real container here.

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

* chore(bazel): enumerate the PR's 4 new test files in BUILD.bazel (adopt-pr rebase gate)

Base added cmd/bd/BUILD.bazel and internal/utils/BUILD.bazel enumerates
go_test srcs explicitly, so PR #5393's four new test files were unlisted.
Output of 'make bazel-sync' (gazelle + go_srcs.py + mod tidy), verbatim and
idempotent. Measured: the unrepaired //internal/utils:utils_test binary lists
0 of the PR's 5 TestResolvePartialIDExact* tests while still building green
(a fake green); repaired it lists 5/5.

* fix(review): surface a routed-tier abbreviation refusal on comment writes

Review-loop fixup for PR #5393 (iteration 1). The review approved with no
required changes; these are the non-gating minor plus one of the two nits,
taken because the minor is a user-visible false message on this PR's own
headline contract.

[minor] Contract & Interface Fidelity. resolveAndGetIssueForMutationExact
passes exact=true to all three tiers, so the cross-rig and auto-routed tiers
can mint utils.ErrAbbreviatedIDNotAllowed too -- and both wrappers propagate it
unwrapped (routed.go:303-305) -- but each routed error was bound inside an `if`
statement and discarded, and `return nil, err` returned the LOCAL error. The
consumers' errors.Is (comment.go:158, comments.go:238) was therefore
structurally unable to observe a routed-tier refusal, so `bd comment hr-8wn
"text"` printed `no issue found matching "hr-8wn"` for an issue a routed rig
demonstrably holds -- the exact falsehood the sentinel's own doc condemns, at
the caller that doc names (internal/utils/id_parser.go:33). Both tiers' errors
are now captured and the first abbreviation refusal is returned in preference to
the local not-found. The wrong write was already refused on every tier; only
the message contract was unmet.

The new pin cmd/bd/comment_routed_exact_test.go drives the real seam (local
town store + routed rig + routes.jsonl, mirroring
TestCheckBeadGateCrossRigPrefixRoute) in both directions, because either
assertion alone passes for the wrong reason: an abbreviation of a routed issue
must select the ROUTED refusal, and an id absent everywhere must stay a plain
not-found. Proven non-vacuous by mutation -- dropping only the selection reds
direction 1 with `no issue found matching "gt-abcdefg"`, the original symptom
verbatim, while direction 2 still passes.

[nit] Test Evidence Quality. The proxied regression test asserted only
strings.Contains(stdout+stderr, id), which passes identically on the false and
the truthful message and so locked the local/proxied message asymmetry in where
the suite could not see it. It now asserts the whole message (verified
empirically: `Error: issue pa-2u not found`) and empty stdout, matching the
exact-message norm of the sibling missing-ID subtest. The asymmetry itself is
deliberate and stays: the proxied route resolves through one exact
`WHERE id = ?` and cannot distinguish an abbreviation of a real issue from an
absent id without adding back the abbreviation probing this PR exists to remove
from write paths.

[nit] Release Safety -- DECLINED, measured. The prescribed `### Changed` bullet
belongs at the top of the first `### Changed` block in `## [Unreleased]` (base
CHANGELOG.md:383), and main has since inserted its own bullet at exactly that
anchor (`@@ -384,0 +492,16`, the #6111 entry). Adding it would mint a second
CHANGELOG add/add conflict for the finalize base-refresh on top of the
`### Fixed` re-conflict already predicted by the rebase gate -- not worth it for
an optional nit whose own text says "No code change".

cmd/bd/BUILD.bazel gains one srcs row for the new test file (via make
bazel-sync, a no-op on a second run) so bazel.yml's "BUILD files in sync" gate
stays clean.

Validation: go build ./... rc 0; go vet ./cmd/bd/ ./internal/utils/ rc 0; gofmt
clean; git diff --check clean; cmd/bd selectors 11/11 PASS including base's own
TestMatchPrefixRoute (the GH#5048 longest-prefix union guard) and
TestResolveCloseTargets (the abbreviation-tolerant sibling path);
TestProxiedServerComment 3/3 under BEADS_TEST_PROXIED_SERVER=1.

* test(utils): pin #6215's sentinel guard to the shared resolver (#5393 base refresh)

Rebasing this PR onto current main (e7138e93af -> a1ac9f4dcb, 27 commits) hit
two conflicts. Both are recorded in .gc/reviews/<root>/base-refresh-repair.md;
this commit carries the one piece of the repair that is not simply a replayed
contributor hunk.

The substantive conflict was internal/utils/id_parser.go against ab88b20517
(#6215, "refuse a bare jq/JS sentinel ... as an issue ID", which itself says
Refs #5393). Both sides ADD at the same point -- the diff3 ancestor section is
empty -- so nothing base-owned is rewritten, and the only question is WHERE
#6215's guard lands now that this PR splits the resolver into ResolvePartialID
(abbreviation-tolerant) and ResolvePartialIDExact (exact-only) over a shared
resolvePartialID.

It belongs in the shared body. #6215 put it in ResolvePartialID only because
that was then the repository's single ID-resolution entry point ("One guard
covers the direct, embedded and proxied-server paths uniformly"); this PR adds
a second. Its changelog entry on main states the guarantee directly -- "bd
update null, bd comment null and every other command that resolves an ID now
fail before any lookup, because the guard sits in the shared resolver" -- and
bd comment is precisely what this PR routes through the exact-only path. The
relocation costs no patch delta: the guard re-anchors as unchanged context
after the PR's insertion, so the content-line diff of (old base..old head) vs
(new base..new head) is empty, and the PR's stat is 16 files +1212/-31 before
and after.

Nothing covered that choice, which is why this test exists. #6215's own
id_parser_sentinel_test.go exercises only ResolvePartialID, so the naive
textual resolution -- guard left in the exported wrapper -- keeps every one of
its assertions green while a sentinel reaching the exact path degrades into
`id is a valid abbreviation, but exact-match resolution is required here:
"null" (matches [hq-null3t0])`: it names an unrelated decoy issue and tells
the caller to use the full id, when in truth their selector matched nothing.

Mutation-proved in both directions: with the guard moved into the wrapper
alone, #6215's two tests still PASS and this test FAILs; with the guard deleted
outright, #6215's refusal test and this one both FAIL (so neither is vacuous).
The over-refusal arm mirrors #6215's accepted-inputs test through the exact
path, so hq-null3t0 and the bare hash null3t0 must still resolve.

No new file, so no BUILD.bazel srcs row is owed. 61 PASS / 0 FAIL / 0 SKIP for
-run 'Sentinel|ResolvePartialID' against a real Dolt container.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 05:04:32 -07:00

340 lines
10 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"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"
)
// validateCommentsArgs runs as cobra's Args validation for the parent
// "comments" command, which executes before PersistentPreRunE opens the
// store (or runs migrations) and before RunE's usesProxiedServer() dispatch.
// The parent command only lists comments for a single issue, so any trailing
// positional arg is a mistake — most commonly the swapped-order add,
// `bd comments <id> add <text>`, which otherwise falls through, reads only
// args[0], and silently drops the rest with exit 0 (GH#4642). Validating
// here (rather than inside RunE, local-store-only) rejects the malformed
// invocation identically for the direct and proxied-server paths, before
// either one can open a store, run a migration, or hit the remote-migrate
// gate for an invocation that is guaranteed to fail.
func validateCommentsArgs(cmd *cobra.Command, args []string) error {
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
return err
}
if len(args) <= 1 {
return nil
}
issueID := args[0]
if args[1] == "add" {
return HandleErrorRespectJSON(`"bd comments <issue-id> add ..." is not valid — the subcommand must come first.
To add a comment, run:
bd comments add <issue-id> <text>
Example:
bd comments add %s "your comment"
See: bd comments --help`, issueID)
}
return HandleErrorRespectJSON(`"bd comments" takes a single issue id and lists its comments.
To list comments:
bd comments <issue-id>
To add a comment:
bd comments add <issue-id> <text>
See: bd comments --help`)
}
var commentsCmd = &cobra.Command{
Use: "comments [issue-id]",
GroupID: "issues",
Short: "View or manage comments on an issue",
Long: `View or manage comments on an issue.
Examples:
# List all comments on an issue (issue id is required — there is no "comments list")
bd comments bd-123
# List comments in JSON format
bd comments bd-123 --json
# Add a comment
bd comments add bd-123 "This is a comment"
# Add a comment from a file
bd comments add bd-123 -f notes.txt`,
Args: validateCommentsArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("comments")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if usesProxiedServer() {
return runCommentsProxiedServer(cmd, rootCtx, args)
}
localTime, _ := cmd.Flags().GetBool("local-time")
issueID := args[0]
if err := ensureStoreActive(); err != nil {
return HandleErrorRespectJSON("getting comments: %v", err)
}
ctx := rootCtx
result, err := resolveAndGetIssueWithRouting(ctx, store, issueID)
if err != nil {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
}
if result == nil || result.Issue == nil {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("issue %s not found", issueID)
}
defer result.Close()
issueID = result.ResolvedID
comments, err := result.Store.GetIssueComments(ctx, issueID)
if err != nil {
return HandleErrorRespectJSON("getting comments: %v", err)
}
if comments == nil {
comments = make([]*types.Comment, 0)
}
if jsonOutput {
return outputJSON(comments)
}
if len(comments) == 0 {
fmt.Printf("No comments on %s\n", issueID)
return nil
}
fmt.Printf("\nComments on %s:\n\n", issueID)
for _, comment := range comments {
ts := comment.CreatedAt
if localTime {
ts = ts.Local()
}
fmt.Printf("[%s] at %s\n", comment.Author, ts.Format("2006-01-02 15:04"))
rendered := uimd.RenderMarkdown(comment.Text)
for _, line := range strings.Split(strings.TrimRight(rendered, "\n"), "\n") {
fmt.Printf(" %s\n", line)
}
fmt.Println()
}
return nil
},
}
var commentsMisplacedListCmd = &cobra.Command{
Use: "list",
Short: "Invalid — use bd comments <issue-id> to list comments",
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
return HandleErrorRespectJSON(`"bd comments list" is not valid.
To list comments on an issue, run:
bd comments <issue-id>
Example:
bd comments bd-123
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",
Long: `Add a comment to an issue.
Examples:
# Add a comment
bd comments add bd-123 "Working on this now"
# Add a comment from a file
bd comments add bd-123 -f notes.txt`,
Args: validateCommentsAddArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("comment add")
evt := metrics.NewCommandEvent("comments-add")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
issueID := args[0]
commentText, err := requireTextFromSources("comment text", "use positional args or -f to read from file",
cmdTextSources(cmd, args[1:]))
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
author, _ := cmd.Flags().GetString("author")
if author == "" {
author = getActorWithGit()
}
// Dispatched after the text is resolved so both backends read the
// same sources and report the same conflicts.
if usesProxiedServer() {
return runCommentsAddProxiedServer(rootCtx, issueID, author, commentText)
}
if err := ensureStoreActive(); err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
ctx := rootCtx
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 {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("issue %s not found", issueID)
}
defer result.Close()
issueID = result.ResolvedID
comment, err := addCommentDirect(ctx, result.Store, issueID, author, commentText)
if err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
if err := commitPendingIfEmbedded(ctx, result.Store, actor, doltAutoCommitParams{
Command: "comments add",
IssueIDs: []string{issueID},
}); err != nil {
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
return outputJSON(comment)
}
fmt.Printf("Comment added to %s\n", issueID)
return nil
},
}
// addCommentDirect appends one comment through the Commenter role and returns
// the stored comment. It is the direct-route sibling of addCommentProxied and
// builds the SAME request, so the two front doors ask the storage layer one
// question.
//
// The role is reached through the STORE's own accessor, never a constructor:
// that accessor is where the store's decorator stack — hooks, telemetry — adds
// its layer, so a comment written here fires the same hook a comment written
// through the provider does. The store is the caller's rather than the global
// one, because a prefix-routed write has to reach the role through the store
// that actually holds the issue.
//
// The RESOLVE stays with the caller. On this route it is fuzzy, prefix-routed
// and cross-repo, none of which belongs on a contract an unattended client also
// calls, and the caller has already produced the canonical id. The role runs
// the issue-then-wisp fallback itself, so the comment lands on the plane the id
// actually names.
//
// The auto-commit policy is applied HERE rather than by each caller. The role
// creates its Dolt version commit inside the storage layer, so
// `--dolt-auto-commit batch` can only defer it by saying so on the context —
// the reason issueOpsContext exists — and a caller that forgets writes exactly
// the per-write commit batch mode is there to avoid. Both comment commands come
// through this function, so the policy is stated once.
func addCommentDirect(ctx context.Context, st storage.DoltStorage, issueID, author, text string) (*types.Comment, error) {
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return nil, err
}
commenter, err := st.Commenter()
if err != nil {
return nil, err
}
result, err := commenter.AddComment(opsCtx, issueops.AddCommentRequest{
Author: author,
IssueID: issueID,
Text: text,
})
if err != nil {
return nil, err
}
return result.Comment, nil
}
func init() {
commentsCmd.AddCommand(commentsMisplacedListCmd)
commentsCmd.AddCommand(commentsAddCmd)
commentsCmd.Flags().Bool("local-time", false, "Show timestamps in local time instead of UTC")
commentsAddCmd.Flags().StringP("file", "f", "", "Read comment text from file")
commentsAddCmd.Flags().StringP("author", "a", "", "Add author to comment")
// Issue ID completions
commentsCmd.ValidArgsFunction = issueIDCompletion
commentsAddCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(commentsCmd)
}
func isUnknownOperationError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "unknown operation")
}