beads/cmd/bd/create_input.go
Robin Carswell 543e44aef8
fix(labels): normalize labels on write, and warn when one contains a space (#5812) (#5813)
* fix(labels): normalize labels on write, as read paths already do (#5812)

bd applies utils.NormalizeLabels (trim, drop empty, dedupe) to every label
FILTER path -- list, search, ready, orphans, count and the workapi
equivalents -- but to no label WRITE path.

That asymmetry stores labels no filter can match:

    bd create "T" --labels 'theme:a, theme:b'   # stores "theme:a", " theme:b"
    bd list --label theme:b                     # filter trims -- no match

--labels 'a, b' is the comma-space form most people type, and pflag's CSV
split leaves the leading space on the second element, so the split looks
like it worked. A filtered list that is silently short is
indistinguishable from a complete one.

Two more everyday inputs corrupt just as quietly: --labels 'a,,b' stores
an empty label, and --labels 'a,a' stores the same label twice.

Apply the existing helper on the write paths so write and read agree:
create (--labels and its --label alias, normalized after merging the two
so dedupe spans both), quick, and update (--add-label, --remove-label,
--set-labels). --remove-label matters as much as the additive flags: an
untrimmed ' theme:a' fails to match the stored label and silently removes
nothing. The --set-labels '' clear-all signal is preserved -- it is gated
on pointer identity, not slice length.

Also add a warn-only 'Label Whitespace' doctor check, since the write-path
fix does nothing for labels already stored and nothing else surfaces them.
It reports leading/trailing and blank labels only. A label whose trimmed
form still contains whitespace is deliberately not reported: that turns on
what a space between labels should mean, which this change does not
settle, and "good first issue" is a legitimate multi-word label.

Not auto-fixable by design -- trimming a damaged label can collide with a
correct label already on the same issue, which needs a human decision.

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

* feat(labels): warn when a stored label contains a space (#5812)

A label containing a space is almost always a comma that was meant and
missed. That is the failure behind #5812's evidence: 150 corrupt label
rows across 111 issues, found months later only because theme-by-theme
counts failed to reconcile.

The issue proposed splitting labels on whitespace as well as commas. This
deliberately does NOT do that, and the reasoning is worth recording.

A shell has exactly one mechanism for "is this one word or two", and it is
already unambiguous. All three of these send ONE argument:

    bd create T --labels 'one two'
    bd create T --labels "one two"
    bd create T --labels one\ two

They are byte-identical by the time bd sees them: quoting and backslash-
escaping are consumed by the shell, which reports only the resulting word
boundaries. It is the same mechanism that makes 'cd my\ dir' work.

Splitting on whitespace would therefore override a boundary the caller has
already explicitly set, making labels the one place on the command line
where quoting does not mean what it means everywhere else. It is also
undoable: with splitting there is no way left to ask for a label containing
a space except a second, nested layer of quotes. And it cannot deliver what
it appears to promise, since 'one two' and "one two" are indistinguishable
by the time any code could act on them.

So honor the shell's boundaries, which bd already does, and warn instead:

    ⚠ Stored "theme:a theme:b" as ONE label — it contains a space.
      If you meant several labels, separate them with commas (a,b) or
      repeat the flag.

The 150 rows would have produced 150 warnings at the keystroke, while
--labels 'good first issue' still does exactly what it says. A warning
rather than an error, because a space-containing label is a legitimate
thing to ask for and the shell has just been used to ask for it; --quiet
silences it. No command changes meaning.

Applied to the paths that write labels: create, q, --add-label and
--set-labels. Deliberately not --remove-label, because removing a
space-containing label is how the damage gets repaired and warning on the
repair is noise.

The Label Whitespace doctor check gains a matching third class so an
existing database can find the ones already in it. It is reported
separately from the untrimmed/blank classes and is not called corruption:
bd cannot tell "good first issue" from a missed comma, so it surfaces them
and a human decides.

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

* fix(labels): close the last raw label write, bd tag (#5812)

Review feedback on #5813. `bd tag` describes itself as "Shorthand for
'bd update <id> --add-label <label>'" and was not: update normalizes and warns,
tag passed the positional straight to AddLabel, and the proxied route passed it
to ApplyLabelPatch, which drops "" but does not trim.

Verified on a scratch DB against binaries built either side of this commit:

  before: bd tag t-fap ' theme:spaced' -> stored " theme:spaced"
          bd list --label theme:spaced -> 0 rows
  after:  bd tag t-wjz ' theme:spaced' -> stored "theme:spaced"
          bd list --label theme:spaced -> 1 row

That is the unfilterable class this PR set out to close, written by the command
whose help text promises equivalence with the one that already closed it.

Normalization happens in tag.go BEFORE the route split, so the direct and
proxied paths cannot diverge on it; runTagProxiedServer now takes the resolved
id and label rather than raw args, which removes the second entry point.

A whitespace-only label is refused (exit 1) rather than dropped. The plural
flags can discard an empty element and still honor the rest of the request;
bd tag has exactly one label to add, so dropping it would report success having
written nothing.

Also here, both from the same review:

- `bd label add` now warns too. splitLabelArg already trimmed, so it never
  stored the untrimmed class, but it could not tell a caller that
  `bd label add bd-1 'theme:a theme:b'` is ONE label. Verified firing.
- docs/core-concepts/labels.md: says plainly that import and batch ingest are
  deliberately NOT normalized (round-trip fidelity; the doctor check is what
  finds legacy damage), so the next reader does not "fix" it. Also notes that
  bare `bd doctor` is not yet supported in embedded mode (GH#3794), so the new
  Label Whitespace check reaches classic and server-mode databases only --
  "run bd doctor" was overselling to embedded users.
- CHANGELOG entries under Fixed and Added.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Steve Yegge <steve.yegge@gmail.com>
2026-08-20 08:08:24 -07:00

367 lines
12 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/timeparsing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
)
type createInput struct {
markdownFile string
graphFile string
title string
explicitID string
parentID string
issueType string
status string
priority int
assignee string
externalRef string
specID string
description string
design string
acceptanceCriteria string
notes string
appendNotes string
labels []string
noInheritLabels bool
deps []string
waitsFor string
waitsForGate string
waitsForGateSet bool // true when --waits-for-gate was explicitly passed (not relying on default)
silent bool
dryRun bool
force bool
validate bool
ephemeral bool
noHistory bool
molType types.MolType
wispType types.WispType
eventCategory string
eventActor string
eventTarget string
eventPayload string
dueAt *time.Time
deferUntil *time.Time
metadata json.RawMessage
metadataSet bool
estimatedMinutes *int
repoOverride string
repoOverrideSet bool
createdBy string
owner string
jsonOutput bool
validationMode string
}
// graphApplyOptions projects the plan-wide CLI flags into the options every
// graph validation/materialization helper takes.
func (in createInput) graphApplyOptions() GraphApplyOptions {
return GraphApplyOptions{Ephemeral: in.ephemeral, NoHistory: in.noHistory, Force: in.force}
}
// graphApplyOptionsFromFlags is the embedded-path projection of the plan-wide
// flags, delegating to graphApplyOptions so both transports share one
// flags→options mapping (the embedded create path reads flags directly
// rather than through gatherCreateInput).
func graphApplyOptionsFromFlags(cmd *cobra.Command) GraphApplyOptions {
var in createInput
in.ephemeral, _ = cmd.Flags().GetBool("ephemeral")
in.noHistory, _ = cmd.Flags().GetBool("no-history")
in.force, _ = cmd.Flags().GetBool("force")
return in.graphApplyOptions()
}
func gatherCreateInput(cmd *cobra.Command, args []string) (createInput, error) {
in := createInput{}
in.markdownFile, _ = cmd.Flags().GetString("file")
in.graphFile, _ = cmd.Flags().GetString("graph")
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
if in.markdownFile != "" && in.graphFile != "" {
return in, HandleError("cannot specify both --file and --graph")
}
if in.markdownFile != "" {
if len(args) > 0 {
return in, HandleError("cannot specify both title and --file flag")
}
if in.dryRun {
return in, HandleError("--dry-run is not supported with --file flag")
}
if err := rejectSingleIssueFlagsForMarkdown(cmd); err != nil {
return in, err
}
}
if in.graphFile != "" {
if len(args) > 0 {
return in, HandleError("cannot specify both title and --graph flag")
}
if err := rejectSingleIssueFlagsForGraph(cmd); err != nil {
return in, err
}
}
in.silent, _ = cmd.Flags().GetBool("silent")
in.force, _ = cmd.Flags().GetBool("force")
in.validate, _ = cmd.Flags().GetBool("validate")
in.noInheritLabels, _ = cmd.Flags().GetBool("no-inherit-labels")
in.ephemeral, _ = cmd.Flags().GetBool("ephemeral")
in.noHistory, _ = cmd.Flags().GetBool("no-history")
if in.ephemeral && in.noHistory {
return in, HandleError("--ephemeral and --no-history are mutually exclusive")
}
titleFlag, _ := cmd.Flags().GetString("title")
title, err := resolveTitle(args, titleFlag, in.markdownFile, in.graphFile)
if err != nil {
return in, err
}
in.title = title
desc, descChanged, err := getDescriptionFlag(cmd)
if err != nil {
return in, err
}
if err := validateDescriptionUpdate(cmd, desc, descChanged); err != nil {
return in, HandleError("%v", err)
}
in.description = desc
skills, _ := cmd.Flags().GetString("skills")
if skills != "" {
if in.description != "" {
in.description += "\n\n"
}
in.description += "## Required Skills\n" + skills
}
ctxStr, _ := cmd.Flags().GetString("context")
if ctxStr != "" {
if in.description != "" {
in.description += "\n\n"
}
in.description += "## Context\n" + ctxStr
}
design, _, err := getDesignFlag(cmd)
if err != nil {
return in, err
}
in.design = design
in.acceptanceCriteria, _ = cmd.Flags().GetString("acceptance")
in.notes, _ = cmd.Flags().GetString("notes")
in.appendNotes, _ = cmd.Flags().GetString("append-notes")
in.specID, _ = cmd.Flags().GetString("spec-id")
if in.markdownFile == "" && in.graphFile == "" {
if in.description == "" && !isTestIssue(in.title) {
if config.GetBool("create.require-description") {
return in, HandleError("description is required (set create.require-description: false in config.yaml to disable)")
}
}
}
priorityStr, _ := cmd.Flags().GetString("priority")
priority, err := validation.ValidatePriority(priorityStr)
if err != nil {
return in, HandleError("%v", err)
}
in.priority = priority
in.issueType, _ = cmd.Flags().GetString("type")
in.status, _ = cmd.Flags().GetString("status")
in.assignee, _ = cmd.Flags().GetString("assignee")
in.externalRef, _ = cmd.Flags().GetString("external-ref")
in.explicitID, _ = cmd.Flags().GetString("id")
in.parentID, _ = cmd.Flags().GetString("parent")
in.waitsFor, _ = cmd.Flags().GetString("waits-for")
in.waitsForGate, _ = cmd.Flags().GetString("waits-for-gate")
in.waitsForGateSet = cmd.Flags().Changed("waits-for-gate")
if in.explicitID != "" && in.parentID != "" {
return in, HandleError("cannot specify both --id and --parent flags")
}
in.labels, _ = cmd.Flags().GetStringSlice("labels")
labelAlias, _ := cmd.Flags().GetStringSlice("label")
if len(labelAlias) > 0 {
in.labels = append(in.labels, labelAlias...)
}
// Normalize after merging the alias so dedupe spans both flags. Read paths
// (list, search, ready, orphans) already do this; without it here, `--labels
// 'a, b'` stores " b" with pflag's leading space and can never match its own
// filter.
in.labels = utils.NormalizeLabels(in.labels)
warnLabelsContainingWhitespace(in.labels)
in.deps, _ = cmd.Flags().GetStringSlice("deps")
in.repoOverride, _ = cmd.Flags().GetString("repo")
in.repoOverrideSet = cmd.Flags().Changed("repo")
if molTypeStr, _ := cmd.Flags().GetString("mol-type"); molTypeStr != "" {
mt := types.MolType(molTypeStr)
if !mt.IsValid() {
return in, HandleError("invalid mol-type %q (must be %s)", molTypeStr, types.ValidMolTypeNames())
}
in.molType = mt
}
if wispTypeStr, _ := cmd.Flags().GetString("wisp-type"); wispTypeStr != "" {
wt := types.WispType(wispTypeStr)
if !wt.IsValid() {
return in, HandleError("invalid wisp-type %q (must be %s)", wispTypeStr, types.ValidWispTypeNames())
}
in.wispType = wt
}
in.eventCategory, _ = cmd.Flags().GetString("event-category")
in.eventActor, _ = cmd.Flags().GetString("event-actor")
in.eventTarget, _ = cmd.Flags().GetString("event-target")
in.eventPayload, _ = cmd.Flags().GetString("event-payload")
if (in.eventCategory != "" || in.eventActor != "" || in.eventTarget != "" || in.eventPayload != "") && in.issueType != "event" {
return in, HandleError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event")
}
if dueStr, _ := cmd.Flags().GetString("due"); dueStr != "" {
t, err := timeparsing.ParseRelativeTime(dueStr, time.Now())
if err != nil {
return in, HandleError("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr)
}
in.dueAt = &t
}
if deferStr, _ := cmd.Flags().GetString("defer"); deferStr != "" {
t, err := timeparsing.ParseRelativeTime(deferStr, time.Now())
if err != nil {
return in, HandleError("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr)
}
if t.Before(time.Now()) && !in.silent && !debug.IsQuiet() {
fmt.Fprintf(os.Stderr, "%s Defer date %q is in the past. Issue will appear in bd ready immediately.\n",
ui.RenderWarn("!"), t.Local().Format("2006-01-02 15:04"))
fmt.Fprintf(os.Stderr, " Did you mean a future date? Use --defer=+1h or --defer=tomorrow\n")
}
in.deferUntil = &t
}
if cmd.Flags().Changed("metadata") {
metadataValue, _ := cmd.Flags().GetString("metadata")
var metadataJSON string
if strings.HasPrefix(metadataValue, "@") {
filePath := metadataValue[1:]
// #nosec G304 -- user explicitly provides file path via @file.json syntax
data, err := os.ReadFile(filePath)
if err != nil {
return in, HandleError("failed to read metadata file %s: %v", filePath, err)
}
metadataJSON = string(data)
} else {
metadataJSON = metadataValue
}
if !json.Valid([]byte(metadataJSON)) {
return in, HandleError("invalid JSON in --metadata: must be valid JSON")
}
in.metadata = json.RawMessage(metadataJSON)
in.metadataSet = true
}
if cmd.Flags().Changed("estimate") {
est, _ := cmd.Flags().GetInt("estimate")
if est < 0 {
return in, HandleError("estimate must be a non-negative number of minutes")
}
in.estimatedMinutes = &est
}
in.createdBy = getActorWithGit()
in.owner = getOwner()
in.jsonOutput = jsonOutput
in.validationMode = config.GetString("validation.on-create")
if in.validate {
in.validationMode = "error"
}
return in, nil
}
var singleIssueOnlyFlags = []string{
"title",
"id", "parent", "no-inherit-labels",
"deps", "waits-for", "waits-for-gate",
"type", "priority", "assignee", "external-ref", "spec-id",
"status",
"description", "body", "message", "body-file", "description-file", "stdin",
"design", "design-file", "acceptance", "notes", "append-notes",
"allow-empty-description",
"labels", "label", "skills", "context",
"event-category", "event-actor", "event-target", "event-payload",
"due", "defer",
"metadata", "estimate", "wisp-type",
}
func rejectSingleIssueFlagsForMarkdown(cmd *cobra.Command) error {
for _, name := range singleIssueOnlyFlags {
if cmd.Flags().Changed(name) {
return HandleError("--%s is not valid with --file (markdown templates supply per-issue fields)", name)
}
}
// --force is plan-wide for --graph (foreign-prefix explicit IDs) but the
// markdown path never consults it, so reject it here rather than accept
// and silently ignore.
if cmd.Flags().Changed("force") {
return HandleError("--force is not valid with --file (markdown templates supply per-issue fields)")
}
return nil
}
func rejectSingleIssueFlagsForGraph(cmd *cobra.Command) error {
for _, name := range singleIssueOnlyFlags {
if cmd.Flags().Changed(name) {
return HandleError("--%s is not valid with --graph (graph plans supply per-node fields)", name)
}
}
if cmd.Flags().Changed("mol-type") {
return HandleError("--mol-type is not valid with --graph (set mol_type per node in the plan instead)")
}
return nil
}
func resolveTitle(args []string, titleFlag, markdownFile, graphFile string) (string, error) {
if markdownFile != "" || graphFile != "" {
return "", nil
}
var title string
switch {
case len(args) > 0 && titleFlag != "":
if args[0] != titleFlag {
return "", HandleError("cannot specify different titles as both positional argument and --title flag\n Positional: %q\n --title: %q", args[0], titleFlag)
}
title = args[0]
case len(args) > 0:
if strings.HasPrefix(args[0], "-") {
return "", HandleError("title %q looks like a flag (starts with '-').\n Run 'bd create --help' for available options.\n To use this title anyway, pass it explicitly: bd create --title=%q", args[0], args[0])
}
title = args[0]
case titleFlag != "":
title = titleFlag
default:
return "", HandleError("title required (or use --file to create from markdown)")
}
if strings.TrimSpace(title) == "" {
return "", HandleError("title cannot be empty or whitespace-only")
}
return title, nil
}