* fix(metadata): require a JSON object for --metadata on create and update (#6035) Root cause: the four --metadata entry points (create and update, each in its direct and proxied-server variant: create.go, create_input.go, update.go, update_input.go) carried copies of the same check, json.Valid, which accepts any JSON value. `bd create --metadata '"oops"'` therefore stored a bare string (or an array, number or null) as the issue's metadata. `bd update` with the same value was refused only late, by the storage-layer merge, with an internal unmarshal error. Fix: one shared readMetadataFlag helper resolves the value (inline or @file.json) and requires a top-level JSON object, refusing a string, number, boolean, array or null with "invalid --metadata: must be a JSON object such as {"key":"value"}, got <kind>". The rule matches what the storage merge already enforces for update (it unmarshals into a map and rejects null), so `{}` stays accepted and null is now refused on create too, where it used to be stored literally. The storage layer is not changed. Not changed: an object whose value is a string that looks like JSON (`{"mykey":"{\"inner\":\"v\"}"}`, the nested case in the report) is still accepted and stored as written. Metadata values are opaque, and refusing such strings would be a design change, not a fix. Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(metadata): cover boolean and null in the end-to-end create/update case (#6743 review) Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(metadata): correct the null-behavior claims and the --metadata help text (#6743 review) Maintainer review fixups for #6743. The review found no blocker and no major, and the scorecard approved with no required changes; these are its minors and nits. - The helper doc comment and the CHANGELOG entry both said the new object rule matches what the storage merge already enforced for update. That holds for a string, number, boolean or array, and is false for null: json.Unmarshal of the literal null into a map zeroes the map and returns no error, so MergeMetadataJSON merged nothing and `bd update --metadata null` exited 0. Refusing null is a real, if small, behavior change on update, so both surfaces now say that instead of claiming a non-change. - The --metadata help text on create and update advertised "JSON string", the one input this change exists to refuse; both now read "JSON object". The generated CLI docs are deliberately not regenerated alongside it: docs/cli-docs.pin is v1.2.2, so generate-cli-docs.sh builds bd from that tag rather than from the checkout, and the committed pages are refreshed at release. Verified both ways -- with this edit alone, check-doc-flags.sh Check 4 reports "PASS: generated CLI docs are fresh"; hand-editing docs/cli-reference/create.md to the new string instead makes it report "FAIL: docs/cli-reference is out of sync with live CLI help". - The `object == nil` arm of the guard is load-bearing and read as redundant to both reviewers, so it now says out loud that it is what catches null, and names internal/httpapi/batch_apply.go as the source of the idiom. Keeping the unmarshal rather than switching the guard to jsonKind preserves symmetry with that plane; the synthesis offered either. - jsonKind's "empty input" arm is unreachable from both callers, which sit behind json.Valid. Documented as defensive rather than dropped, because dropping it makes the byte index below panic for any future caller that has not validated first. - os.ReadFile's error is wrapped with %w, so callers of this newly shared helper can still reach fs.ErrNotExist. The PR body asserts the same null premise in two places (its `null` table row and the "keeps update's existing rule" bullet) and overstates HTTP-plane enforcement; those are corrected at finalize, since review iterations do not touch GitHub. No behavior change beyond the help string. `go test ./cmd/bd -run GH6035` passes; gofmt, go vet, check-doc-flags.sh and check-doc-freshness.sh clean. --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
314 lines
10 KiB
Go
314 lines
10 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"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 updateInput struct {
|
|
fields map[string]any
|
|
addLabels []string
|
|
removeLabels []string
|
|
setLabels *[]string
|
|
reparent *string
|
|
claim bool
|
|
appendNotes string
|
|
hasAppendNotes bool
|
|
setMetadata []string
|
|
unsetMetadata []string
|
|
mergeMetadataIn json.RawMessage
|
|
clearDeferStatus bool
|
|
// bd-wsqvw conditional-update guards; non-nil only when the flag was
|
|
// explicitly passed (a pointer to "" is the real "expected unassigned"
|
|
// guard).
|
|
ifAssignee *string
|
|
ifStatus *string
|
|
// bd-98s5c: --force bypasses the live-claim reassign fence (mutually
|
|
// exclusive with --if-assignee at the flag-group level).
|
|
force bool
|
|
}
|
|
|
|
func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, error) {
|
|
in := &updateInput{fields: map[string]any{}}
|
|
|
|
if cmd.Flags().Changed("status") {
|
|
status, _ := cmd.Flags().GetString("status")
|
|
if err := validateUpdateStatus(ctx, status); err != nil {
|
|
return nil, err
|
|
}
|
|
in.fields["status"] = status
|
|
if status == "closed" {
|
|
session, _ := cmd.Flags().GetString("session")
|
|
if session == "" {
|
|
session = os.Getenv("CLAUDE_SESSION_ID")
|
|
}
|
|
if session != "" {
|
|
in.fields["closed_by_session"] = session
|
|
}
|
|
}
|
|
}
|
|
if cmd.Flags().Changed("priority") {
|
|
priorityStr, _ := cmd.Flags().GetString("priority")
|
|
priority, err := validation.ValidatePriority(priorityStr)
|
|
if err != nil {
|
|
return nil, HandleErrorRespectJSON("%v", err)
|
|
}
|
|
in.fields["priority"] = priority
|
|
}
|
|
if cmd.Flags().Changed("title") {
|
|
title, _ := cmd.Flags().GetString("title")
|
|
title = strings.TrimSpace(title)
|
|
if title == "" {
|
|
return nil, HandleErrorRespectJSON("title cannot be empty")
|
|
}
|
|
in.fields["title"] = title
|
|
}
|
|
if cmd.Flags().Changed("assignee") {
|
|
assignee, _ := cmd.Flags().GetString("assignee")
|
|
in.fields["assignee"] = assignee
|
|
}
|
|
in.force, _ = cmd.Flags().GetBool("force")
|
|
description, descChanged, err := getDescriptionFlag(cmd)
|
|
if err != nil {
|
|
return nil, HandleErrorRespectJSON("%v", err)
|
|
}
|
|
if descChanged {
|
|
if err := validateDescriptionUpdate(cmd, description, descChanged); err != nil {
|
|
return nil, HandleErrorRespectJSON("%v", err)
|
|
}
|
|
in.fields["description"] = description
|
|
}
|
|
design, designChanged, err := getDesignFlag(cmd)
|
|
if err != nil {
|
|
return nil, HandleErrorRespectJSON("%v", err)
|
|
}
|
|
if designChanged {
|
|
in.fields["design"] = design
|
|
}
|
|
if cmd.Flags().Changed("notes") && cmd.Flags().Changed("append-notes") {
|
|
return nil, HandleErrorRespectJSON("cannot specify both --notes and --append-notes")
|
|
}
|
|
if cmd.Flags().Changed("notes") {
|
|
notes, _ := cmd.Flags().GetString("notes")
|
|
in.fields["notes"] = notes
|
|
}
|
|
if cmd.Flags().Changed("append-notes") {
|
|
in.appendNotes, _ = cmd.Flags().GetString("append-notes")
|
|
in.hasAppendNotes = true
|
|
}
|
|
if cmd.Flags().Changed("acceptance") || cmd.Flags().Changed("acceptance-criteria") {
|
|
var ac string
|
|
if cmd.Flags().Changed("acceptance") {
|
|
ac, _ = cmd.Flags().GetString("acceptance")
|
|
} else {
|
|
ac, _ = cmd.Flags().GetString("acceptance-criteria")
|
|
}
|
|
in.fields["acceptance_criteria"] = ac
|
|
}
|
|
if cmd.Flags().Changed("external-ref") {
|
|
externalRef, _ := cmd.Flags().GetString("external-ref")
|
|
if externalRef == "" {
|
|
in.fields["external_ref"] = nil
|
|
} else {
|
|
in.fields["external_ref"] = externalRef
|
|
}
|
|
}
|
|
if cmd.Flags().Changed("spec-id") {
|
|
specID, _ := cmd.Flags().GetString("spec-id")
|
|
in.fields["spec_id"] = specID
|
|
}
|
|
if cmd.Flags().Changed("estimate") {
|
|
estimate, _ := cmd.Flags().GetInt("estimate")
|
|
if estimate < 0 {
|
|
return nil, HandleErrorRespectJSON("estimate must be a non-negative number of minutes")
|
|
}
|
|
in.fields["estimated_minutes"] = estimate
|
|
}
|
|
if cmd.Flags().Changed("type") {
|
|
issueType, _ := cmd.Flags().GetString("type")
|
|
in.fields["issue_type"] = utils.NormalizeIssueType(issueType)
|
|
}
|
|
// Normalize on the way in, as the read paths do. --remove-label matters as
|
|
// much as the additive flags: an untrimmed " theme:a" would fail to match
|
|
// the stored label and silently remove nothing.
|
|
if cmd.Flags().Changed("add-label") {
|
|
addLabels, _ := cmd.Flags().GetStringSlice("add-label")
|
|
in.addLabels = utils.NormalizeLabels(addLabels)
|
|
warnLabelsContainingWhitespace(in.addLabels)
|
|
}
|
|
if cmd.Flags().Changed("remove-label") {
|
|
removeLabels, _ := cmd.Flags().GetStringSlice("remove-label")
|
|
in.removeLabels = utils.NormalizeLabels(removeLabels)
|
|
}
|
|
if cmd.Flags().Changed("set-labels") {
|
|
labels, _ := cmd.Flags().GetStringSlice("set-labels")
|
|
// Preserve the explicit "clear all labels" signal: --set-labels ''
|
|
// normalizes to empty, and a nil slice here would still be a non-nil
|
|
// pointer to an empty slice, which is the clear instruction.
|
|
labels = utils.NormalizeLabels(labels)
|
|
warnLabelsContainingWhitespace(labels)
|
|
in.setLabels = &labels
|
|
}
|
|
if cmd.Flags().Changed("parent") {
|
|
parent, _ := cmd.Flags().GetString("parent")
|
|
in.reparent = &parent
|
|
}
|
|
if cmd.Flags().Changed("await-id") {
|
|
awaitID, _ := cmd.Flags().GetString("await-id")
|
|
in.fields["await_id"] = awaitID
|
|
}
|
|
if cmd.Flags().Changed("due") {
|
|
dueStr, _ := cmd.Flags().GetString("due")
|
|
if dueStr == "" {
|
|
in.fields["due_at"] = nil
|
|
} else {
|
|
t, err := timeparsing.ParseRelativeTime(dueStr, time.Now())
|
|
if err != nil {
|
|
return nil, HandleErrorRespectJSON("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr)
|
|
}
|
|
in.fields["due_at"] = t
|
|
}
|
|
}
|
|
if cmd.Flags().Changed("defer") {
|
|
deferStr, _ := cmd.Flags().GetString("defer")
|
|
jsonOut, _ := cmd.Flags().GetBool("json")
|
|
if deferStr == "" {
|
|
in.fields["defer_until"] = nil
|
|
if _, ok := in.fields["status"]; !ok {
|
|
in.clearDeferStatus = true
|
|
}
|
|
} else {
|
|
t, err := timeparsing.ParseRelativeTime(deferStr, time.Now())
|
|
if err != nil {
|
|
return nil, HandleErrorRespectJSON("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr)
|
|
}
|
|
inPast := t.Before(time.Now())
|
|
if inPast && !jsonOut {
|
|
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.fields["defer_until"] = t
|
|
if _, ok := in.fields["status"]; !ok && !inPast {
|
|
in.fields["status"] = string(types.StatusDeferred)
|
|
}
|
|
}
|
|
}
|
|
ephemeralChanged := cmd.Flags().Changed("ephemeral")
|
|
persistentChanged := cmd.Flags().Changed("persistent")
|
|
noHistoryChanged := cmd.Flags().Changed("no-history")
|
|
historyChanged := cmd.Flags().Changed("history")
|
|
if ephemeralChanged && persistentChanged {
|
|
return nil, HandleErrorRespectJSON("cannot specify both --ephemeral and --persistent flags")
|
|
}
|
|
if noHistoryChanged && ephemeralChanged {
|
|
return nil, HandleErrorRespectJSON("cannot specify both --no-history and --ephemeral flags")
|
|
}
|
|
if noHistoryChanged && historyChanged {
|
|
return nil, HandleErrorRespectJSON("cannot specify both --no-history and --history flags")
|
|
}
|
|
if ephemeralChanged {
|
|
in.fields["wisp"] = true
|
|
}
|
|
if persistentChanged {
|
|
in.fields["wisp"] = false
|
|
}
|
|
if noHistoryChanged {
|
|
in.fields["no_history"] = true
|
|
}
|
|
if historyChanged {
|
|
in.fields["no_history"] = false
|
|
}
|
|
if cmd.Flags().Changed("metadata") {
|
|
metadataValue, _ := cmd.Flags().GetString("metadata")
|
|
metadata, err := readMetadataFlag(metadataValue)
|
|
if err != nil {
|
|
return nil, HandleErrorRespectJSON("%v", err)
|
|
}
|
|
in.mergeMetadataIn = metadata
|
|
}
|
|
setMetadataFlags, _ := cmd.Flags().GetStringArray("set-metadata")
|
|
unsetMetadataFlags, _ := cmd.Flags().GetStringArray("unset-metadata")
|
|
if (len(setMetadataFlags) > 0 || len(unsetMetadataFlags) > 0) && cmd.Flags().Changed("metadata") {
|
|
return nil, HandleErrorRespectJSON("cannot combine --metadata with --set-metadata or --unset-metadata")
|
|
}
|
|
in.setMetadata = setMetadataFlags
|
|
in.unsetMetadata = unsetMetadataFlags
|
|
|
|
in.claim, _ = cmd.Flags().GetBool("claim")
|
|
|
|
// bd-wsqvw conditional-update guards, mirroring the non-proxied path's
|
|
// updateGuardsFromFlags rules: Changed()-detected presence (so
|
|
// `--if-assignee ""` guards on unassigned), --if-status validated against
|
|
// the live status set, mutually exclusive with --claim, and requiring a
|
|
// field update to ride on.
|
|
if cmd.Flags().Changed("if-assignee") {
|
|
v, _ := cmd.Flags().GetString("if-assignee")
|
|
in.ifAssignee = &v
|
|
}
|
|
if cmd.Flags().Changed("if-status") {
|
|
v, _ := cmd.Flags().GetString("if-status")
|
|
if err := validateUpdateStatus(ctx, v); err != nil {
|
|
return nil, err
|
|
}
|
|
in.ifStatus = &v
|
|
}
|
|
if in.ifAssignee != nil || in.ifStatus != nil {
|
|
if in.claim {
|
|
return nil, HandleErrorRespectJSON("cannot combine --if-assignee/--if-status with --claim (--claim is already an atomic compare-and-set)")
|
|
}
|
|
if len(in.fields) == 0 && !in.hasAppendNotes && len(in.mergeMetadataIn) == 0 && len(in.setMetadata) == 0 && len(in.unsetMetadata) == 0 {
|
|
return nil, HandleErrorRespectJSON("--if-assignee/--if-status require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard")
|
|
}
|
|
}
|
|
return in, nil
|
|
}
|
|
|
|
func validateUpdateStatus(ctx context.Context, status string) error {
|
|
if uowProvider == nil {
|
|
return HandleError("proxied-server UOW provider not initialized")
|
|
}
|
|
uw, err := uowProvider.NewUOW(ctx)
|
|
if err != nil {
|
|
return HandleError("open unit of work: %v", err)
|
|
}
|
|
names, err := uw.ConfigUseCase().ListAllStatusNames(ctx)
|
|
uw.Close(ctx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("read status set: %v", err)
|
|
}
|
|
for _, name := range names {
|
|
if name == status {
|
|
return nil
|
|
}
|
|
}
|
|
return HandleErrorRespectJSON("invalid status %q (allowed: %s)", status, strings.Join(names, ", "))
|
|
}
|
|
|
|
func isUpdateInputNoop(in *updateInput) bool {
|
|
if in.claim {
|
|
return false
|
|
}
|
|
if len(in.fields) > 0 || in.hasAppendNotes || in.setLabels != nil || in.reparent != nil {
|
|
return false
|
|
}
|
|
if len(in.addLabels) > 0 || len(in.removeLabels) > 0 {
|
|
return false
|
|
}
|
|
if len(in.mergeMetadataIn) > 0 || len(in.setMetadata) > 0 || len(in.unsetMetadata) > 0 {
|
|
return false
|
|
}
|
|
return true
|
|
}
|