beads/cmd/bd/flags.go
Isis Anisoptera 45a116d1a7
fix(update): fence unforced --notes overwrites behind --force across all surfaces (#5946)
* fix(update): fence unforced --notes overwrites behind --force across all surfaces

bd update --notes silently replaced existing notes, destroying handoff
history. The contract now refuses an unforced overwrite of non-empty
notes with ErrNotesOverwrite (409 notes_overwrite_refused over HTTP,
force_notes_overwrite to override), enforced inside the mutation
transaction on both the dolt and uow backends, for single updates and
batch apply alike. CAS guards keep precedence: a stale
--if-assignee/--if-status still surfaces as the exit-13 mismatch, on
both backends, before the fence speaks.

CLI: --force and --if-assignee are no longer mutually exclusive (that
exclusion made overwriting under a guard impossible); both update
routes translate the fence's sentinel into the same actionable advice
(--force to overwrite, --append-notes to preserve history), and the
post---force warning is worded as an audit statement. The shipped
plugin skill docs and bd note help now prescribe --append-notes for
handoffs instead of the newly fenced bare --notes.

The fence is the single enforcement point: no client-side pre-read
copies of the rule. Conformance contracts, unit tests for
AuthorizeNotesOverwrite, and embedded/proxied/httpapi regression
coverage included.

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

* fix(update): exempt explicit clears from the notes fence; share its predicate

CI surfaced three gaps in the fence's reach:

- Clearing notes (--notes "" / patch.notes: "") was refused, diverging
  from every sibling text field's clear and from the backend behavior
  contracts. The fence now targets only its actual footgun — replacing
  non-empty notes with different non-empty content — via a single shared
  predicate, issueops.NotesReplacement, used by both the contract's
  AuthorizeNotesOverwrite and the CLI's warning path, so the two can no
  longer drift. Prose updated to match everywhere the rule is stated
  (ErrNotesOverwrite, ForceNotesOverwrite, OpenAPI spec + regenerated
  types).
- The revision-CAS integration tests' incidental concurrent writes now
  patch design instead of notes, so they no longer depend on notes-fence
  semantics at all.
- The historical-upgrade harness deliberately replaces fixture notes and
  asserts the new value; its two bd update --notes calls now pass
  --force.

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

* fix(update): address review — changelog BREAKING entry, problem.go doc block, close-policy-under-guard test

Review follow-ups on #5946 (bee-ghosttrack, MERGE-AFTER-FIXES):

- CHANGELOG: BREAKING entry under [Unreleased] ### Changed for the notes
  fence on both wires (CLI exit 1, HTTP 409 notes_overwrite_refused), with
  the --force / --append-notes migration line. It also names the two
  deliberate edges: the explicit-clear exemption, and --force widening to
  the close-policy half under --if-assignee now that the flag pair is legal.
- problem.go: CodeNotesOverwrite's comment had landed inside
  CodeDependencyCycle's doc block; each const now sits under its own docs.
- assign_fence_embedded_test.go: pin the previously untested close-policy
  half of --force under --if-assignee (refused unforced, authorized forced).

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

* test(update): align TestWarnNotesReplacement with the post-fence warning copy

The test landed on main after this branch was cut and pins the pre-fence
wording, where the warning fired on any unforced overwrite. Since the fence,
an unforced overwrite is refused outright and warnNotesReplacement fires only
after a forced one — the audit trail for a habitual --force — so the copy it
pins is now '--force replaced existing notes'.

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

* docs(import): record bd import's notes-fence exemption as by-design (GH#6190)

Import consults none of the per-field live-state fences — notes overwrite,
live-claim reassign, close policy — and that is the intended shape, not an
omission: its contract is wholesale row replacement, guarded by its own
staleness check (only strictly-newer rows rewrite local state, --allow-stale
is the single deliberate-overwrite opt-in) and reported field-by-field in
updated_issues. Named in AuthorizeNotesOverwrite's enforcement-boundary
comment and in bd import's help; the published CLI docs pick the help text
up at the next release pin bump.

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

* fix(update): refuse --notes "" and add --clear-notes; stop --notes help reading as additive

GH#6021: an empty --notes wiped the whole notes field at exit 0 behind the
same ✓ Updated receipt as a successful write — and the empty string is
exactly what a dead command substitution collapses to. The empty value is
now refused on both CLI routes (the accident and the deliberate clear are
the same bytes at the flag layer), and the deliberate clear gets its own
verb, --clear-notes, mutually exclusive with --notes/--append-notes. A verb
rather than the proposed --allow-empty-notes opt-in: what needs authorizing
is an intent, not an input path — --allow-empty-description unblocks
stdin/file plumbing, which notes does not have — and an opt-in passed
habitually would silently disarm the guard while a habitual --clear-notes
fails loudly. --force does not bypass the refusal; the fence's clear
exemption stands, so the verb alone authorizes the erase. The HTTP API is
unchanged: patch.notes "" still clears.

GH#6272: bd update --help called --notes "Additional notes" and the prime
text said "Add supplementary notes" — both read as appending, so agents
following the injected guidance faithfully clobbered prior context. The
update help now names the operation with the --append-notes contrast at the
point of use, the shared/create help is field-named like --description and
--design, and the prime line points at bd update --append-notes.

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

* fix(bazel): enumerate the PR-new files in cmd/bd and issueops srcs

The base added cmd/bd/BUILD.bazel and internal/storage/issueops/BUILD.bazel
with EXPLICIT srcs lists after this branch was cut, so the three files this
PR adds were never enumerated:

  cmd/bd/update_notes_guard.go        (go_library bd_lib)
  cmd/bd/update_notes_guard_test.go   (go_test bd_test)
  internal/storage/issueops/aggregate_authorize_notes_test.go (go_test)

The go_library omission is a hard build break, not a silent skip:
update.go:215,220 and update_input.go:106,111 are enumerated and call
validateNotesUpdate / clearNotesRequested, so //cmd/bd:bd_lib compiles the
callers without the callee. bazel.yml arms unconditionally for fork PRs
(head.repo.fork == true) and builds //cmd/bd:bd + //cmd/bd:bd_test, so this
reds the lane. make bazel-sync-check cannot see it -- go_srcs.py only
validates the glob-based go_srcs filegroup, never the rule srcs lists.

Generated by make bazel-sync (gazelle), not hand-edited, so the workflow's
own BUILD-files-in-sync drift step agrees byte-for-byte.

* fix(notes): name --clear-notes in bd note's rm guidance, correct the fence boundary comment, pin both request-shape rules

Takes all three non-gating minors from the review. No behavior change: two
prose fixes and two test cases.

1. cmd/bd/note.go's rm|remove|delete branch advised
   `bd update <id> --notes "text" --force` under "To change or clear notes",
   but clearing through --notes is exactly what this PR made impossible --
   validateNotesUpdate refuses an empty value unconditionally and --force does
   not reach it. The branch now names both verbs separately: --notes --force to
   replace, --clear-notes to clear. The edit and update branches speak only of
   replacing and were already correct, so they are untouched.

2. aggregate.go's enforcement-boundary comment claimed the UpdateIssueInTx
   funnel's "one notes-replacing caller is bd edit". Under this PR's own
   NotesReplacement predicate there are at least four more (bd note's
   read-combine-write, bd defer --reason, bd rename and delete-tombstoning's
   mechanical ID rewrites, bd compact's clears). The exemption is still sound --
   every funnel writer derives its new value from the current notes -- so the
   comment now names those CLASSES instead of a single caller, which is the
   claim that is actually true and that a future fence auditor can check.

3. Both branches this PR adds to ValidateUpdateRequest were uncovered: the
   batch apply leg reaches them here and nowhere else, while the single-issue
   HTTP handler's own pre-check returns before storage. Added a sibling table
   (the existing one varies only the patch; these two rules are properties of
   the REQUEST) with a case each. Mutation-checked, disjoint: neutralizing the
   force-without-notes branch reds only the first case, neutralizing the
   notes+append branch reds only the second, and the pre-existing
   canonical-fields table stays green under both.

Not an amend of 5ffcc9c16c: that commit's message states it was generated by
make bazel-sync and not hand-edited, so folding hand-written Go into it would
falsify the claim its own BUILD-files-in-sync argument rests on. No new files,
so the srcs lists it repaired stay correct.

---------

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

338 lines
12 KiB
Go

package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/spf13/cobra"
)
// registerCommonIssueFlags registers flags common to create and update commands.
func registerCommonIssueFlags(cmd *cobra.Command) {
cmd.Flags().StringP("assignee", "a", "", "Assignee")
cmd.Flags().StringP("description", "d", "", "Issue description")
cmd.Flags().String("body", "", "Alias for --description (GitHub CLI convention)")
_ = cmd.Flags().MarkHidden("body") // Hidden alias for agent/CLI ergonomics
cmd.Flags().StringP("message", "m", "", "Alias for --description (git commit convention)")
_ = cmd.Flags().MarkHidden("message") // Hidden alias for muscle memory from git commit -m
cmd.Flags().String("body-file", "", "Read description from file (use - for stdin)")
cmd.Flags().String("description-file", "", "Alias for --body-file")
_ = cmd.Flags().MarkHidden("description-file") // Hidden alias
cmd.Flags().Bool("stdin", false, "Read description from stdin (alias for --body-file -)")
cmd.MarkFlagsMutuallyExclusive("stdin", "body-file")
cmd.MarkFlagsMutuallyExclusive("stdin", "description-file")
cmd.MarkFlagsMutuallyExclusive("stdin", "description")
cmd.MarkFlagsMutuallyExclusive("stdin", "body")
cmd.MarkFlagsMutuallyExclusive("stdin", "message")
cmd.Flags().String("design", "", "Design notes")
cmd.Flags().String("design-file", "", "Read design from file (use - for stdin)")
cmd.MarkFlagsMutuallyExclusive("design", "design-file")
cmd.Flags().String("acceptance", "", "Acceptance criteria")
// Field-named like --description and --design — no merge behavior implied
// (GH#6272: "Additional notes" read as additive while update replaces the
// field; update overrides this usage string with the operational contrast).
cmd.Flags().String("notes", "", "Notes")
cmd.Flags().String("append-notes", "", "Append to existing notes (with newline separator)")
cmd.Flags().String("external-ref", "", "External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)")
}
// getDescriptionFlag retrieves the description value, checking --body-file, --description-file,
// --description, and --body (in that order of precedence).
// Supports reading from stdin via --description=- or --body=- (useful when description
// contains apostrophes or other characters that are hard to escape in shell).
// Returns the value, whether any flag was explicitly changed, and any error.
func getDescriptionFlag(cmd *cobra.Command) (string, bool, error) {
if stdinFlag, _ := cmd.Flags().GetBool("stdin"); stdinFlag {
content, err := readBodyFile("-")
if err != nil {
return "", false, HandleError("reading from stdin: %v", err)
}
return content, true, nil
}
bodyFileChanged := cmd.Flags().Changed("body-file")
descFileChanged := cmd.Flags().Changed("description-file")
descChanged := cmd.Flags().Changed("description")
bodyChanged := cmd.Flags().Changed("body")
messageChanged := cmd.Flags().Changed("message")
if bodyFileChanged && descFileChanged {
bodyFile, _ := cmd.Flags().GetString("body-file")
descFile, _ := cmd.Flags().GetString("description-file")
if bodyFile != descFile {
return "", false, HandleError("cannot specify both --body-file and --description-file with different values")
}
}
if bodyFileChanged || descFileChanged {
var filePath string
if bodyFileChanged {
filePath, _ = cmd.Flags().GetString("body-file")
} else {
filePath, _ = cmd.Flags().GetString("description-file")
}
if descChanged || bodyChanged || messageChanged {
return "", false, HandleError("cannot specify both --body-file and --description/--body/--message")
}
content, err := readBodyFile(filePath)
if err != nil {
return "", false, HandleError("reading body file: %v", err)
}
return content, true, nil
}
desc, _ := cmd.Flags().GetString("description")
body, _ := cmd.Flags().GetString("body")
message, _ := cmd.Flags().GetString("message")
if desc == "-" || body == "-" || message == "-" {
values := make(map[string]string)
if descChanged {
values["--description"] = desc
}
if bodyChanged {
values["--body"] = body
}
if messageChanged {
values["--message"] = message
}
if len(values) > 1 {
var firstVal string
for _, v := range values {
if firstVal == "" {
firstVal = v
} else if v != firstVal {
fmt.Fprintf(os.Stderr, "Error: cannot specify multiple description flags with different values\n")
for flag, val := range values {
fmt.Fprintf(os.Stderr, " %s: %q\n", flag, val)
}
return "", false, SilentExit()
}
}
}
content, err := readBodyFile("-")
if err != nil {
return "", false, HandleError("reading from stdin: %v", err)
}
return content, true, nil
}
changedCount := 0
var firstVal string
var firstFlag string
if descChanged {
changedCount++
firstVal = desc
firstFlag = "--description"
}
if bodyChanged {
changedCount++
if firstVal == "" {
firstVal = body
firstFlag = "--body"
} else if body != firstVal {
fmt.Fprintf(os.Stderr, "Error: cannot specify both %s and --body with different values\n", firstFlag)
fmt.Fprintf(os.Stderr, " %s: %q\n", firstFlag, firstVal)
fmt.Fprintf(os.Stderr, " --body: %q\n", body)
return "", false, SilentExit()
}
}
if messageChanged {
changedCount++
if firstVal == "" {
firstVal = message
firstFlag = "--message"
} else if message != firstVal {
fmt.Fprintf(os.Stderr, "Error: cannot specify both %s and --message with different values\n", firstFlag)
fmt.Fprintf(os.Stderr, " %s: %q\n", firstFlag, firstVal)
fmt.Fprintf(os.Stderr, " --message: %q\n", message)
return "", false, SilentExit()
}
}
if descChanged {
return desc, true, nil
}
if bodyChanged {
return body, true, nil
}
if messageChanged {
return message, true, nil
}
return desc, descChanged, nil
}
// getDesignFlag retrieves the design value from --design-file or --design.
// Returns the value, whether any flag was explicitly changed, and any error.
func getDesignFlag(cmd *cobra.Command) (string, bool, error) {
if cmd.Flags().Changed("design-file") {
path, _ := cmd.Flags().GetString("design-file")
content, err := readBodyFile(path)
if err != nil {
return "", false, HandleError("reading from stdin: %v", err)
}
return content, true, nil
}
if cmd.Flags().Changed("design") {
v, _ := cmd.Flags().GetString("design")
return v, true, nil
}
return "", false, nil
}
// readBodyFile reads the description content from a file.
// If filePath is "-", reads from stdin.
func readBodyFile(filePath string) (string, error) {
var reader io.Reader
if filePath == "-" {
reader = os.Stdin
} else {
// #nosec G304 - filePath comes from user flag, validated by caller
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
reader = file
}
content, err := io.ReadAll(reader)
if err != nil {
return "", fmt.Errorf("failed to read file: %w", err)
}
return string(content), nil
}
// textSources names the places a command can take body text from: stdin, a
// file path, an explicit text flag, then positional args. A non-nil stdin
// means --stdin was given. flagName names the text flag (e.g. "--response")
// in conflict errors and always accompanies flagText. flagSet marks the text
// flag as explicitly passed (cobra's Changed), so an empty flag value still
// counts as a source — like a blank positional — rather than as absent.
type textSources struct {
stdin io.Reader
filePath string
flagText string
flagName string
flagSet bool
positional []string
}
// textFromSources resolves body text from the single provided source: stdin,
// file path, flag value, or positional args joined with spaces. Combining any
// two sources is an error rather than a silent drop of one of them — commands
// normally reject flag combinations earlier via registerTextSourceFlags'
// mutual exclusion, and the error here keeps a command that forgets that
// registration from silently ignoring a source. Blank positional tokens and
// an explicitly-set-but-empty text flag never resolve to text, but still
// count as provided — the user attempted to pass text (e.g. an empty "$VAR"),
// so an empty result is "cannot be empty" rather than "no source provided".
// Trailing newlines (including CRLF) are trimmed from stdin — shells append
// one (echo, heredocs) — while file content is passed through verbatim like
// every other file-input flag. Returns "" with provided=false when no source
// is given at all.
func textFromSources(src textSources) (text string, provided bool, err error) {
type source struct {
name string
resolve func() (string, error)
}
var sources []source
if positional := strings.Join(src.positional, " "); strings.TrimSpace(positional) != "" {
sources = append(sources, source{fmt.Sprintf("positional text %q", positional), func() (string, error) {
return positional, nil
}})
}
if src.stdin != nil {
sources = append(sources, source{"--stdin", func() (string, error) {
content, err := io.ReadAll(src.stdin)
if err != nil {
return "", fmt.Errorf("reading from stdin: %w", err)
}
return strings.TrimRight(string(content), "\r\n"), nil
}})
}
if src.filePath != "" {
sources = append(sources, source{"--file", func() (string, error) {
// Verbatim, like every other file-input flag (--body-file,
// --design-file, --reason-file): a file is a deliberate payload,
// so its trailing newlines are preserved.
return readBodyFile(src.filePath)
}})
}
if src.flagSet || src.flagText != "" {
sources = append(sources, source{src.flagName, func() (string, error) {
return src.flagText, nil
}})
}
provided = len(sources) > 0 || len(src.positional) > 0
switch len(sources) {
case 0:
return "", provided, nil
case 1:
text, err = sources[0].resolve()
return text, provided, err
default:
names := make([]string, len(sources))
for i, s := range sources {
names[i] = s.name
}
return "", provided, fmt.Errorf("cannot combine %s", strings.Join(names, " with "))
}
}
// cmdTextSources builds textSources from a command's --stdin and --file
// flags (either may be unregistered) plus its positional text args. Callers
// with a command-specific text flag fill in flagText/flagName themselves.
func cmdTextSources(cmd *cobra.Command, positional []string) textSources {
src := textSources{positional: positional}
if stdinFlag, _ := cmd.Flags().GetBool("stdin"); stdinFlag {
src.stdin = os.Stdin
}
src.filePath, _ = cmd.Flags().GetString("file")
return src
}
// registerTextSourceFlags registers the shared text-source flags — --stdin
// and --file, read back by name in cmdTextSources — and marks them mutually
// exclusive with each other and with any command-specific text flags (e.g.
// "response", registered by the caller beforehand). noun names the text in
// the flag help (e.g. "comment text").
func registerTextSourceFlags(cmd *cobra.Command, noun string, textFlags ...string) {
cmd.Flags().Bool("stdin", false, "Read "+noun+" from stdin")
cmd.Flags().String("file", "", "Read "+noun+" from file")
cmd.MarkFlagsMutuallyExclusive(append([]string{"stdin", "file"}, textFlags...)...)
}
// requireTextFromSources resolves body text like textFromSources and owns the
// shared empty-text policy: text from an explicit source must be non-blank
// ("<noun> cannot be empty"), and with no source at all the error lists the
// command's accepted sources via hint (e.g. "use positional args, --stdin, or
// --file").
func requireTextFromSources(noun, hint string, src textSources) (string, error) {
text, provided, err := textFromSources(src)
if err != nil {
return "", err
}
if strings.TrimSpace(text) != "" {
return text, nil
}
if provided {
return "", fmt.Errorf("%s cannot be empty", noun)
}
return "", fmt.Errorf("no %s provided (%s)", noun, hint)
}
// registerPriorityFlag registers the priority flag with a specific default value.
func registerPriorityFlag(cmd *cobra.Command, defaultVal string) {
cmd.Flags().StringP("priority", "p", defaultVal, "Priority (0-4 or P0-P4, 0=highest)")
}