diff --git a/CHANGELOG.md b/CHANGELOG.md index 85280df74..8e48fd87b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -173,6 +173,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Text-input commands now REFUSE two sources instead of silently picking + one** (#5332). `bd comment`, `bd note` and `bd comments add` used to apply a + precedence order when a caller gave both positional text and `--stdin` or + `--file`: the flag won and the positional text was dropped with no message. + Naming two sources is now an error — `cannot combine positional text "..." + with --stdin` — because the dropped half was, in every case we could find, + the text the caller actually meant. Single-source invocations are unchanged. + Scripts that relied on the old precedence (passing both and expecting the + flag to win) must drop the redundant argument. + + `bd human respond` gains the same layer, so its response text can come from + positional args, `--response`, `--file` or `--stdin`; `--response` is no + longer a required flag. `bd human dismiss` takes its reason positionally as + well as via `--reason`. Both now accept trailing positional text + (` [text...]`), matching `bd comment`'s contract — a second argument is + free text, never a second issue id. + +- **`bd list --status=all` no longer hides boolean-pinned beads** (#5332). + `all` promises every status, but the pinned exclusion was decided by + comparing the raw selector string to `pinned`/`hooked`, so `all` fell through + and kept forcing `Pinned=false`. The same string comparison also missed every + multi-status set containing them, so `--status=pinned,closed` excluded the + pinned beads it explicitly asked for. Both now lift the exclusion. **Scripts + that used `--status=all` as a way to list everything EXCEPT pinned beads will + see pinned beads appear**; add `--no-pinned` to keep the old result. + `--ready` is unaffected: it forces status `open` and ignores the selector, so + an `all` it never applies has no pinned side effect either. + +- **`bd human list` matches `bd list`'s status handling, and hides no bead + type** (#5332). It used to pass `--status` through unvalidated and show + closed beads by default. Now done/frozen statuses and pinned beads are hidden + by default, `--status` is validated against the built-in and custom status + names (comma-separated sets and `all` supported, so a typo is an error rather + than an empty list), and every bead TYPE still shows — gates, wisps, infra + beads and templates — because a `human` label is an explicit request for a + person's attention. `bd human stats` counts across every status, as before. + +- **`bd human stats` classifies dismissals by close-reason PREFIX** (#5332). + It matched the substring `dismiss` case-insensitively anywhere in the close + reason; it now requires the `Dismissed` prefix that `bd human dismiss` + writes, shared as one constant so the writer and the classifier cannot drift. + Beads closed before this with a lowercase or mid-string "dismiss" in their + reason move from the Dismissed count to the Responded count. Forward + behavior is unchanged. + - **The settings plane no longer serves the KV plane by any read** (bd-rfwtv, bd-klko9). `bd kv` keys and the `bd remember` memories nested under them are user data stored as config rows; they ride in the settings table without being diff --git a/cmd/bd/comment.go b/cmd/bd/comment.go index 83a4fefb2..ac1d9e737 100644 --- a/cmd/bd/comment.go +++ b/cmd/bd/comment.go @@ -2,9 +2,6 @@ package main import ( "fmt" - "io" - "os" - "strings" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" @@ -80,42 +77,23 @@ To list comments on an issue, use the plural form: bd comments `, } }() - if usesProxiedServer() { - return runCommentProxiedServer(cmd, rootCtx, args) - } - id := args[0] textArgs := args[1:] - stdinFlag, _ := cmd.Flags().GetBool("stdin") - fileFlag, _ := cmd.Flags().GetString("file") - - var commentText string - switch { - case stdinFlag: - content, err := io.ReadAll(os.Stdin) - if err != nil { - return HandleErrorRespectJSON("reading from stdin: %v", err) - } - commentText = strings.TrimRight(string(content), "\n") - case fileFlag != "": - content, err := readBodyFile(fileFlag) - if err != nil { - return HandleErrorRespectJSON("reading file: %v", err) - } - commentText = content - case len(textArgs) > 0: - commentText = strings.Join(textArgs, " ") - default: - return HandleErrorRespectJSON("no comment text provided (use positional args, --stdin, or --file)") - } - - if strings.TrimSpace(commentText) == "" { - return HandleErrorRespectJSON("comment text cannot be empty") + commentText, err := requireTextFromSources("comment text", "use positional args, --stdin, or --file", + cmdTextSources(cmd, textArgs)) + if err != nil { + return HandleErrorRespectJSON("%v", err) } author := getActorWithGit() + // Dispatched after the text is resolved so both backends read the + // same sources and report the same conflicts. + if usesProxiedServer() { + return runCommentProxiedServer(rootCtx, id, author, commentText) + } + ctx := rootCtx result, err := resolveAndGetIssueForMutation(ctx, store, id) @@ -161,9 +139,7 @@ To list comments on an issue, use the plural form: bd comments `, } func init() { - commentCmd.Flags().Bool("stdin", false, "Read comment text from stdin") - commentCmd.Flags().String("file", "", "Read comment text from file") - commentCmd.MarkFlagsMutuallyExclusive("stdin", "file") + registerTextSourceFlags(commentCmd, "comment text") commentCmd.ValidArgsFunction = issueIDCompletion rootCmd.AddCommand(commentCmd) } diff --git a/cmd/bd/comments.go b/cmd/bd/comments.go index 5e0de6362..f0d02bb4e 100644 --- a/cmd/bd/comments.go +++ b/cmd/bd/comments.go @@ -3,7 +3,6 @@ package main import ( "context" "fmt" - "os" "strings" "github.com/spf13/cobra" @@ -190,27 +189,12 @@ Examples: } }() - if usesProxiedServer() { - return runCommentsAddProxiedServer(cmd, rootCtx, args) - } - issueID := args[0] - commentText, _ := cmd.Flags().GetString("file") - if commentText != "" { - data, err := os.ReadFile(commentText) // #nosec G304 - user-provided file path is intentional - if err != nil { - return HandleErrorRespectJSON("reading file: %v", err) - } - commentText = string(data) - } else if len(args) < 2 { - return HandleErrorRespectJSON("comment text required (use -f to read from file)") - } else { - commentText = strings.Join(args[1:], " ") - } - - if strings.TrimSpace(commentText) == "" { - return HandleErrorRespectJSON("comment text cannot be empty") + 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") @@ -218,6 +202,12 @@ Examples: 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) } diff --git a/cmd/bd/comments_proxied_server.go b/cmd/bd/comments_proxied_server.go index aa84e0911..b96fac4c0 100644 --- a/cmd/bd/comments_proxied_server.go +++ b/cmd/bd/comments_proxied_server.go @@ -4,8 +4,6 @@ import ( "context" "errors" "fmt" - "io" - "os" "strings" "github.com/spf13/cobra" @@ -71,40 +69,8 @@ func runCommentsProxiedServer(cmd *cobra.Command, ctx context.Context, args []st return nil } -func runCommentProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { - id := args[0] - textArgs := args[1:] - - stdinFlag, _ := cmd.Flags().GetBool("stdin") - fileFlag, _ := cmd.Flags().GetString("file") - - var commentText string - switch { - case stdinFlag: - content, err := io.ReadAll(os.Stdin) - if err != nil { - return HandleErrorRespectJSON("reading from stdin: %v", err) - } - commentText = strings.TrimRight(string(content), "\n") - case fileFlag != "": - content, err := readBodyFile(fileFlag) - if err != nil { - return HandleErrorRespectJSON("reading file: %v", err) - } - commentText = content - case len(textArgs) > 0: - commentText = strings.Join(textArgs, " ") - default: - return HandleErrorRespectJSON("no comment text provided (use positional args, --stdin, or --file)") - } - - if strings.TrimSpace(commentText) == "" { - return HandleErrorRespectJSON("comment text cannot be empty") - } - - author := getActorWithGit() - - comment, issue, err := addCommentProxied(ctx, id, author, commentText) +func runCommentProxiedServer(ctx context.Context, id, author, text string) error { + comment, issue, err := addCommentProxied(ctx, id, author, text) if err != nil { return HandleErrorRespectJSON("%v", err) } @@ -118,32 +84,8 @@ func runCommentProxiedServer(cmd *cobra.Command, ctx context.Context, args []str return nil } -func runCommentsAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { - issueID := args[0] - - commentText, _ := cmd.Flags().GetString("file") - if commentText != "" { - data, err := os.ReadFile(commentText) // #nosec G304 - user-provided file path is intentional - if err != nil { - return HandleErrorRespectJSON("reading file: %v", err) - } - commentText = string(data) - } else if len(args) < 2 { - return HandleErrorRespectJSON("comment text required (use -f to read from file)") - } else { - commentText = strings.Join(args[1:], " ") - } - - if strings.TrimSpace(commentText) == "" { - return HandleErrorRespectJSON("comment text cannot be empty") - } - - author, _ := cmd.Flags().GetString("author") - if author == "" { - author = getActorWithGit() - } - - comment, issue, err := addCommentProxied(ctx, issueID, author, commentText) +func runCommentsAddProxiedServer(ctx context.Context, issueID, author, text string) error { + comment, issue, err := addCommentProxied(ctx, issueID, author, text) if err != nil { return HandleErrorRespectJSON("%v", err) } diff --git a/cmd/bd/flags.go b/cmd/bd/flags.go index c5c70a9f9..2f7289800 100644 --- a/cmd/bd/flags.go +++ b/cmd/bd/flags.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "os" + "strings" "github.com/spf13/cobra" ) @@ -208,6 +209,126 @@ func readBodyFile(filePath string) (string, error) { 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 +// (" 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)") diff --git a/cmd/bd/flags_test.go b/cmd/bd/flags_test.go index 14a21e1b1..2c7d7d70d 100644 --- a/cmd/bd/flags_test.go +++ b/cmd/bd/flags_test.go @@ -1,6 +1,7 @@ package main import ( + "io" "os" "path/filepath" "strings" @@ -483,3 +484,85 @@ func TestGetDesignFlag(t *testing.T) { } }) } + +func TestTextFromSources(t *testing.T) { + bodyFile := filepath.Join(t.TempDir(), "body.md") + if err := os.WriteFile(bodyFile, []byte("file text\n"), 0o644); err != nil { + t.Fatal(err) + } + crlfFile := filepath.Join(t.TempDir(), "crlf.md") + if err := os.WriteFile(crlfFile, []byte("Approved\r\n"), 0o644); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + useStdin bool + stdin string + filePath string + flagText string + positional []string + want string + wantErr bool + }{ + {name: "flag text", flagText: "flag text", want: "flag text"}, + {name: "positional joined", positional: []string{"Use", "OAuth2"}, want: "Use OAuth2"}, + {name: "file content is verbatim", filePath: bodyFile, want: "file text\n"}, + {name: "file content keeps CRLF", filePath: crlfFile, want: "Approved\r\n"}, + {name: "stdin trims CRLF", useStdin: true, stdin: "Approved\r\n", want: "Approved"}, + {name: "stdin conflicts with file and flag", useStdin: true, stdin: "stdin text\n", filePath: bodyFile, flagText: "flag", wantErr: true}, + {name: "file conflicts with flag", filePath: bodyFile, flagText: "flag", wantErr: true}, + {name: "no source is empty", want: ""}, + {name: "positional conflicts with stdin", useStdin: true, stdin: "x", positional: []string{"pos"}, wantErr: true}, + {name: "positional conflicts with file", filePath: bodyFile, positional: []string{"pos"}, wantErr: true}, + {name: "positional conflicts with flag", flagText: "flag", positional: []string{"pos"}, wantErr: true}, + {name: "blank positional does not conflict with file", filePath: bodyFile, positional: []string{""}, want: "file text\n"}, + {name: "blank positional does not conflict with stdin", useStdin: true, stdin: "stdin text\n", positional: []string{" "}, want: "stdin text"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var stdin io.Reader + if tt.useStdin { + stdin = strings.NewReader(tt.stdin) + } + got, _, err := textFromSources(textSources{stdin: stdin, filePath: tt.filePath, flagText: tt.flagText, flagName: "--response", positional: tt.positional}) + if tt.wantErr { + if err == nil { + t.Fatal("expected conflict error, got nil") + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != tt.want { + t.Errorf("got %q, want %q", got, tt.want) + } + }) + } + + if _, _, err := textFromSources(textSources{filePath: filepath.Join(t.TempDir(), "missing.md")}); err == nil { + t.Error("expected error for unreadable file") + } +} + +func TestRequireTextFromSources(t *testing.T) { + if _, err := requireTextFromSources("response text", "use positional args or --response", + textSources{}); err == nil || !strings.Contains(err.Error(), "no response text provided (use positional args or --response)") { + t.Errorf("expected no-source error listing the hint, got %v", err) + } + if _, err := requireTextFromSources("response text", "hint", + textSources{positional: []string{" "}}); err == nil || !strings.Contains(err.Error(), "response text cannot be empty") { + t.Errorf("expected cannot-be-empty error for blank positional text, got %v", err) + } + if _, err := requireTextFromSources("note text", "hint", + textSources{stdin: strings.NewReader("\n")}); err == nil || !strings.Contains(err.Error(), "note text cannot be empty") { + t.Errorf("expected cannot-be-empty error for blank stdin, got %v", err) + } + got, err := requireTextFromSources("response text", "hint", + textSources{flagText: "flag text", flagName: "--response"}) + if err != nil || got != "flag text" { + t.Errorf("got %q, %v; want \"flag text\", nil", got, err) + } +} diff --git a/cmd/bd/human.go b/cmd/bd/human.go index 482ebcd6c..c87faa2d6 100644 --- a/cmd/bd/human.go +++ b/cmd/bd/human.go @@ -1,15 +1,19 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "slices" "strings" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" ) var humanCmd = &cobra.Command{ @@ -24,7 +28,7 @@ This command shows the ~15 essential commands that human users need most often. For the full command list, run: bd --help SUBCOMMANDS: - human list List all human-needed beads (issues with 'human' label) + human list List human-needed beads (issues with 'human' label; hides closed by default) human respond Respond to a human-needed bead (adds comment and closes) human dismiss Dismiss a human-needed bead permanently human stats Show summary statistics for human-needed beads`, @@ -97,14 +101,19 @@ SUBCOMMANDS: // human list command var humanListCmd = &cobra.Command{ Use: "list", - Short: "List all human-needed beads", - Long: `List all issues labeled with 'human' tag. + Short: "List human-needed beads", + Long: `List issues labeled with 'human' tag. -These are issues that require human intervention or input. +These are issues that require human intervention or input. Every +human-labeled bead shows regardless of type (including gates and wisps). +By default closed, pinned, and other done/frozen beads are hidden; use +--status to select specific statuses, or --status=all to include every +status. Examples: bd human list - bd human list --status=open + bd human list --status=closed + bd human list --status=all bd human list --json`, SilenceUsage: true, SilenceErrors: true, @@ -118,41 +127,15 @@ Examples: status, _ := cmd.Flags().GetString("status") - ctx := rootCtx - - if usesProxiedServer() { - return runHumanListProxiedServer(ctx, status) - } - - filter := types.IssueFilter{ - Labels: []string{"human"}, - } - - if status != "" { - s := types.Status(status) - filter.Status = &s - } - - if err := ensureStoreActive(); err != nil { - return HandleErrorRespectJSON("listing human beads: %v", err) - } - - var err error - issues, err := store.SearchIssues(ctx, "", filter) + issues, err := humanIssues(rootCtx, status) if err != nil { return HandleErrorRespectJSON("listing human beads: %v", err) } if jsonOutput { - issueIDs := make([]string, len(issues)) - for i, issue := range issues { - issueIDs[i] = issue.ID - } - labelsMap, _ := store.GetLabelsForIssues(ctx, issueIDs) - for _, issue := range issues { - issue.Labels = labelsMap[issue.ID] - } - + // SearchIssues already hydrated .Labels on both backends (the + // filter never sets SkipLabels), so the issues marshal with their + // labels attached. data, err := json.MarshalIndent(issues, "", " ") if err != nil { return HandleErrorRespectJSON("encoding JSON: %v", err) @@ -166,6 +149,63 @@ Examples: }, } +// humanIssues loads the human-labeled beads matching the status selector +// through whichever backend this invocation uses: the direct store, or a +// proxied-server unit of work. Both routes apply the same humanListFilter. +func humanIssues(ctx context.Context, status string) ([]*types.Issue, error) { + if usesProxiedServer() { + return proxiedHumanIssues(ctx, status) + } + + if err := ensureStoreActive(); err != nil { + return nil, err + } + cfg, err := workapi.LoadStoreListConfig(ctx, store) + if err != nil { + return nil, fmt.Errorf("loading status configuration: %w", err) + } + filter, err := humanListFilter(status, cfg) + if err != nil { + return nil, err + } + return store.SearchIssues(ctx, "", filter) +} + +// humanListRequest builds the list request for "human list": every +// human-labeled bead regardless of type — a human label is an explicit +// request for a person's attention, and this command is the only place a +// person sees it, so gates, wisps, infra beads, and templates all show. +// Status filtering matches `bd list`: done/frozen statuses and pinned beads +// are hidden by default, an explicit --status selects specific statuses +// (validated against the built-in and custom status names), and "all" lifts +// the status defaults entirely. +func humanListRequest(status string) issueops.ListRequest { + unlimited := 0 + req := issueops.ListRequest{ + Labels: []string{"human"}, + Limit: &unlimited, // human list has never paginated; 0 = unlimited + // No bead type is hidden from a human listing. + IncludeAllTypes: true, + } + req.Status = status // "" applies the defaults; "all" lifts them + return req +} + +// humanListFilter resolves humanListRequest against loaded status/type config. +func humanListFilter(status string, cfg workapi.ListConfig) (types.IssueFilter, error) { + return workapi.BuildListFilter(humanListRequest(status), cfg) +} + +// warnIfNotHumanLabeled warns on stderr when the bead lacks the 'human' +// label. The check is advisory — respond/dismiss act on whichever bead the +// user named. The issue must carry its labels; anything returned by +// GetIssue/resolveAndGetIssueForMutation does. +func warnIfNotHumanLabeled(issue *types.Issue) { + if !slices.Contains(issue.Labels, "human") { + fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", issue.ID) + } +} + func printHumanList(issues []*types.Issue) { if len(issues) == 0 { fmt.Println("No human-needed beads found.") @@ -174,32 +214,45 @@ func printHumanList(issues []*types.Issue) { fmt.Printf("\n%s (%d found)\n\n", ui.RenderBold("Human-needed beads"), len(issues)) for _, issue := range issues { + if issue.Status == types.StatusClosed { + // Closed items fade to muted gray, matching bd list/query. They + // only appear under an explicit --status, so the fade is what + // distinguishes them from the work still waiting on a person. + fmt.Printf(" %s\n", ui.RenderClosedLine(fmt.Sprintf("%s %s", issue.ID, issue.Title))) + fmt.Printf(" %s\n", ui.RenderClosedLine(fmt.Sprintf("Status: %s", issue.Status))) + fmt.Printf(" %s\n", ui.RenderClosedLine(fmt.Sprintf("Priority: P%d", issue.Priority))) + fmt.Println() + continue + } fmt.Printf(" %s %s\n", ui.RenderCommand(issue.ID), issue.Title) if issue.Status != "open" { fmt.Printf(" Status: %s\n", issue.Status) } - if issue.Priority != 0 { - fmt.Printf(" Priority: P%d\n", issue.Priority) - } + fmt.Printf(" Priority: %s\n", ui.RenderPriorityForStatus(issue.Priority, string(issue.Status))) fmt.Println() } } // human respond command var humanRespondCmd = &cobra.Command{ - Use: "respond ", + Use: "respond [response...]", Short: "Respond to a human-needed bead", Long: `Respond to a human-needed bead by adding a comment and closing it. The response is added as a comment and the issue is closed with reason "Responded". +The response text can be given as positional arguments, --response, --file, or --stdin. Examples: - bd human respond bd-123 --response "Use OAuth2 for authentication" - bd human respond bd-123 -r "Approved, proceed with implementation"`, - Args: cobra.ExactArgs(1), + bd human respond bd-123 "Use OAuth2 for authentication" + bd human respond bd-123 -r "Approved, proceed with implementation" + bd human respond bd-123 --file response.md + echo "Approved" | bd human respond bd-123 --stdin`, + Args: cobra.MinimumNArgs(1), SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { + CheckReadonly("human respond") + evt := metrics.NewCommandEvent("human-respond") defer func() { if c := metrics.Global(); c != nil { @@ -207,19 +260,23 @@ Examples: } }() - response, _ := cmd.Flags().GetString("response") - - if response == "" { - return HandleErrorRespectJSON("--response is required") + src := cmdTextSources(cmd, args[1:]) + src.flagText, _ = cmd.Flags().GetString("response") + src.flagName = "--response" + src.flagSet = cmd.Flags().Changed("response") + response, err := requireTextFromSources("response text", "use positional args, --response, --file, or --stdin", src) + if err != nil { + return HandleErrorRespectJSON("%v", err) } - CheckReadonly("human respond") - ctx := rootCtx issueID := args[0] + // Formatted once here so the direct and proxied backends store + // identically-shaped comments. + commentText := fmt.Sprintf("Response: %s", response) if usesProxiedServer() { - return runHumanRespondProxiedServer(ctx, issueID, response) + return runHumanRespondProxiedServer(ctx, issueID, commentText) } // Direct mode @@ -248,20 +305,8 @@ Examples: return HandleErrorRespectJSON("issue %s is already closed", resolvedID) } - labelsMap, _ := targetStore.GetLabelsForIssues(ctx, []string{resolvedID}) - hasHumanLabel := false - for _, label := range labelsMap[resolvedID] { - if label == "human" { - hasHumanLabel = true - break - } - } + warnIfNotHumanLabeled(issue) - if !hasHumanLabel { - fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", resolvedID) - } - - commentText := fmt.Sprintf("Response: %s", response) _, err = targetStore.AddIssueComment(ctx, resolvedID, actor, commentText) if err != nil { return HandleErrorRespectJSON("adding comment: %v", err) @@ -278,19 +323,23 @@ Examples: // human dismiss command var humanDismissCmd = &cobra.Command{ - Use: "dismiss ", + Use: "dismiss [reason...]", Short: "Dismiss a human-needed bead", Long: `Dismiss a human-needed bead permanently without responding. The issue is closed with a "Dismissed" reason and optional note. +The reason can be given as positional arguments or --reason. Examples: bd human dismiss bd-123 + bd human dismiss bd-123 "No longer applicable" bd human dismiss bd-123 --reason "No longer applicable"`, - Args: cobra.ExactArgs(1), + Args: cobra.MinimumNArgs(1), SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { + CheckReadonly("human dismiss") + evt := metrics.NewCommandEvent("human-dismiss") defer func() { if c := metrics.Global(); c != nil { @@ -298,15 +347,32 @@ Examples: } }() - reason, _ := cmd.Flags().GetString("reason") + reasonFlag, _ := cmd.Flags().GetString("reason") - CheckReadonly("human dismiss") + // A dismissal reason is optional, so this is textFromSources rather + // than requireTextFromSources: no source at all is fine, but naming + // two is still the same hard error every other text input gives. + reason, _, err := textFromSources(textSources{ + flagText: reasonFlag, + flagName: "--reason", + flagSet: cmd.Flags().Changed("reason"), + positional: args[1:], + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + reason = strings.TrimSpace(reason) + + closeReason := dismissedCloseReason + if reason != "" { + closeReason = fmt.Sprintf("%s: %s", dismissedCloseReason, reason) + } ctx := rootCtx issueID := args[0] if usesProxiedServer() { - return runHumanDismissProxiedServer(ctx, issueID, reason) + return runHumanDismissProxiedServer(ctx, issueID, closeReason) } // Direct mode @@ -335,23 +401,7 @@ Examples: return HandleErrorRespectJSON("issue %s is already closed", resolvedID) } - labelsMap, _ := targetStore.GetLabelsForIssues(ctx, []string{resolvedID}) - hasHumanLabel := false - for _, label := range labelsMap[resolvedID] { - if label == "human" { - hasHumanLabel = true - break - } - } - - if !hasHumanLabel { - fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", resolvedID) - } - - closeReason := "Dismissed" - if reason != "" { - closeReason = fmt.Sprintf("Dismissed: %s", reason) - } + warnIfNotHumanLabeled(issue) if err := targetStore.CloseIssue(ctx, resolvedID, closeReason, actor, ""); err != nil { return HandleErrorRespectJSON("closing bead: %v", err) @@ -383,22 +433,9 @@ Example: } }() - ctx := rootCtx - - if usesProxiedServer() { - return runHumanStatsProxiedServer(ctx) - } - - filter := types.IssueFilter{ - Labels: []string{"human"}, - } - - if err := ensureStoreActive(); err != nil { - return HandleErrorRespectJSON("getting human bead stats: %v", err) - } - - var err error - issues, err := store.SearchIssues(ctx, "", filter) + // The stats universe is `human list --status=all`: every human-labeled + // bead, every status, every type. + issues, err := humanIssues(rootCtx, "all") if err != nil { return HandleErrorRespectJSON("getting human bead stats: %v", err) } @@ -408,6 +445,11 @@ Example: }, } +// dismissedCloseReason prefixes the close reason `human dismiss` writes; +// printHumanStats classifies dismissed beads by this same prefix so the +// writer and the classifier cannot drift apart. +const dismissedCloseReason = "Dismissed" + func printHumanStats(issues []*types.Issue) { total := len(issues) pending := 0 @@ -418,7 +460,7 @@ func printHumanStats(issues []*types.Issue) { switch issue.Status { case "closed": closed++ - if strings.Contains(strings.ToLower(issue.CloseReason), "dismiss") { + if strings.HasPrefix(issue.CloseReason, dismissedCloseReason) { dismissed++ } default: @@ -451,9 +493,9 @@ func init() { humanCmd.AddCommand(humanStatsCmd) // Add flags for subcommands - humanListCmd.Flags().StringP("status", "s", "", "Filter by status (open, closed, etc.)") - humanRespondCmd.Flags().StringP("response", "r", "", "Response text (required)") - _ = humanRespondCmd.MarkFlagRequired("response") + humanListCmd.Flags().StringP("status", "s", "", "Filter by status (open, closed, etc.; comma-separated for multiple, 'all' for every status)") + humanRespondCmd.Flags().StringP("response", "r", "", "Response text") + registerTextSourceFlags(humanRespondCmd, "response text", "response") humanDismissCmd.Flags().StringP("reason", "", "", "Reason for dismissal (optional)") // Register with root command diff --git a/cmd/bd/human_embedded_test.go b/cmd/bd/human_embedded_test.go index ccf01b238..51e3b7bc6 100644 --- a/cmd/bd/human_embedded_test.go +++ b/cmd/bd/human_embedded_test.go @@ -6,9 +6,12 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "strings" "sync" "testing" + + "github.com/steveyegge/beads/internal/types" ) // bdHuman runs "bd human" with the given args and returns stdout. @@ -25,6 +28,26 @@ func bdHuman(t *testing.T, bd, dir string, args ...string) string { return stdout.String() } +// createHumanBead creates a bead carrying the 'human' label and returns its ID. +func createHumanBead(t *testing.T, bd, dir, title string) string { + t.Helper() + id := bdCreateSilent(t, bd, dir, title, "--labels", "human") + if id == "" { + t.Fatalf("could not find issue ID in create output for %q", title) + } + return id +} + +// humanShowClosed asserts the bead is closed and returns its parsed issue. +func humanShowClosed(t *testing.T, bd, dir, id string) *types.Issue { + t.Helper() + issue := bdShow(t, bd, dir, id) + if issue.Status != types.StatusClosed { + t.Errorf("expected issue %s to be closed, got status %q", id, issue.Status) + } + return issue +} + func TestEmbeddedHuman(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") @@ -64,26 +87,7 @@ func TestEmbeddedHuman(t *testing.T) { // ===== Respond and Dismiss ===== t.Run("human_respond_and_dismiss", func(t *testing.T) { - // Create a bead - cmd := exec.Command(bd, "create", "Human test issue", "--type", "task", "--silent") - cmd.Dir = dir - cmd.Env = bdEnv(dir) - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("create failed: %v\n%s", err, out) - } - id := strings.TrimSpace(string(out)) - if id == "" { - t.Fatalf("could not find issue ID in output: %s", out) - } - - // Humanize it - cmd = exec.Command(bd, "label", "add", id, "human") - cmd.Dir = dir - cmd.Env = bdEnv(dir) - if out, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("label add failed: %v\n%s", err, out) - } + id := createHumanBead(t, bd, dir, "Human test issue") // Verify it shows up in human list listOut := bdHuman(t, bd, dir, "list") @@ -93,55 +97,94 @@ func TestEmbeddedHuman(t *testing.T) { // Test Respond bdHuman(t, bd, dir, "respond", id, "--response", "Approved") + humanShowClosed(t, bd, dir, id) - // Verify closed - cmd = exec.Command(bd, "show", id) - cmd.Dir = dir - cmd.Env = bdEnv(dir) - showOut, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("show failed: %v\n%s", err, showOut) + // Closed beads drop out of the default list but show with + // --status=closed and --status=all. + listOut = bdHuman(t, bd, dir, "list") + if strings.Contains(listOut, id) { + t.Errorf("closed issue %s should be hidden from default human list:\n%s", id, listOut) } - if !strings.Contains(string(showOut), "CLOSED") { - t.Errorf("expected issue %s to be closed after respond:\n%s", id, showOut) + closedOut := bdHuman(t, bd, dir, "list", "--status=closed") + if !strings.Contains(closedOut, id) { + t.Errorf("expected closed issue %s in human list --status=closed:\n%s", id, closedOut) + } + allOut := bdHuman(t, bd, dir, "list", "--status=all") + if !strings.Contains(allOut, id) { + t.Errorf("expected closed issue %s in human list --status=all:\n%s", id, allOut) } - // Create another for Dismiss - cmd = exec.Command(bd, "create", "Dismiss test issue", "--silent") - cmd.Dir = dir - cmd.Env = bdEnv(dir) - out, err = cmd.CombinedOutput() - if err != nil { - t.Fatalf("create failed: %v\n%s", err, out) - } - id2 := strings.TrimSpace(string(out)) - if id2 == "" { - t.Fatalf("could not find issue ID in output: %s", out) - } - - cmd = exec.Command(bd, "label", "add", id2, "human") - cmd.Dir = dir - cmd.Env = bdEnv(dir) - if out, err = cmd.CombinedOutput(); err != nil { - t.Fatalf("label add failed: %v\n%s", err, out) + // An invalid status is an error, not a silent empty list. + if out, _ := bdRunFailCode(t, bd, dir, "human", "list", "--status=colsed"); !strings.Contains(out, "invalid status") { + t.Errorf("expected invalid-status error, got:\n%s", out) } // Test Dismiss + id2 := createHumanBead(t, bd, dir, "Dismiss test issue") bdHuman(t, bd, dir, "dismiss", id2, "--reason", "Not needed") + issue2 := humanShowClosed(t, bd, dir, id2) + if issue2.CloseReason != "Dismissed: Not needed" { + t.Errorf("expected dismiss reason %q, got %q", "Dismissed: Not needed", issue2.CloseReason) + } + }) - // Verify closed - cmd = exec.Command(bd, "show", id2) - cmd.Dir = dir - cmd.Env = bdEnv(dir) - showOut2, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("show failed: %v\n%s", err, showOut2) + // ===== Respond via positional text and --file ===== + + t.Run("human_respond_positional_and_file", func(t *testing.T) { + // Positional response text, multiple words without a flag. + id := createHumanBead(t, bd, dir, "Positional respond test") + bdHuman(t, bd, dir, "respond", id, "Approved,", "proceed", "with", "implementation") + humanShowClosed(t, bd, dir, id) + + // Response text from a file. + id2 := createHumanBead(t, bd, dir, "File respond test") + respFile := filepath.Join(t.TempDir(), "response.md") + if err := os.WriteFile(respFile, []byte("Approved via file\n"), 0o644); err != nil { + t.Fatal(err) } - if !strings.Contains(string(showOut2), "CLOSED") { - t.Errorf("expected issue %s to be closed after dismiss:\n%s", id2, showOut2) + bdHuman(t, bd, dir, "respond", id2, "--file", respFile) + humanShowClosed(t, bd, dir, id2) + + // Positional dismiss reason. + id3 := createHumanBead(t, bd, dir, "Positional dismiss test") + bdHuman(t, bd, dir, "dismiss", id3, "No", "longer", "applicable") + issue3 := humanShowClosed(t, bd, dir, id3) + if issue3.CloseReason != "Dismissed: No longer applicable" { + t.Errorf("expected dismiss reason %q, got %q", "Dismissed: No longer applicable", issue3.CloseReason) } - if !strings.Contains(string(showOut2), "Dismissed: Not needed") { - t.Errorf("expected dismiss reason in output:\n%s", showOut2) + }) + + // ===== Guard rails: conflicting sources and empty text ===== + + t.Run("human_respond_dismiss_guards", func(t *testing.T) { + id := createHumanBead(t, bd, dir, "Guard test bead") + + // Positional text combined with a flag source is a conflict, not a + // silent drop of the positional text. + if out, _ := bdRunFailCode(t, bd, dir, "human", "respond", id, "typed", "text", "--response", "flag text"); !strings.Contains(out, "cannot combine positional text") { + t.Errorf("expected positional/flag conflict error, got:\n%s", out) + } + if out, _ := bdRunFailCode(t, bd, dir, "human", "dismiss", id, "typed", "text", "--reason", "flag text"); !strings.Contains(out, "cannot combine positional text") { + t.Errorf("expected positional/flag conflict error, got:\n%s", out) + } + + // Whitespace-only response must not close the bead. + if _, code := bdRunFailCode(t, bd, dir, "human", "respond", id, " "); code == 0 { + t.Error("whitespace-only response should fail") + } + + // ID-shaped free text is accepted as a dismiss reason like any other + // text: respond/dismiss act on exactly one bead, args[0]. + idText := createHumanBead(t, bd, dir, "Shaped-text bead") + bdHuman(t, bd, dir, "dismiss", idText, "bd-dev") + issueText := humanShowClosed(t, bd, dir, idText) + if issueText.CloseReason != "Dismissed: bd-dev" { + t.Errorf("expected ID-shaped free text kept as dismiss reason, got %q", issueText.CloseReason) + } + + // The bead targeted by the rejected invocations is untouched. + if issue := bdShow(t, bd, dir, id); issue.Status == types.StatusClosed { + t.Errorf("rejected commands must not close the bead, got status %q", issue.Status) } }) } diff --git a/cmd/bd/human_proxied_integration_test.go b/cmd/bd/human_proxied_integration_test.go index 47043a7d4..13ecb6779 100644 --- a/cmd/bd/human_proxied_integration_test.go +++ b/cmd/bd/human_proxied_integration_test.go @@ -3,9 +3,14 @@ package main import ( + "context" + "encoding/json" "os/exec" + "slices" "strings" "testing" + + "github.com/steveyegge/beads/internal/types" ) func bdProxiedHuman(t *testing.T, bd, dir string, args ...string) (string, string) { @@ -202,4 +207,115 @@ func TestProxiedServerHuman(t *testing.T) { t.Errorf("closed beads leaked into open human list:\n%s", listOut) } }) + + // A human-labeled bead can be a WISP: `bd human list` shows the whole + // ephemeral plane, so a bead a person can SEE here must be one they can + // also ANSWER. Before the wisp branch, respond resolved the wisp fine and + // then wrote its comment and close against the durable tables, where the + // row does not exist. + t.Run("respond_on_wisp", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm7") + wisp := bdProxiedCreate(t, bd, p.dir, "Wisp question", "--ephemeral", "--labels", "human") + + // No label warning: the label load has to reach the WISP plane too, + // and a failed load must stay silent rather than claim the label is + // missing. + _, stderr := bdProxiedHuman(t, bd, p.dir, "respond", wisp.ID, "wisp answer") + if strings.Contains(stderr, "does not have 'human' label") { + t.Errorf("unexpected label warning for a human-labeled wisp:\n%s", stderr) + } + + db := openProxiedDB(t, p) + if got := readStatus(t, db, wisp.ID); got != types.StatusClosed { + t.Errorf("expected closed wisp, got status %q", got) + } + var wispComments int + if err := db.QueryRowContext(context.Background(), + "SELECT COUNT(*) FROM wisp_comments WHERE issue_id = ?", wisp.ID).Scan(&wispComments); err != nil { + t.Fatalf("count wisp_comments: %v", err) + } + if wispComments != 1 { + t.Errorf("wisp_comments count = %d, want 1: the comment must land on the wisp plane", wispComments) + } + }) + + // The proxied list must apply the SAME filter as the direct one: closed + // hidden by default, --status=all lifting it, an invalid selector refused + // rather than silently returning nothing. + t.Run("list_filters_and_status_selector", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm8") + open := bdProxiedCreate(t, bd, p.dir, "Open human bead", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, open.ID, "human") + done := bdProxiedCreate(t, bd, p.dir, "Done human bead", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, done.ID, "human") + other := bdProxiedCreate(t, bd, p.dir, "Not for humans", "--type", "task") + bdProxiedHuman(t, bd, p.dir, "dismiss", done.ID) + + out, _ := bdProxiedHuman(t, bd, p.dir, "list") + if !strings.Contains(out, open.ID) { + t.Errorf("expected open human bead in list, got:\n%s", out) + } + if strings.Contains(out, done.ID) || strings.Contains(out, other.ID) { + t.Errorf("expected closed and unlabeled beads hidden, got:\n%s", out) + } + + all, _ := bdProxiedHuman(t, bd, p.dir, "list", "--status=all") + if !strings.Contains(all, open.ID) || !strings.Contains(all, done.ID) { + t.Errorf("expected --status=all to show open and closed beads, got:\n%s", all) + } + + if out := bdProxiedHumanFail(t, bd, p.dir, "list", "--status=colsed"); !strings.Contains(out, "invalid status") { + t.Errorf("expected invalid-status error, got:\n%s", out) + } + + jsonOut, _ := bdProxiedHuman(t, bd, p.dir, "list", "--json") + start := strings.Index(jsonOut, "[") + if start < 0 { + t.Fatalf("no JSON array in human list output:\n%s", jsonOut) + } + var issues []*types.Issue + if err := json.Unmarshal([]byte(jsonOut[start:]), &issues); err != nil { + t.Fatalf("parse human list JSON: %v\nraw: %s", err, jsonOut[start:]) + } + if len(issues) != 1 || issues[0].ID != open.ID { + t.Fatalf("expected exactly the open human bead in JSON, got %+v", issues) + } + // The list no longer re-fetches labels for the JSON path; the search + // already hydrated them. + if !slices.Contains(issues[0].Labels, "human") { + t.Errorf("expected hydrated labels in JSON, got %v", issues[0].Labels) + } + }) + + // Positional response/reason text has to reach the proxied backend the + // same way the flag does — the text sources are resolved BEFORE the + // proxied dispatch, so there is one reading for both routes. + t.Run("positional_text_reaches_the_proxy", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm9") + + answered := bdProxiedCreate(t, bd, p.dir, "Positional respond", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, answered.ID, "human") + bdProxiedHuman(t, bd, p.dir, "respond", answered.ID, "Use", "OAuth2") + commentsOut, _, err := bdProxiedRunBuffers(t, bd, p.dir, "comments", "--json", answered.ID) + if err != nil { + t.Fatalf("bd comments --json failed: %v\n%s", err, commentsOut) + } + var comments []types.Comment + if err := json.Unmarshal([]byte(commentsOut), &comments); err != nil { + t.Fatalf("decode comments JSON: %v\nraw: %q", err, commentsOut) + } + if len(comments) != 1 || comments[0].Text != "Response: Use OAuth2" { + t.Fatalf("expected 1 response comment with the joined text, got %+v", comments) + } + + dropped := bdProxiedCreate(t, bd, p.dir, "Positional dismiss", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, dropped.ID, "human") + bdProxiedHuman(t, bd, p.dir, "dismiss", dropped.ID, "No", "longer", "applicable") + if got := bdProxiedShow(t, bd, p.dir, dropped.ID); got.CloseReason != "Dismissed: No longer applicable" { + t.Errorf("close reason: got %q, want %q", got.CloseReason, "Dismissed: No longer applicable") + } + }) } diff --git a/cmd/bd/human_proxied_server.go b/cmd/bd/human_proxied_server.go index b007af022..10c948add 100644 --- a/cmd/bd/human_proxied_server.go +++ b/cmd/bd/human_proxied_server.go @@ -2,14 +2,15 @@ package main import ( "context" - "encoding/json" + "errors" "fmt" - "os" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/workapi" ) // The proxied-server twins of the four `bd human` subcommands. The direct @@ -19,16 +20,19 @@ import ( // of work; each write invocation is exactly ONE RunTx with a real commit // message, per the proxied write convention. -// proxiedHumanSearch runs the shared human-label query and hands back the -// issues, inside the caller's unit of work. -func proxiedHumanSearch(ctx context.Context, uw uow.UnitOfWork, status string) ([]*types.Issue, error) { - filter := types.IssueFilter{ - Labels: []string{"human"}, - } - if status != "" { - s := types.Status(status) - filter.Status = &s +// proxiedHumanIssues is the proxied-server side of humanIssues: the SAME +// humanListRequest, resolved against the workspace's own status/type config +// and queried through a unit of work. It goes through openAndPrepare rather +// than hand-building a filter so `bd human list` cannot mean one thing in +// direct mode and another behind the proxy — the divergence a second +// hand-built filter here would reintroduce the next time the defaults move. +func proxiedHumanIssues(ctx context.Context, status string) ([]*types.Issue, error) { + uw, filter, err := openAndPrepare(ctx, listInput{ListRequest: humanListRequest(status)}) + if err != nil { + return nil, err } + defer uw.Close(ctx) + page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter) if err != nil { return nil, err @@ -36,141 +40,106 @@ func proxiedHumanSearch(ctx context.Context, uw uow.UnitOfWork, status string) ( return page.Items, nil } -func runHumanListProxiedServer(ctx context.Context, status string) error { - uw, err := proxiedOpenReadUOW(ctx) - if err != nil { - return HandleErrorRespectJSON("listing human beads: %v", err) - } - defer uw.Close(ctx) - - issues, err := proxiedHumanSearch(ctx, uw, status) - if err != nil { - return HandleErrorRespectJSON("listing human beads: %v", err) - } - - if jsonOutput { - issueIDs := make([]string, len(issues)) - for i, issue := range issues { - issueIDs[i] = issue.ID - } - labelsMap, _ := uw.LabelUseCase().GetLabelsForIssues(ctx, issueIDs) - for _, issue := range issues { - issue.Labels = labelsMap[issue.ID] - } - - data, err := json.MarshalIndent(issues, "", " ") - if err != nil { - return HandleErrorRespectJSON("encoding JSON: %v", err) - } - fmt.Println(string(data)) - return nil - } - - printHumanList(issues) - return nil -} - -func runHumanStatsProxiedServer(ctx context.Context) error { - uw, err := proxiedOpenReadUOW(ctx) - if err != nil { - return HandleErrorRespectJSON("getting human bead stats: %v", err) - } - defer uw.Close(ctx) - - issues, err := proxiedHumanSearch(ctx, uw, "") - if err != nil { - return HandleErrorRespectJSON("getting human bead stats: %v", err) - } - - printHumanStats(issues) - return nil -} - -// proxiedHumanCloseTarget is the shared pre-flight for respond and dismiss, -// run INSIDE the write transaction so the already-closed verdict and the close -// ride the same snapshot: the classic existence / already-closed refusals with -// their exact wording, plus the missing-'human'-label observation the caller -// warns about after the transaction lands. -func proxiedHumanCloseTarget(ctx context.Context, uw uow.UnitOfWork, issueID string) (hasHumanLabel bool, err error) { - issue, err := proxiedRequireIssue(ctx, uw, issueID) - if err != nil { - return false, err - } - if issue == nil { - return false, fmt.Errorf("issue not found: %s", issueID) - } - if issue.Status == types.StatusClosed { - return false, fmt.Errorf("issue %s is already closed", issueID) - } - - labelsMap, _ := uw.LabelUseCase().GetLabelsForIssues(ctx, []string{issueID}) - for _, label := range labelsMap[issueID] { - if label == "human" { - return true, nil - } - } - return false, nil -} - -func runHumanRespondProxiedServer(ctx context.Context, issueID, response string) error { - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - - hasHumanLabel, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (bool, string, error) { - hasLabel, err := proxiedHumanCloseTarget(ctx, uw, issueID) - if err != nil { - return false, "", err - } - commentText := fmt.Sprintf("Response: %s", response) - if _, err := uw.CommentUseCase().AddCommentToIssue(ctx, issueID, actor, commentText); err != nil { - return false, "", fmt.Errorf("adding comment: %w", err) - } - if _, err := uw.IssueUseCase().CloseIssue(ctx, issueID, domain.CloseIssueParams{Reason: "Responded"}, actor); err != nil { - return false, "", fmt.Errorf("closing bead: %w", err) - } - return hasLabel, fmt.Sprintf("bd: human respond %s", issueID), nil - }) +// runHumanRespondProxiedServer takes the fully-formatted comment text, not the +// raw response: `bd human respond` resolves its text sources and applies the +// "Response: " shape once, so both backends store identically-shaped comments. +func runHumanRespondProxiedServer(ctx context.Context, issueID, commentText string) error { + res, err := closeHumanProxied(ctx, issueID, commentText, "Responded", "human respond") if err != nil { return HandleErrorRespectJSON("%v", err) } - - if !hasHumanLabel { - fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", issueID) + if res.labelsKnown { + warnIfNotHumanLabeled(res.issue) } - - fmt.Printf("%s Bead %s closed with response.\n", ui.RenderPass("✔"), issueID) + fmt.Printf("%s Bead %s closed with response.\n", ui.RenderPass("✔"), res.issue.ID) return nil } -func runHumanDismissProxiedServer(ctx context.Context, issueID, reason string) error { - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - - closeReason := "Dismissed" - if reason != "" { - closeReason = fmt.Sprintf("Dismissed: %s", reason) - } - - hasHumanLabel, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (bool, string, error) { - hasLabel, err := proxiedHumanCloseTarget(ctx, uw, issueID) - if err != nil { - return false, "", err - } - if _, err := uw.IssueUseCase().CloseIssue(ctx, issueID, domain.CloseIssueParams{Reason: closeReason}, actor); err != nil { - return false, "", fmt.Errorf("closing bead: %w", err) - } - return hasLabel, fmt.Sprintf("bd: human dismiss %s", issueID), nil - }) +// runHumanDismissProxiedServer takes the fully-formatted close reason, not the +// raw dismissal note: `bd human dismiss` resolves its text sources and applies +// the shared dismissedCloseReason prefix once for both backends. +func runHumanDismissProxiedServer(ctx context.Context, issueID, closeReason string) error { + res, err := closeHumanProxied(ctx, issueID, "", closeReason, "human dismiss") if err != nil { return HandleErrorRespectJSON("%v", err) } - - if !hasHumanLabel { - fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", issueID) + if res.labelsKnown { + warnIfNotHumanLabeled(res.issue) } - - fmt.Printf("%s Bead %s dismissed.\n", ui.RenderPass("✔"), issueID) + fmt.Printf("%s Bead %s dismissed.\n", ui.RenderPass("✔"), res.issue.ID) return nil } + +// humanCloseResult carries the bead as read inside the close transaction, with +// its labels when they loaded, so the caller can warn once the transaction has +// committed. labelsKnown separates "loaded, and the label is absent" from "the +// load failed" — only the first is grounds for the advisory warning. +type humanCloseResult struct { + issue *types.Issue + labelsKnown bool +} + +// closeHumanProxied resolves a bead and closes it with closeReason inside ONE +// proxied-server transaction, adding comment first when it is non-empty, so +// the already-closed verdict and the close ride the same snapshot. +// +// It resolves through GetIssueOrWisp rather than proxiedRequireIssue because a +// human-labeled bead can be a WISP: `bd human list` shows the whole ephemeral +// plane, so a bead a person can see here must be one they can also answer. A +// wisp takes the wisp-side comment and close calls; the durable path is +// unchanged. +// +// Close hooks are NOT fired here. They used to need hand-wiring at each +// proxied call site, but the unit-of-work plumbing fires them itself now +// (uow.NewNotifyingProvider, bd-opisf) — buffered during the transaction and +// drained after Commit. A hand-wired call here would fire each hook twice. +func closeHumanProxied(ctx context.Context, id, comment, closeReason, commitVerb string) (humanCloseResult, error) { + if uowProvider == nil { + return humanCloseResult{}, errors.New("proxied-server UOW provider not initialized") + } + return uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (humanCloseResult, string, error) { + src := workapi.NewUOWDetailSource(uw) + issue, isWisp, err := workapi.GetIssueOrWisp(ctx, src, id) + if errors.Is(err, storage.ErrNotFound) { + return humanCloseResult{}, "", fmt.Errorf("issue not found: %s", id) + } + if err != nil { + return humanCloseResult{}, "", fmt.Errorf("resolving issue ID %s: %w", id, err) + } + if issue.Status == types.StatusClosed { + return humanCloseResult{}, "", fmt.Errorf("issue %s is already closed", issue.ID) + } + + res := humanCloseResult{issue: issue} + // Labels feed only the advisory human-label warning, so a failed load + // means no warning — not a warning that the label is missing, which + // is what ignoring the error used to produce. + if labels, lerr := src.Labels(ctx, issue.ID, isWisp); lerr == nil { + issue.Labels = labels + res.labelsKnown = true + } + + if comment != "" { + var cerr error + if isWisp { + _, cerr = uw.CommentUseCase().AddCommentToWisp(ctx, issue.ID, actor, comment) + } else { + _, cerr = uw.CommentUseCase().AddCommentToIssue(ctx, issue.ID, actor, comment) + } + if cerr != nil { + return humanCloseResult{}, "", fmt.Errorf("adding comment: %w", cerr) + } + } + + params := domain.CloseIssueParams{Reason: closeReason} + if isWisp { + _, err = uw.IssueUseCase().CloseWisp(ctx, issue.ID, params, actor) + } else { + _, err = uw.IssueUseCase().CloseIssue(ctx, issue.ID, params, actor) + } + if err != nil { + return humanCloseResult{}, "", fmt.Errorf("closing bead: %w", err) + } + return res, fmt.Sprintf("bd: %s %s", commitVerb, issue.ID), nil + }) +} diff --git a/cmd/bd/human_test.go b/cmd/bd/human_test.go index d4a0945d4..f5b4ad82c 100644 --- a/cmd/bd/human_test.go +++ b/cmd/bd/human_test.go @@ -4,7 +4,9 @@ import ( "strings" "testing" + "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" ) func TestPrintHumanStats(t *testing.T) { @@ -100,11 +102,143 @@ func TestHumanCmdSubcommands(t *testing.T) { } } -func TestHumanRespondRequiresResponseFlag(t *testing.T) { +// TestHumanRespondDismissArgs pins the Args policy for respond and dismiss: +// an issue ID is required and trailing args are free text, not extra IDs +// (MinimumNArgs(1), not ExactArgs(1)). End-to-end coverage lives in the +// embedded tests, which are env-gated — this always-run check guards the +// declaration itself. +func TestHumanRespondDismissArgs(t *testing.T) { + for _, cmd := range []*cobra.Command{humanRespondCmd, humanDismissCmd} { + if err := cmd.Args(cmd, []string{"bd-123", "free", "text"}); err != nil { + t.Errorf("%s should accept positional free text after the ID: %v", cmd.Name(), err) + } + if err := cmd.Args(cmd, []string{}); err == nil { + t.Errorf("%s should still require an issue ID", cmd.Name()) + } + } +} + +func TestHumanListFilter(t *testing.T) { + cfg := workapi.ListConfig{ + CustomStatuses: []types.CustomStatus{ + {Name: "archived", Category: types.CategoryDone}, + {Name: "review", Category: types.CategoryActive}, + }, + } + + t.Run("default hides the canonical done/frozen statuses", func(t *testing.T) { + filter, err := humanListFilter("", cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + excluded := make(map[types.Status]bool) + for _, s := range filter.ExcludeStatus { + excluded[s] = true + } + for _, want := range []types.Status{types.StatusClosed, types.StatusPinned, "archived"} { + if !excluded[want] { + t.Errorf("default filter should exclude %q, got ExcludeStatus=%v", want, filter.ExcludeStatus) + } + } + if excluded["review"] { + t.Errorf("active-category custom status should not be excluded, got %v", filter.ExcludeStatus) + } + if filter.Status != nil { + t.Errorf("default filter should not pin a status, got %v", *filter.Status) + } + }) + + t.Run("default hides pinned beads but no bead types", func(t *testing.T) { + filter, err := humanListFilter("", cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if filter.Pinned == nil || *filter.Pinned { + t.Errorf("default filter should hide boolean-pinned beads, got Pinned=%v", filter.Pinned) + } + if filter.Limit != 0 { + t.Errorf("human list should stay unlimited, got Limit=%d", filter.Limit) + } + }) + + t.Run("no bead type is ever hidden", func(t *testing.T) { + for _, status := range []string{"", "open", "all"} { + filter, err := humanListFilter(status, cfg) + if err != nil { + t.Fatalf("unexpected error for status %q: %v", status, err) + } + if len(filter.ExcludeTypes) != 0 { + t.Errorf("status %q: human list must not exclude bead types (gates, infra), got %v", status, filter.ExcludeTypes) + } + if filter.SkipWisps { + t.Errorf("status %q: human list must show human-labeled wisps", status) + } + if filter.IsTemplate != nil { + t.Errorf("status %q: human list must not hide templates, got IsTemplate=%v", status, *filter.IsTemplate) + } + } + }) + + t.Run("explicit status overrides default", func(t *testing.T) { + filter, err := humanListFilter("closed", cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if filter.Status == nil || *filter.Status != types.StatusClosed { + t.Errorf("expected Status=closed, got %v", filter.Status) + } + if len(filter.ExcludeStatus) != 0 { + t.Errorf("explicit status should drop the default exclusions, got %v", filter.ExcludeStatus) + } + }) + + t.Run("all shows every status", func(t *testing.T) { + filter, err := humanListFilter("all", cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if filter.Status != nil || len(filter.Statuses) != 0 || len(filter.ExcludeStatus) != 0 { + t.Errorf("--status=all should not constrain status, got Status=%v Statuses=%v ExcludeStatus=%v", + filter.Status, filter.Statuses, filter.ExcludeStatus) + } + }) + + t.Run("invalid status is refused", func(t *testing.T) { + if _, err := humanListFilter("nonesuch", cfg); err == nil { + t.Error("expected an error for an unknown status") + } + }) + + t.Run("always filters on human label", func(t *testing.T) { + for _, status := range []string{"", "open", "all"} { + filter, err := humanListFilter(status, cfg) + if err != nil { + t.Fatalf("unexpected error for status %q: %v", status, err) + } + if len(filter.Labels) != 1 || filter.Labels[0] != "human" { + t.Errorf("expected Labels=[human] for status %q, got %v", status, filter.Labels) + } + } + }) +} + +func TestHumanRespondTextSourceFlags(t *testing.T) { + for _, name := range []string{"file", "stdin"} { + if humanRespondCmd.Flags().Lookup(name) == nil { + t.Errorf("respond command should have --%s flag", name) + } + } + + // --response must not be marked required: the response can also come from + // --file, --stdin, or positional args, and cobra rejects those invocations + // before RunE if the flag carries the required annotation. flag := humanRespondCmd.Flags().Lookup("response") if flag == nil { t.Fatal("respond command should have --response flag") } + if len(flag.Annotations[cobra.BashCompOneRequiredFlag]) > 0 { + t.Error("--response must not be hard-required; --file/--stdin/positional text are valid sources") + } } func TestHumanDismissHasReasonFlag(t *testing.T) { diff --git a/cmd/bd/note.go b/cmd/bd/note.go index ac959f9b2..c0f7e772d 100644 --- a/cmd/bd/note.go +++ b/cmd/bd/note.go @@ -2,9 +2,6 @@ package main import ( "fmt" - "io" - "os" - "strings" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" @@ -131,31 +128,10 @@ To read notes on an issue, use: bd show `, id := args[0] textArgs := args[1:] - stdinFlag, _ := cmd.Flags().GetBool("stdin") - fileFlag, _ := cmd.Flags().GetString("file") - - var noteText string - switch { - case stdinFlag: - content, err := io.ReadAll(os.Stdin) - if err != nil { - return HandleErrorRespectJSON("reading from stdin: %v", err) - } - noteText = strings.TrimRight(string(content), "\n") - case fileFlag != "": - content, err := readBodyFile(fileFlag) - if err != nil { - return HandleErrorRespectJSON("reading file: %v", err) - } - noteText = content - case len(textArgs) > 0: - noteText = strings.Join(textArgs, " ") - default: - return HandleErrorRespectJSON("no note text provided (use positional args, --stdin, or --file)") - } - - if noteText == "" { - return HandleErrorRespectJSON("note text is empty") + noteText, err := requireTextFromSources("note text", "use positional args, --stdin, or --file", + cmdTextSources(cmd, textArgs)) + if err != nil { + return HandleErrorRespectJSON("%v", err) } if usesProxiedServer() { @@ -223,9 +199,7 @@ To read notes on an issue, use: bd show `, } func init() { - noteCmd.Flags().Bool("stdin", false, "Read note text from stdin") - noteCmd.Flags().String("file", "", "Read note text from file") - noteCmd.MarkFlagsMutuallyExclusive("stdin", "file") + registerTextSourceFlags(noteCmd, "note text") noteCmd.ValidArgsFunction = issueIDCompletion rootCmd.AddCommand(noteCmd) } diff --git a/cmd/bd/proxied_lookup_failure_test.go b/cmd/bd/proxied_lookup_failure_test.go index c89a71771..e2469c34a 100644 --- a/cmd/bd/proxied_lookup_failure_test.go +++ b/cmd/bd/proxied_lookup_failure_test.go @@ -109,16 +109,6 @@ func showViewCmd(view string) *cobra.Command { return cmd } -// cmdWithStringFlag registers one string flag so the command under test does -// not fall back to an environment lookup for it - `bd comment add` shells out -// to git for the author when --author is empty, which has nothing to do with -// what is being tested here. -func cmdWithStringFlag(name, value string) *cobra.Command { - cmd := &cobra.Command{} - cmd.Flags().String(name, value, "") - return cmd -} - // closeReasonCmd registers the reason flags `bd close` reads before it resolves // anything. collectCloseReasonFlags returns an error for an unregistered one, // which would abort the command ahead of the lookup under test. @@ -336,11 +326,27 @@ var proxiedLookupCommands = []struct { { name: "comment add", run: func(ctx context.Context) error { - return runCommentsAddProxiedServer(cmdWithStringFlag("author", "tester"), ctx, []string{stubMissingID, "hello"}) + return runCommentsAddProxiedServer(ctx, stubMissingID, "tester", "hello") }, wantNotFound: "Error: issue bd-missing not found", wantHardErr: "Error: resolving bd-missing: connection reset by peer", }, + { + name: "human respond", + run: func(ctx context.Context) error { + return runHumanRespondProxiedServer(ctx, stubMissingID, "Response: resp") + }, + wantNotFound: "Error: issue not found: bd-missing", + wantHardErr: "Error: resolving issue ID bd-missing: connection reset by peer", + }, + { + name: "human dismiss", + run: func(ctx context.Context) error { + return runHumanDismissProxiedServer(ctx, stubMissingID, "Dismissed") + }, + wantNotFound: "Error: issue not found: bd-missing", + wantHardErr: "Error: resolving issue ID bd-missing: connection reset by peer", + }, } // TestProxiedLookupReportsMissingIssue covers the errors.Is(storage.ErrNotFound) diff --git a/internal/workapi/list.go b/internal/workapi/list.go index 014c379c3..6132a22be 100644 --- a/internal/workapi/list.go +++ b/internal/workapi/list.go @@ -218,16 +218,22 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter MaxRowsSource: in.MaxRowsSource, } + // The status selector is parsed once here; every consumer below — the + // "all" short-circuit, the default exclusions, the pinned default — + // works from the same parts so their readings cannot drift. + statusParts := splitStatusSelector(in.Status) + statusAll := len(statusParts) == 1 && statusParts[0] == "all" + if in.ReadyFlag { s := types.StatusOpen filter.Status = &s - } else if in.Status != "" && in.Status != "all" { - if err := ApplyStatusFilter(&filter, in.Status, cfg.CustomStatusNames()); err != nil { + } else if len(statusParts) > 0 && !statusAll { + if err := applyStatusParts(&filter, statusParts, cfg.CustomStatusNames()); err != nil { return filter, err } } - if in.Status == "" && !in.AllFlag && !in.ReadyFlag && !in.PinnedFlag { + if len(statusParts) == 0 && !in.AllFlag && !in.ReadyFlag && !in.PinnedFlag { excludeStatuses := []types.Status{types.StatusClosed, types.StatusPinned} for _, cs := range cfg.CustomStatuses { if cs.Category == types.CategoryDone || cs.Category == types.CategoryFrozen { @@ -336,25 +342,12 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter if in.PinnedFlag { pinned := true filter.Pinned = &pinned - } else if in.NoPinnedFlag || (in.Status != "pinned" && in.Status != "hooked" && !in.AllFlag) { + } else if in.NoPinnedFlag || (!statusSelectsPinned(statusParts, !in.ReadyFlag) && !in.AllFlag) { pinned := false filter.Pinned = &pinned } - if !in.IncludeTemplates { - isTemplate := false - filter.IsTemplate = &isTemplate - } - - if !in.IncludeGates && in.IssueType != "gate" { - filter.ExcludeTypes = append(filter.ExcludeTypes, "gate") - } - - if !in.IncludeInfra && !cfg.IsInfra(in.IssueType) { - for _, t := range cfg.InfraTypes() { - filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(t)) - } - } + applyTypeSuppressions(in, cfg, &filter) for _, raw := range in.ExcludeTypes { for _, t := range strings.Split(raw, ",") { @@ -406,15 +399,83 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter return filter, err } + return filter, nil +} + +// applyTypeSuppressions applies every default suppression that hides a bead on +// account of WHAT IT IS, so that a "show everything" frontend has exactly one +// thing to skip. Two kinds live here: the type-level exclusions that make the +// default listing show durable work only (templates, gates, infra types), and +// the plane decision — whether the wisps TABLE is read at all. +// +// IncludeAllTypes lifts them ALL by skipping this function entirely, which is +// what makes it future-proof: a suppression added here is automatically lifted +// for frontends like `bd human list` without touching them. +func applyTypeSuppressions(in issueops.ListRequest, cfg ListConfig, filter *types.IssueFilter) { + if in.IncludeAllTypes { + return + } + + if !in.IncludeTemplates { + isTemplate := false + filter.IsTemplate = &isTemplate + } + + if !in.IncludeGates && in.IssueType != "gate" { + filter.ExcludeTypes = append(filter.ExcludeTypes, "gate") + } + + if !in.IncludeInfra && !cfg.IsInfra(in.IssueType) { + for _, t := range cfg.InfraTypes() { + filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(t)) + } + } + // The plane bit. Three requests admit the wisp table: an explicit // IncludeEphemeral, IncludeInfra (which admits the plane AND drops the // infra-type exclusions above), and naming an infra type (which routed to - // the plane alone a few lines up). Everything else is the durable listing. + // the plane alone in BuildListFilter). Everything else is the durable + // listing. IncludeAllTypes is a fourth, via the early return above — it is + // the union of these flags, so it must decide the plane too, not only the + // type exclusions. if !in.IncludeEphemeral && !in.IncludeInfra && (in.IssueType == "" || !cfg.IsInfra(in.IssueType)) { filter.SkipWisps = true } +} - return filter, nil +// splitStatusSelector splits a --status selector into its trimmed +// comma-separated parts. An empty selector yields nil. This is the only +// reading of the selector syntax; everything downstream works on the parts. +func splitStatusSelector(status string) []string { + if status == "" { + return nil + } + parts := strings.Split(status, ",") + for i := range parts { + parts[i] = strings.TrimSpace(parts[i]) + } + return parts +} + +// statusSelectsPinned reports whether a status selector asks for +// pinned-carrying beads: the pinned or hooked status, or — when the selector +// actually applies to the query — the "all" selector, which promises every +// status. The pinned default is not forced off for a filter that asks for +// those beads. allApplies is false under --ready, which forces status open +// and otherwise ignores the selector, so "all" must not lift the pinned +// default there. +func statusSelectsPinned(parts []string, allApplies bool) bool { + for _, part := range parts { + switch part { + case "pinned", "hooked": + return true + case "all": + if allApplies { + return true + } + } + } + return false } // ValidStatusList renders the status names a filter accepts, for error text. @@ -429,20 +490,33 @@ func ValidStatusList(customStatusNames []string) string { // ApplyStatusFilter parses a status selector - one status, or a // comma-separated OR set - onto the filter. func ApplyStatusFilter(filter *types.IssueFilter, status string, customStatusNames []string) error { - statusParts := strings.Split(status, ",") - if len(statusParts) == 1 { - s := types.Status(strings.TrimSpace(statusParts[0])) + parts := splitStatusSelector(status) + if len(parts) == 0 { + return fmt.Errorf("invalid status %q (valid: %s)", status, ValidStatusList(customStatusNames)) + } + return applyStatusParts(filter, parts, customStatusNames) +} + +func applyStatusParts(filter *types.IssueFilter, parts []string, customStatusNames []string) error { + if len(parts) == 1 { + s := types.Status(parts[0]) if !s.IsValidWithCustom(customStatusNames) { - return fmt.Errorf("invalid status %q (valid: %s)", status, ValidStatusList(customStatusNames)) + return fmt.Errorf("invalid status %q (valid: %s)", parts[0], ValidStatusList(customStatusNames)) } filter.Status = &s return nil } - for _, part := range statusParts { - s := types.Status(strings.TrimSpace(part)) + for _, part := range parts { + s := types.Status(part) if !s.IsValidWithCustom(customStatusNames) { - return fmt.Errorf("invalid status %q in multi-status filter (valid: %s)", strings.TrimSpace(part), ValidStatusList(customStatusNames)) + // "all" is a real selector on its own (every status), so failing + // it as merely "invalid" would contradict the flag help. A custom + // status literally named "all" passes validation above instead. + if part == "all" { + return fmt.Errorf(`status "all" cannot be combined with other statuses`) + } + return fmt.Errorf("invalid status %q in multi-status filter (valid: %s)", part, ValidStatusList(customStatusNames)) } filter.Statuses = append(filter.Statuses, s) } diff --git a/internal/workapi/list_golden_test.go b/internal/workapi/list_golden_test.go index f81b2fcbb..bca18820e 100644 --- a/internal/workapi/list_golden_test.go +++ b/internal/workapi/list_golden_test.go @@ -29,6 +29,13 @@ type listFilterGoldenCase struct { // was nothing to record them from. They pin what the leaf promises // (issueops.ListRequest.MaxRows and .SkipCounts), which is the same standard // the conformance contract holds the implementations to. +// +// ONE case has been deliberately RE-recorded rather than preserved: +// status_all_keyword's Pinned went false -> null. The old builder compared the +// raw selector string to "pinned"/"hooked", so --status=all — which promises +// EVERY status — silently kept forcing Pinned=false and hid pinned beads from +// the one selector that says it hides nothing. TestPinnedDefaultBySelector +// below owns that behavior now; see the PR body for the compatibility note. func TestBuildListFilterGolden(t *testing.T) { blob, err := os.ReadFile(filepath.Join("testdata", "list_filter_golden.json")) if err != nil { diff --git a/internal/workapi/list_pinned_test.go b/internal/workapi/list_pinned_test.go new file mode 100644 index 000000000..58d36280c --- /dev/null +++ b/internal/workapi/list_pinned_test.go @@ -0,0 +1,163 @@ +package workapi + +import ( + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// TestPinnedDefaultBySelector owns the rule that decides whether a listing +// forces Pinned=false: a selector that ASKS for pinned-carrying beads must not +// then have them filtered back out. +// +// The old builder compared the raw --status string to "pinned"/"hooked", so +// two selectors that do ask for those beads were still getting the exclusion: +// "all", which promises every status, and any multi-status set containing +// pinned or hooked ("pinned,closed"), which never matched the two string +// equalities. Both now lift the default. This is the observable behavior +// change riding on this filter work — scripts that relied on --status=all +// hiding pinned beads will see them appear — so it is pinned HERE, not left to +// the golden table. +func TestPinnedDefaultBySelector(t *testing.T) { + var cfg ListConfig + + // pinnedDefault reports filter.Pinned as a tri-state: nil (no constraint, + // i.e. pinned beads are admitted) or the forced value. + pinnedDefault := func(t *testing.T, in issueops.ListRequest) *bool { + t.Helper() + filter, err := BuildListFilter(in, cfg) + if err != nil { + t.Fatalf("BuildListFilter(%+v): %v", in, err) + } + return filter.Pinned + } + + t.Run("selectors that ask for pinned beads lift the default", func(t *testing.T) { + for _, status := range []string{"pinned", "hooked", "all", "pinned,closed", "closed,hooked", " all "} { + if got := pinnedDefault(t, issueops.ListRequest{Status: status}); got != nil { + t.Errorf("--status=%q: Pinned = %v, want nil (no pinned exclusion)", status, *got) + } + } + }) + + t.Run("every other selector keeps the exclusion", func(t *testing.T) { + for _, status := range []string{"", "open", "closed", "open,closed", "in_progress"} { + got := pinnedDefault(t, issueops.ListRequest{Status: status}) + if got == nil || *got { + t.Errorf("--status=%q: Pinned = %v, want false", status, got) + } + } + }) + + t.Run("--no-pinned wins over the selector", func(t *testing.T) { + for _, status := range []string{"pinned", "all", "pinned,closed"} { + got := pinnedDefault(t, issueops.ListRequest{Status: status, NoPinnedFlag: true}) + if got == nil || *got { + t.Errorf("--status=%q --no-pinned: Pinned = %v, want false", status, got) + } + } + }) + + t.Run("--pinned forces pinned-only regardless of selector", func(t *testing.T) { + got := pinnedDefault(t, issueops.ListRequest{Status: "all", PinnedFlag: true}) + if got == nil || !*got { + t.Errorf("--status=all --pinned: Pinned = %v, want true", got) + } + }) + + // --ready forces status open and otherwise IGNORES the selector, so an + // "all" that the query never applies must not have a pinned side effect + // either. Without this, `bd list --ready --status=all` would admit pinned + // beads into a ready listing that is filtered to open. + t.Run("--ready ignores the selector, including for pinned", func(t *testing.T) { + got := pinnedDefault(t, issueops.ListRequest{Status: "all", ReadyFlag: true}) + if got == nil || *got { + t.Errorf("--ready --status=all: Pinned = %v, want false", got) + } + }) +} + +// TestIncludeAllTypesLiftsEverySuppression pins IncludeAllTypes as the union of +// the type knobs AND the plane knob: nothing is hidden for being a template, a +// gate, an infra type, or a wisp. It is the guarantee `bd human list` rests on. +func TestIncludeAllTypesLiftsEverySuppression(t *testing.T) { + cfg := ListConfig{} + + t.Run("lifts type exclusions and admits the ephemeral plane", func(t *testing.T) { + filter, err := BuildListFilter(issueops.ListRequest{IncludeAllTypes: true}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if len(filter.ExcludeTypes) != 0 { + t.Errorf("ExcludeTypes = %v, want none", filter.ExcludeTypes) + } + if filter.IsTemplate != nil { + t.Errorf("IsTemplate = %v, want nil (templates not hidden)", *filter.IsTemplate) + } + if filter.SkipWisps { + t.Error("SkipWisps = true, want false: IncludeAllTypes must admit the ephemeral plane") + } + }) + + t.Run("without it the default listing still suppresses", func(t *testing.T) { + filter, err := BuildListFilter(issueops.ListRequest{}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if len(filter.ExcludeTypes) == 0 { + t.Error("default listing should exclude gate/infra types") + } + if filter.IsTemplate == nil || *filter.IsTemplate { + t.Errorf("IsTemplate = %v, want false", filter.IsTemplate) + } + if !filter.SkipWisps { + t.Error("SkipWisps = false, want true for a default listing") + } + }) + + // It is a TYPE/plane knob only: the status axis is untouched, so the + // done/frozen exclusions and the pinned default still apply. + t.Run("says nothing about status", func(t *testing.T) { + filter, err := BuildListFilter(issueops.ListRequest{IncludeAllTypes: true}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if len(filter.ExcludeStatus) == 0 { + t.Error("IncludeAllTypes must not lift the default status exclusions") + } + if filter.Pinned == nil || *filter.Pinned { + t.Errorf("Pinned = %v, want false: IncludeAllTypes must not lift the pinned default", filter.Pinned) + } + }) + + // ExcludeTypes is the caller's own explicit exclusion, not a default + // suppression, so IncludeAllTypes must leave it alone. + t.Run("explicit ExcludeTypes still applies", func(t *testing.T) { + filter, err := BuildListFilter(issueops.ListRequest{ + IncludeAllTypes: true, + ExcludeTypes: []string{"gate"}, + }, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if len(filter.ExcludeTypes) != 1 || filter.ExcludeTypes[0] != types.IssueType("gate") { + t.Errorf("ExcludeTypes = %v, want [gate]", filter.ExcludeTypes) + } + }) +} + +// TestStatusAllCannotBeCombined pins the error a multi-status set containing +// "all" gets: "all" is a real selector on its own, so reporting it as merely +// invalid would contradict the flag help. +func TestStatusAllCannotBeCombined(t *testing.T) { + var filter types.IssueFilter + err := ApplyStatusFilter(&filter, "all,open", nil) + if err == nil { + t.Fatal("expected an error for --status=all,open") + } + want := `status "all" cannot be combined with other statuses` + if err.Error() != want { + t.Errorf("error = %q, want %q", err, want) + } +} diff --git a/internal/workapi/testdata/list_filter_golden.json b/internal/workapi/testdata/list_filter_golden.json index db02041b8..e1bb2510f 100644 --- a/internal/workapi/testdata/list_filter_golden.json +++ b/internal/workapi/testdata/list_filter_golden.json @@ -449,7 +449,7 @@ "PriorityMax": null, "SourceRepo": null, "Ephemeral": null, - "Pinned": false, + "Pinned": null, "IsBlocked": null, "IsTemplate": false, "ParentID": null, diff --git a/issueops/reader.go b/issueops/reader.go index 0d12ba1d4..60c410c00 100644 --- a/issueops/reader.go +++ b/issueops/reader.go @@ -256,6 +256,25 @@ type ListRequest struct { // // On the ReadyFlag arm it is CARRIED rather than dropped; see that field. IncludeEphemeral bool + // IncludeAllTypes lifts every default suppression that hides a bead from a + // listing on account of WHAT IT IS: the three type knobs above (templates, + // gates, infra types) AND the ephemeral plane, so the wisps table is read + // too. Frontends whose contract is "never hide a bead" — `bd human list`, + // where a human label is an explicit request for a person's attention — + // set this one field instead of enumerating the knobs and then drifting + // from them when a fourth suppression lands. + // + // IT IS THE UNION OF THOSE FLAGS, NOT A NEW MECHANISM. Setting it is + // equivalent to IncludeTemplates + IncludeGates + IncludeInfra + + // IncludeEphemeral; it narrows nothing and admits nothing they cannot. + // Both the type suppressions and the plane decision live in workapi's + // applyTypeSuppressions, which this flag skips entirely — so a suppression + // added there is lifted here automatically, which is the whole point. + // + // IT SAYS NOTHING ABOUT STATUS. The done/frozen exclusions and the pinned + // default are a separate axis and still apply; --status (including "all") + // is how a caller lifts those. + IncludeAllTypes bool // ExcludeTypes entries may be comma-separated; splitting happens inside. ExcludeTypes []string