beads/cmd/bd/human_embedded_test.go
Isis Anisoptera c8dd08c262
fix(human): respond/dismiss text sources, bd list parity, and proxied-server support (#5333)
* fix(cli): one text-source layer for comment, note, and human respond

`bd comment`, `bd note` and `bd comments add` each read their body text a
little differently, and all three applied a SILENT precedence when a caller
gave two sources: positional text plus --stdin or --file resolved to the flag
and dropped the positional half with no message. In every case we could find,
the dropped half was the text the caller meant.

One textSources layer now owns the reading for all of them. Naming two sources
is an ERROR ("cannot combine positional text ... with --stdin") rather than a
precedence question; --file content is passed through verbatim, matching every
other file-input flag (--body-file, --design-file, --reason-file), while stdin
keeps trimming the trailing newline a shell appends; and an explicitly-set-but-
empty text flag counts as a source via cobra's Changed, so `--response ""` gets
"cannot be empty" rather than "no text provided".

`bd human respond` joins them: its response can come from positional args,
--response, --file or --stdin, so --response is no longer a required flag.
`bd human dismiss` takes its reason positionally as well as via --reason, and
both accept trailing free text (`<id> [text...]`) the way `bd comment` does —
a second argument is text, never a second id. The "Response: " prefix and the
shared Dismissed close reason are now formatted ONCE, before the proxied
dispatch, so the two backends cannot shape them differently; the same move
lets the proxied comment entry points take resolved text instead of re-reading
the flags themselves.

`human stats` classifies dismissals by that shared Dismissed prefix instead of
a case-insensitive substring search for "dismiss", so the writer and the
classifier cannot drift. Beads closed earlier with a lowercase or mid-string
"dismiss" move from the Dismissed count to Responded; CHANGELOG carries the
note.

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

* fix(human): bring `human list`/`stats` to bd list parity via IncludeAllTypes

`bd human list` built its own two-field filter: a label match plus whatever
--status the caller typed, unvalidated. So it showed closed beads by default
where `bd list` hides them, answered a typo'd status with a silent empty list
instead of an error, and — because it never went through the shared builder —
could not be told what a default listing is SUPPOSED to hide.

It goes through workapi.BuildListFilter now, which gets it the done/frozen
status exclusions, the pinned default, status validation against built-in and
custom names, comma-separated sets, and "all". `human stats` counts the same
universe (--status=all) through the same path, and the proxied side calls
openAndPrepare rather than hand-building a second filter, so the command
cannot mean one thing in direct mode and another behind the proxy.

What it must NOT inherit is the type suppression: 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. That is
the new issueops.ListRequest.IncludeAllTypes — the union of IncludeTemplates,
IncludeGates, IncludeInfra AND IncludeEphemeral. Both the type exclusions and
the PLANE decision now live in one applyTypeSuppressions that the flag skips
whole, so it decides the ephemeral plane too rather than lifting three type
knobs and leaving `bd human list` blind to human-labeled wisps. A suppression
added there in future is lifted here without touching this command.

Two pinned fixes fall out of parsing the status selector ONCE instead of
comparing the raw string in three places:

  * --status=all no longer forces Pinned=false. "all" promises every status;
    the string comparison never matched it, so the one selector that hides
    nothing kept hiding pinned beads. The golden case status_all_keyword is
    re-recorded (Pinned false -> null) and TestPinnedDefaultBySelector owns
    the rule now.
  * --status=pinned,closed no longer excludes the pinned beads it asks for —
    the same comparison missed every multi-status set.

--ready is deliberately unaffected: it forces status open and otherwise
ignores the selector, so an "all" the query never applies must not have a
pinned side effect either.

BEHAVIOR CHANGE, called out in CHANGELOG: scripts using --status=all as a way
to list everything EXCEPT pinned beads will see pinned beads appear. Add
--no-pinned to keep the old result.

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

* fix(human): let proxied respond/dismiss answer wisps, and stop the phantom label warning

Two gaps in the proxied twins of `bd human respond`/`dismiss`, both of which
`bd human list` showing every bead type now makes reachable:

WISPS. The pair resolved through proxiedRequireIssue and then wrote the
comment and the close against the DURABLE tables. A human-labeled wisp is a
bead a person can see in `bd human list` — so it has to be one they can also
answer. Resolution goes through workapi.GetIssueOrWisp and the write side
branches: AddCommentToWisp/CloseWisp for the ephemeral plane, unchanged calls
for the durable one, still inside the single RunTx the proxied write
convention asks for.

THE ADVISORY WARNING FIRED ON A FAILED LOAD. The missing-'human'-label warning
read labels with the error discarded, so a label load that FAILED was
indistinguishable from a bead with no human label, and the user was told the
label was missing when nothing had been checked. The result now carries
labelsKnown, and a failed load simply warns nothing.

NOT salvaged: the post-commit close-hook firing this branch originally carried.
It was written when each proxied call site hand-wired its own hooks; main has
since moved firing onto the unit-of-work plumbing (uow.NewNotifyingProvider,
bd-opisf), which buffers during the transaction and drains after Commit. The
proxied human close already fires its hooks — a hand-wired call here would
fire each one twice. The reason is recorded on closeHumanProxied so the next
reader does not re-add it.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 05:36:11 -07:00

245 lines
7.7 KiB
Go

//go:build cgo
package main
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.
func bdHuman(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
fullArgs := append([]string{"human"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd human %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, stdout.String(), stderr.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")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "th")
// ===== Default Help Output =====
t.Run("human_default", func(t *testing.T) {
out := bdHuman(t, bd, dir)
if len(strings.TrimSpace(out)) == 0 {
t.Error("expected non-empty human output")
}
})
// ===== List =====
t.Run("human_list_empty", func(t *testing.T) {
out := bdHuman(t, bd, dir, "list")
// No human-labeled issues yet — should succeed without error
_ = out
})
// ===== Stats =====
t.Run("human_stats", func(t *testing.T) {
out := bdHuman(t, bd, dir, "stats")
// Should succeed and produce output
if len(strings.TrimSpace(out)) == 0 {
t.Error("expected non-empty stats output")
}
})
// ===== Respond and Dismiss =====
t.Run("human_respond_and_dismiss", func(t *testing.T) {
id := createHumanBead(t, bd, dir, "Human test issue")
// Verify it shows up in human list
listOut := bdHuman(t, bd, dir, "list")
if !strings.Contains(listOut, id) {
t.Errorf("expected issue %s in human list output:\n%s", id, listOut)
}
// Test Respond
bdHuman(t, bd, dir, "respond", id, "--response", "Approved")
humanShowClosed(t, bd, dir, id)
// 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)
}
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)
}
// 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)
}
})
// ===== 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)
}
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)
}
})
// ===== 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)
}
})
}
// TestEmbeddedHumanConcurrent exercises human operations concurrently.
func TestEmbeddedHumanConcurrent(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")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "hx")
const numWorkers = 8
type workerResult struct {
worker int
err error
}
results := make([]workerResult, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 0; w < numWorkers; w++ {
go func(worker int) {
defer wg.Done()
r := workerResult{worker: worker}
var args []string
switch worker % 2 {
case 0:
args = []string{"human", "list"}
case 1:
args = []string{"human", "stats"}
}
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("human (worker %d): %v\n%s", worker, err, out)
results[worker] = r
return
}
results[worker] = r
}(w)
}
wg.Wait()
for _, r := range results {
if r.err != nil && !strings.Contains(r.err.Error(), "one writer at a time") {
t.Errorf("worker %d failed: %v", r.worker, r.err)
}
}
}