From f142cc2ffdece62ae5830a7f436e4949a48c79fe Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Mon, 19 Oct 2026 03:41:08 +0000 Subject: [PATCH] test(cli): before-parity pins for --format json, ordinary --if-revision, and version/config/history/as-of shapes (P7, P8, P10) (#7676) * test(cli): pin --format json == --json on show, list, ready and memories Before-parity pin P7 (gap analysis 2026-10-17, section 5a). The hidden root --format flag is an alias for --json (GH#2612). It is a root persistent flag, so a subcommand that registers a --format of its own shadows it (the GH#6278 hazard): `bd list` already does and passes `json` through by hand, and a graph-preview fork that added a local --format to `bd show` made `bd show ID --format json` exit nonzero. TestEmbeddedFormatJSONAliasMatchesJSON runs show, list, ready and memories with --json and then with `--format json`, `--format=json` and a leading `bd --format json `, and requires exit 0 and byte-identical stdout. It adds bdRunStreams, a small helper returning stdout, stderr and the exit status separately, which the following pins reuse. The new TestEmbedded* function is listed in the bd_test srcs and placed in the 100-shard embedded cmd manifest by gen_embedded_cmd_shard_manifest.py --write (incremental). Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) * test(cli): pin the ordinary --if-revision compare-and-swap contract Before-parity pin P8 (gap analysis 2026-10-17, section 5a). --if-revision is the decimal int64 compare-and-swap merged in #7203, and gascity's bdstore_conditional.go classifier reads both its exit status and its machine body. A second, opaque-token meaning for the same flag in another kind of workspace must leave the ordinary one unchanged. TestEmbeddedIfRevisionOrdinaryCAS pins, through the real binary: - a stale decimal token on update, close, assign and delete (preview and --force) exits 13, prints nothing on stdout, writes nothing, and ends stderr with a precondition_failed body naming the id and the expected and current revisions as exact JSON integers; - a non-decimal token exits 1 with the "invalid --if-revision" refusal in text and --json modes, never 13, and writes nothing; - the current token applies on update, close, assign and delete. It is the ordinary-workspace half of TestGraphPreviewIfRevisionOutsideLinkModeIsUpstreamCAS from the donnabox/codex/preview3-source-catchup-46aa branch (added in 3d16d826be, revised in 1640940fa9, 3ff2fe73ce, 55dbb61156, 653369305a and 97446d1f08), ported onto this package's embedded helpers. The port drops the graph-only forget refusal, extends the stale and non-decimal cases from update/delete to close and assign, and compares revisions as json.Number rather than float64, since they are int64 values past 2^53. It is named TestEmbedded* so the bazel-embedded lane, which discovers `^func TestEmbedded` in *_embedded_test.go, runs it; the existing TestIfRevisionMatchAndMismatch is not discovered there. The file is listed in the bd_test srcs and placed in the 100-shard embedded cmd manifest by gen_embedded_cmd_shard_manifest.py --write (incremental). Co-authored-by: Jim Wordelman Co-authored-by: Donna Box Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) * test(cli): pin version, config set, history and show --as-of shapes Before-parity pin P10 (gap analysis 2026-10-17, section 5a): the store-less and history-adjacent commands a later versioned-history or graph slice could change by accident. - TestEmbeddedVersionOutputShape: `bd version` with no arguments exits 0 and prints one "bd version (...)" line, in a workspace and outside one; --json is one object with version, build and schema_version (plus commit and branch when known) agreeing with the text line, and --format json prints the same document; an argument exits 1 and points at `bd versions ` (#6661), on stderr or as the --json error, through the real binary rather than RunE. - TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan: in a store holding a row the pre-enable scan refuses over, `bd config set` and `bd config set-many` of another key with the value "true" exit 0, store it, print no refusal and leave the switch off; the switch itself is still refused afterwards, as a control. - TestEmbeddedHistoryAndShowAsOfReadDoltCommits: with versioned history recording, `bd history --json` is still the Dolt-commit history (an array of CommitHash/Committer/CommitDate/Issue entries with full 32-character Dolt hashes, no recorded-version fields, and the same hashes in the text output), and `bd show --as-of ` with a hash from it is the Dolt AS OF read in show's JSON shape, not the R7.1 as-of read over issue_versions; `--as-of main` reads the branch head. The three TestEmbedded* functions are placed in the 100-shard embedded cmd manifest by gen_embedded_cmd_shard_manifest.py --write (incremental). Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: Jim Wordelman Co-authored-by: Donna Box --- .github/scripts/embedded-cmd-test-shards.txt | 5 + cmd/bd/BUILD.bazel | 2 + cmd/bd/format_json_alias_embedded_test.go | 102 +++++++++++ cmd/bd/history_embedded_test.go | 127 +++++++++++++ .../if_revision_ordinary_cas_embedded_test.go | 168 ++++++++++++++++++ cmd/bd/version_embedded_test.go | 95 ++++++++++ ...ioned_history_switch_scan_embedded_test.go | 50 ++++++ 7 files changed, 549 insertions(+) create mode 100644 cmd/bd/format_json_alias_embedded_test.go create mode 100644 cmd/bd/if_revision_ordinary_cas_embedded_test.go diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index 983c57438..e05f241a2 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -123,13 +123,18 @@ 100 49 TestEmbeddedInitAPushConsentAndRemoteBootstrap 100 50 TestEmbeddedDiffConcurrent +100 50 TestEmbeddedVersionOutputShape +100 51 TestEmbeddedHistoryAndShowAsOfReadDoltCommits 100 51 TestEmbeddedInitGitBootstrapRoutingFreshQuiet +100 52 TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan 100 52 TestEmbeddedSwarmConcurrent +100 53 TestEmbeddedIfRevisionOrdinaryCAS 100 53 TestEmbeddedInitSelectedExcludeRoutingStealthDecoyQuiet +100 54 TestEmbeddedFormatJSONAliasMatchesJSON 100 54 TestEmbeddedSearchConcurrent 100 55 TestEmbeddedUndefer diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 8477c2d1a..f16e65cbb 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -804,6 +804,7 @@ go_test( "find_duplicates_test.go", "flags_test.go", "flatten_embedded_test.go", + "format_json_alias_embedded_test.go", "formula_fixture_proxied_test.go", "formula_help_test.go", "formula_primitives_test.go", @@ -865,6 +866,7 @@ go_test( "identity_preview_refusal_test.go", "if_revision_embedded_test.go", "if_revision_gc_matcher_embedded_test.go", + "if_revision_ordinary_cas_embedded_test.go", "if_revision_proxied_close_delete_test.go", "if_revision_proxied_integration_test.go", "if_revision_reassign_fence_embedded_test.go", diff --git a/cmd/bd/format_json_alias_embedded_test.go b/cmd/bd/format_json_alias_embedded_test.go new file mode 100644 index 000000000..3e163c870 --- /dev/null +++ b/cmd/bd/format_json_alias_embedded_test.go @@ -0,0 +1,102 @@ +//go:build cgo + +package main + +import ( + "bytes" + "encoding/json" + "errors" + "os" + "os/exec" + "slices" + "strings" + "testing" +) + +// bdRunStreams runs one bd process in dir with the hermetic test environment +// and returns stdout, stderr and the exit status separately. A nonzero exit is +// returned, not fatal, so a caller can pin the status itself; only a process +// that could not be started fails the test here. +func bdRunStreams(t *testing.T, bd, dir string, args ...string) (stdout, stderr string, exit int) { + t.Helper() + cmd := exec.Command(bd, args...) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + var outBuf, errBuf bytes.Buffer + cmd.Stdout, cmd.Stderr = &outBuf, &errBuf + if err := cmd.Run(); err != nil { + var ee *exec.ExitError + if !errors.As(err, &ee) { + t.Fatalf("bd %s did not run: %v", strings.Join(args, " "), err) + } + return outBuf.String(), errBuf.String(), ee.ExitCode() + } + return outBuf.String(), errBuf.String(), 0 +} + +// TestEmbeddedFormatJSONAliasMatchesJSON pins the hidden root --format alias +// (GH#2612): on show, list, ready and memories, `--format json` prints exactly +// what `--json` prints, byte for byte, and exits 0 like it. +// +// The alias is a root persistent flag, so any subcommand that registers a +// --format of its own shadows it (the GH#6278 hazard). `bd list` already has +// its own --format and passes `json` through by hand (list_input.go). A +// local --format added to show, ready or memories for another output +// format would turn `bd show ID --format json` into a refusal or into a +// different document. Both are regressions this test catches: it compares +// the whole of stdout, not a parse of it. +// +// Each command is checked in three spellings: `--format json` and +// `--format=json` after the subcommand, and `--format json` before it, where +// the flag is plainly the root's. +func TestEmbeddedFormatJSONAliasMatchesJSON(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", "fj") + + id := bdCreateSilent(t, bd, dir, "Format alias parity", "--type", "task", "--description", "read through --format json") + bdRunOK(t, bd, dir, "remember", "the format alias is --json", "--key", "fj-alias") + + for _, tc := range []struct { + name string + args []string + // mention is a value the --json document must contain, so two empty + // documents cannot match each other. + mention string + }{ + {"show", []string{"show", id}, id}, + {"list", []string{"list"}, id}, + {"ready", []string{"ready"}, id}, + {"memories", []string{"memories"}, "fj-alias"}, + } { + t.Run(tc.name, func(t *testing.T) { + wantArgs := slices.Concat(tc.args, []string{"--json"}) + want, wantErr, exit := bdRunStreams(t, bd, dir, wantArgs...) + if exit != 0 { + t.Fatalf("bd %s exited %d\nstdout:\n%s\nstderr:\n%s", strings.Join(wantArgs, " "), exit, want, wantErr) + } + if !json.Valid([]byte(want)) || !strings.Contains(want, tc.mention) { + t.Fatalf("bd %s did not print one JSON document naming %s:\n%s", strings.Join(wantArgs, " "), tc.mention, want) + } + + for _, args := range [][]string{ + slices.Concat(tc.args, []string{"--format", "json"}), + slices.Concat(tc.args, []string{"--format=json"}), + slices.Concat([]string{"--format", "json"}, tc.args), + } { + got, gotErr, exit := bdRunStreams(t, bd, dir, args...) + if exit != 0 { + t.Errorf("bd %s exited %d, want 0 like bd %s\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, strings.Join(wantArgs, " "), got, gotErr) + continue + } + if got != want { + t.Errorf("bd %s printed a different document from bd %s\n--format:\n%s\n--json:\n%s", strings.Join(args, " "), strings.Join(wantArgs, " "), got, want) + } + } + }) + } +} diff --git a/cmd/bd/history_embedded_test.go b/cmd/bd/history_embedded_test.go index 5c7910c20..ab351a1dd 100644 --- a/cmd/bd/history_embedded_test.go +++ b/cmd/bd/history_embedded_test.go @@ -7,6 +7,8 @@ import ( "fmt" "os" "os/exec" + "regexp" + "sort" "strings" "sync" "testing" @@ -403,3 +405,128 @@ func TestEmbeddedHistoryConcurrent(t *testing.T) { } } } + +// doltCommitHashPattern is a full Dolt commit hash: 32 characters of Dolt's +// base32 alphabet. It is what `bd show --as-of` takes, and a prefix is not. +var doltCommitHashPattern = regexp.MustCompile(`^[0-9a-v]{32}$`) + +// issueVersionOnlyKeys are fields of a recorded version (`bd versions --json`, +// storage.IssueVersion) that neither the Dolt-commit history nor the Dolt AS OF +// read has. +var issueVersionOnlyKeys = []string{"local_revision", "epoch", "change_actor", "change_at", "attribution_status", "removed_restriction", "state_bytes"} + +// TestEmbeddedHistoryAndShowAsOfReadDoltCommits pins what `bd history ` and +// `bd show --as-of ` read in an ordinary workspace whose store records +// versioned history, so both planes hold the same issue: +// - `bd history --json` is the Dolt-commit history: an array, newest first, +// of {CommitHash, Committer, CommitDate, Issue} entries, each CommitHash a full +// Dolt commit hash and each Issue the row as that commit left it. No field of a +// recorded version appears, and the text output names the same full hashes. +// - `bd show --as-of `, with a hash from `bd history`, is the Dolt AS OF +// read: the issue as that commit left it, in show's JSON shape (an array of +// issues), not a recorded version. A branch name is a ref too: --as-of main +// reads the branch head. +// +// Recorded versions are a separate plane with its own command (`bd versions`) and +// its own as-of read (R7.1, over issue_versions), which takes an instant or a +// version address and not a Dolt ref. Recording them must change neither answer. +func TestEmbeddedHistoryAndShowAsOfReadDoltCommits(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", "hd") + bdConfig(t, bd, dir, "set", "versioned-history.enabled", "true") + + id := bdCreateSilent(t, bd, dir, "Before title", "--type", "task") + bdUpdate(t, bd, dir, id, "--title", "After title") + + // Both planes hold this issue: versions were recorded for it. + var recorded struct { + Recording bool `json:"recording"` + Versions []json.RawMessage `json:"versions"` + } + if out, stderr, exit := bdRunStreams(t, bd, dir, "versions", id, "--json"); exit != 0 || json.Unmarshal([]byte(out), &recorded) != nil || !recorded.Recording || len(recorded.Versions) == 0 { + t.Fatalf("bd versions %s --json (exit %d) did not report recorded versions, so this test would not tell the planes apart\nstdout:\n%s\nstderr:\n%s", id, exit, out, stderr) + } + + historyJSON := bdHistory(t, bd, dir, id, "--json") + var entries []map[string]json.RawMessage + if err := json.Unmarshal([]byte(historyJSON), &entries); err != nil { + t.Fatalf("bd history %s --json is not a JSON array: %v\n%s", id, err, historyJSON) + } + if len(entries) < 2 { + t.Fatalf("bd history %s --json has %d entries, want one for each of the create and the update:\n%s", id, len(entries), historyJSON) + } + type snapshot struct { + ID string `json:"id"` + Title string `json:"title"` + } + hashes := make([]string, len(entries)) + titles := make([]string, len(entries)) + for i, entry := range entries { + keys := make([]string, 0, len(entry)) + for key := range entry { + keys = append(keys, key) + } + sort.Strings(keys) + if got := strings.Join(keys, ","); got != "CommitDate,CommitHash,Committer,Issue" { + t.Errorf("bd history entry %d has keys %s, want the Dolt-commit entry CommitDate,CommitHash,Committer,Issue", i, got) + } + if err := json.Unmarshal(entry["CommitHash"], &hashes[i]); err != nil || !doltCommitHashPattern.MatchString(hashes[i]) { + t.Errorf("bd history entry %d CommitHash %s is not a full Dolt commit hash", i, entry["CommitHash"]) + } + var issue snapshot + if err := json.Unmarshal(entry["Issue"], &issue); err != nil || issue.ID != id { + t.Errorf("bd history entry %d Issue %s is not a snapshot of %s", i, entry["Issue"], id) + } + titles[i] = issue.Title + } + if titles[0] != "After title" || titles[len(titles)-1] != "Before title" { + t.Fatalf("bd history %s titles newest first are %q, want %q first and %q last", id, titles, "After title", "Before title") + } + for _, key := range issueVersionOnlyKeys { + if strings.Contains(historyJSON, `"`+key+`"`) { + t.Errorf("bd history %s --json carries %q, a field of a recorded version:\n%s", id, key, historyJSON) + } + } + text := bdHistory(t, bd, dir, id) + for _, hash := range hashes { + if !strings.Contains(text, hash) { + t.Errorf("bd history %s text output does not name the full commit hash %s:\n%s", id, hash, text) + } + } + + // show --as-of reads the Dolt commit the history named. + first := hashes[len(hashes)-1] + asOfJSON := func(ref string) snapshot { + t.Helper() + out, stderr, exit := bdRunStreams(t, bd, dir, "show", id, "--as-of", ref, "--json") + var shown []map[string]json.RawMessage + if exit != 0 || json.Unmarshal([]byte(out), &shown) != nil || len(shown) != 1 { + t.Fatalf("bd show %s --as-of %s --json exited %d, want an array of one issue\nstdout:\n%s\nstderr:\n%s", id, ref, exit, out, stderr) + } + for _, key := range issueVersionOnlyKeys { + if _, ok := shown[0][key]; ok { + t.Errorf("bd show %s --as-of %s --json carries %q, a field of a recorded version:\n%s", id, ref, key, out) + } + } + var issues []snapshot + if err := json.Unmarshal([]byte(out), &issues); err != nil { + t.Fatalf("bd show %s --as-of %s --json: %v\n%s", id, ref, err, out) + } + return issues[0] + } + if got := asOfJSON(first); got.ID != id || got.Title != "Before title" { + t.Errorf("bd show %s --as-of %s (its first commit) read %+v, want the issue titled %q", id, first, got, "Before title") + } + if got := asOfJSON("main"); got.ID != id || got.Title != "After title" { + t.Errorf("bd show %s --as-of main read %+v, want the branch head's title %q", id, got, "After title") + } + human := bdShowRaw(t, bd, dir, id, "--as-of", first) + if !strings.Contains(human, "as of "+first) || !strings.Contains(human, "Before title") || strings.Contains(human, "After title") { + t.Errorf("bd show %s --as-of %s text output does not show the first commit's issue under that ref:\n%s", id, first, human) + } +} diff --git a/cmd/bd/if_revision_ordinary_cas_embedded_test.go b/cmd/bd/if_revision_ordinary_cas_embedded_test.go new file mode 100644 index 000000000..c51b058fa --- /dev/null +++ b/cmd/bd/if_revision_ordinary_cas_embedded_test.go @@ -0,0 +1,168 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "os" + "slices" + "strconv" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// ifRevisionStaleExit is a literal on purpose: the contract with gascity's +// bdstore_conditional.go classifier is the number 13, not whatever name the +// constant for it (ExitGuardMismatch) happens to have. +const ifRevisionStaleExit = 13 + +// decodeIfRevisionBodyExact decodes the flat machine body a refused +// --if-revision write puts on the last line of stderr, keeping numbers as +// json.Number. Revisions are int64 values well past 2^53, so comparing them +// as float64 would accept a neighbouring revision; a json.Number also proves +// the field is a JSON number and not a string. +func decodeIfRevisionBodyExact(t *testing.T, line string) map[string]any { + t.Helper() + dec := json.NewDecoder(strings.NewReader(line)) + dec.UseNumber() + var body map[string]any + if err := dec.Decode(&body); err != nil { + t.Fatalf("decode the --if-revision refusal body: %v\nline: %s", err, line) + } + return body +} + +// TestEmbeddedIfRevisionOrdinaryCAS pins the ordinary --if-revision +// compare-and-swap (#7203) end to end, as a gascity-style caller sees it: +// +// - a stale decimal token on update, close, assign and delete (preview and +// --force) exits 13 with a precondition_failed body on the last line of +// stderr naming the id and both revisions as JSON integers, prints +// nothing on stdout and writes nothing; +// - a token that is not a decimal exits 1 with the "invalid --if-revision" +// refusal, never 13, and writes nothing; +// - the current token applies on update, close, assign and delete, and +// each write that leaves the issue in place moves its revision on. +// +// A second meaning for the same flag (an opaque token in some other kind of +// workspace) must leave all of this unchanged in an ordinary one. This is +// the ordinary-workspace half of the fork's +// TestGraphPreviewIfRevisionOutsideLinkModeIsUpstreamCAS, ported onto this +// package's embedded helpers and extended from update/delete to close and +// assign. +func TestEmbeddedIfRevisionOrdinaryCAS(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", "ifrev") + + id := bdCreateSilent(t, bd, dir, "Stale guard", "--type", "task", "--priority", "2") + stale := bdShowRevision(t, bd, dir, id) + bdRunOK(t, bd, dir, "update", id, "--notes", "bump", "--json") + current := bdShowRevision(t, bd, dir, id) + if current == stale { + t.Fatal("an unguarded update did not advance the revision") + } + staleToken := strconv.FormatInt(stale, 10) + + for _, tc := range []struct { + name string + args []string + }{ + {"update", []string{"update", id, "--priority", "3"}}, + {"close", []string{"close", id}}, + {"assign", []string{"assign", id, "worker"}}, + {"delete preview", []string{"delete", id}}, + {"delete force", []string{"delete", id, "--force"}}, + } { + args := slices.Concat(tc.args, []string{"--if-revision", staleToken, "--json"}) + stdout, stderr, exit := bdRunStreams(t, bd, dir, args...) + if exit != ifRevisionStaleExit { + t.Fatalf("stale --if-revision %s exited %d, want %d\nstdout:\n%s\nstderr:\n%s", tc.name, exit, ifRevisionStaleExit, stdout, stderr) + } + if stdout != "" { + t.Errorf("stale --if-revision %s printed on stdout, want nothing:\n%s", tc.name, stdout) + } + body := decodeIfRevisionBodyExact(t, lastJSONLine(t, stderr)) + if body["code"] != ifRevisionCodePreconditionFailed || body["id"] != id { + t.Errorf("stale --if-revision %s reported %v, want code %q for %s", tc.name, body, ifRevisionCodePreconditionFailed, id) + } + if got := body["expected_revision"]; got != json.Number(staleToken) { + t.Errorf("stale --if-revision %s reported expected_revision %#v, want the JSON integer %s", tc.name, got, staleToken) + } + if got := body["current_revision"]; got != json.Number(strconv.FormatInt(current, 10)) { + t.Errorf("stale --if-revision %s reported current_revision %#v, want the JSON integer %d", tc.name, got, current) + } + if msg, _ := body["error"].(string); !strings.Contains(msg, "precondition failed") { + t.Errorf("stale --if-revision %s error text %q lacks \"precondition failed\"", tc.name, msg) + } + if got := bdShowRevision(t, bd, dir, id); got != current { + t.Fatalf("stale --if-revision %s wrote: revision %d -> %d", tc.name, current, got) + } + } + + // A token that is not a decimal is a typo refused before any write, with + // exit 1 and not the guard's 13, in both output modes. + for _, base := range [][]string{ + {"update", id, "--priority", "3"}, + {"close", id}, + {"assign", id, "worker"}, + {"delete", id}, + {"delete", id, "--force"}, + } { + for _, mode := range [][]string{nil, {"--json"}} { + args := slices.Concat(base, []string{"--if-revision", "observed"}, mode) + stdout, stderr, exit := bdRunStreams(t, bd, dir, args...) + out := stdout + stderr + // The text refusal quotes the token; the --json one carries the + // same text JSON-escaped. + refused := strings.Contains(out, `invalid --if-revision "observed"`) || + strings.Contains(out, `invalid --if-revision \"observed\"`) + if exit != 1 || !refused { + t.Errorf("bd %s exited %d, want exit 1 refusing the non-decimal token\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, stdout, stderr) + } + if strings.Contains(out, ifRevisionCodePreconditionFailed) { + t.Errorf("bd %s reported a stale revision for a token that is not one:\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), stdout, stderr) + } + } + } + if got := bdShowRevision(t, bd, dir, id); got != current { + t.Fatalf("a refused non-decimal token wrote: revision %d -> %d", current, got) + } + + // The current token applies, on each verb in turn. + revision := current + guarded := func(target string, args ...string) { + t.Helper() + bdRunOK(t, bd, dir, slices.Concat(args, []string{"--if-revision", strconv.FormatInt(revision, 10), "--json"})...) + next := bdShowRevision(t, bd, dir, target) + if next == revision { + t.Fatalf("a matching --if-revision on bd %s did not advance the revision", strings.Join(args, " ")) + } + revision = next + } + guarded(id, "update", id, "--priority", "3") + if got := bdShow(t, bd, dir, id); got.Priority != 3 { + t.Errorf("matching --if-revision update did not apply: priority = %d, want 3", got.Priority) + } + guarded(id, "close", id) + if got := bdShow(t, bd, dir, id); got.Status != types.StatusClosed { + t.Errorf("matching --if-revision close did not apply: status = %s, want closed", got.Status) + } + bdRunOK(t, bd, dir, "delete", id, "--force", "--if-revision", strconv.FormatInt(revision, 10), "--json") + bdShowFail(t, bd, dir, id) + + // assign gets an issue of its own: closing an issue assigned to someone + // other than the actor is refused without --force, whatever the guard. + other := bdCreateSilent(t, bd, dir, "Guarded assign", "--type", "task") + revision = bdShowRevision(t, bd, dir, other) + guarded(other, "assign", other, "worker") + if got := bdShow(t, bd, dir, other); got.Assignee != "worker" { + t.Errorf("matching --if-revision assign did not apply: assignee = %q, want worker", got.Assignee) + } +} diff --git a/cmd/bd/version_embedded_test.go b/cmd/bd/version_embedded_test.go index a2ecfea8d..436f7a5be 100644 --- a/cmd/bd/version_embedded_test.go +++ b/cmd/bd/version_embedded_test.go @@ -3,9 +3,11 @@ package main import ( + "encoding/json" "fmt" "os" "os/exec" + "regexp" "strings" "sync" "testing" @@ -72,3 +74,96 @@ func TestEmbeddedVersionConcurrent(t *testing.T) { } } } + +// versionLinePattern is the whole of `bd version`'s stdout: +// "bd version ()", with ": " or +// ": @" inside the parentheses when the binary knows them. +var versionLinePattern = regexp.MustCompile(`^bd version (\S+) \(([^):]+)(?:: (?:\S+@)?\S+)?\)\n$`) + +// TestEmbeddedVersionOutputShape pins `bd version` the way scripts and +// plugins call it, in an ordinary workspace and in a directory that is not +// one: +// - with no arguments it exits 0 and prints exactly one line on stdout, +// "bd version (...)"; +// - --json prints one object with version, build and schema_version, plus +// commit and branch when known, and no other key; its version and build +// agree with the text line, and --format json prints the same document; +// - an argument is refused with exit 1 and points at `bd versions ` +// (#6661): on stderr in text mode, as the JSON error on stdout with +// --json, and without the version line either way. +// +// TestVersionWithAnArgumentPointsAtVersions pins the refusal on RunE; this +// pins it through the real binary, where the root pre-run and workspace +// discovery run first. +func TestEmbeddedVersionOutputShape(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) + workspace, _, _ := bdInit(t, bd, "--prefix", "vo") + + for name, dir := range map[string]string{"workspace": workspace, "no workspace": t.TempDir()} { + t.Run(name, func(t *testing.T) { + text, stderr, exit := bdRunStreams(t, bd, dir, "version") + if exit != 0 { + t.Fatalf("bd version exited %d\nstdout:\n%s\nstderr:\n%s", exit, text, stderr) + } + line := versionLinePattern.FindStringSubmatch(text) + if line == nil { + t.Fatalf("bd version stdout is not one %q line:\n%q", versionLinePattern, text) + } + + doc, stderr, exit := bdRunStreams(t, bd, dir, "version", "--json") + if exit != 0 { + t.Fatalf("bd version --json exited %d\nstdout:\n%s\nstderr:\n%s", exit, doc, stderr) + } + var fields map[string]any + if err := json.Unmarshal([]byte(doc), &fields); err != nil { + t.Fatalf("bd version --json is not one JSON object: %v\n%s", err, doc) + } + for key := range fields { + switch key { + case "version", "build", "schema_version", "commit", "branch": + default: + t.Errorf("bd version --json has an unexpected key %q:\n%s", key, doc) + } + } + if _, ok := fields["schema_version"].(float64); !ok { + t.Errorf("bd version --json has no numeric schema_version:\n%s", doc) + } + if fields["version"] != line[1] || fields["build"] != line[2] { + t.Errorf("bd version --json says version %v build %v, the text line says %s and %s:\n%s", fields["version"], fields["build"], line[1], line[2], doc) + } + for _, key := range []string{"commit", "branch"} { + if v, ok := fields[key]; ok { + if s, isString := v.(string); !isString || s == "" { + t.Errorf("bd version --json %s = %#v, want a non-empty string when present", key, v) + } + } + } + if alias, _, exit := bdRunStreams(t, bd, dir, "version", "--format", "json"); exit != 0 || alias != doc { + t.Errorf("bd version --format json exited %d and printed a different document from --json:\n%s\nwant:\n%s", exit, alias, doc) + } + + stdout, stderr, exit := bdRunStreams(t, bd, dir, "version", "vo-123") + if exit != 1 || stdout != "" { + t.Errorf("bd version vo-123 exited %d with stdout %q, want exit 1 and nothing on stdout", exit, stdout) + } + for _, want := range []string{"Did you mean", "bd versions vo-123"} { + if !strings.Contains(stderr, want) { + t.Errorf("bd version vo-123 stderr lacks %q:\n%s", want, stderr) + } + } + + stdout, stderr, exit = bdRunStreams(t, bd, dir, "version", "vo-123", "--json") + var refusal struct { + Error string `json:"error"` + } + if exit != 1 || json.Unmarshal([]byte(stdout), &refusal) != nil || !strings.Contains(refusal.Error, "bd versions vo-123") { + t.Errorf("bd version vo-123 --json exited %d, want exit 1 and a JSON error naming `bd versions vo-123`\nstdout:\n%s\nstderr:\n%s", exit, stdout, stderr) + } + }) + } +} diff --git a/cmd/bd/versioned_history_switch_scan_embedded_test.go b/cmd/bd/versioned_history_switch_scan_embedded_test.go index 6c4c1a286..acf34632f 100644 --- a/cmd/bd/versioned_history_switch_scan_embedded_test.go +++ b/cmd/bd/versioned_history_switch_scan_embedded_test.go @@ -434,3 +434,53 @@ func TestEmbeddedVersionedHistorySwitchRefusesAnUnrecordableGateTimeout(t *testi t.Fatalf("after applying the remedies the switch did not turn on: config get says %q", got) } } + +// TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan pins that the pre-enable scan belongs +// to versioned-history.enabled alone. In a store that holds a row the scan refuses over, `bd config +// set` and `bd config set-many` of any other key -- given the value "true", which is what turns +// the switch on -- exit 0, store the value, print no refusal and leave the switch off. The switch +// itself is still refused afterwards, which proves the store held a row the scan would have named. +// +// TestEmbeddedVersionedHistorySwitchRefusesUnversionableMetadata pins that turning the switch OFF +// never scans; this pins the other half of "any other key ... passes without reading a row" +// (checkVersionedHistoryCanBeEnabled's doc comment) through the real commands. +func TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan(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") + } + // The offender below can only be written while nothing records versions. No t.Parallel: + // t.Setenv is incompatible. + t.Setenv(vhEnvVar, "") + + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "vso") + + offender := bdCreateSilent(t, bd, dir, "holds an integer past 2^53", "--metadata", `{"n":9007199254740993}`) + + for _, args := range [][]string{ + {"config", "set", "custom.vso-marker", "true"}, + {"config", "set-many", "custom.vso-batch=true"}, + } { + stdout, stderr, exit := bdRunStreams(t, bd, dir, args...) + if exit != 0 { + t.Fatalf("bd %s exited %d in a store holding %s; the scan must not run for this key\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, offender, stdout, stderr) + } + if out := stdout + stderr; strings.Contains(out, "cannot turn versioned history on") || strings.Contains(out, offender) { + t.Errorf("bd %s printed the versioned-history refusal for a key that is not the switch:\n%s", strings.Join(args, " "), out) + } + } + for key, want := range map[string]string{"custom.vso-marker": "true", "custom.vso-batch": "true"} { + if got := strings.TrimSpace(bdConfig(t, bd, dir, "get", key)); got != want { + t.Errorf("config get %s = %q, want %q", key, got, want) + } + } + if got := strings.TrimSpace(bdConfig(t, bd, dir, "get", "versioned-history.enabled")); strings.HasPrefix(got, "true") { + t.Fatalf("setting other keys turned versioned history on: config get says %q", got) + } + + // The control: the scan does see the offender when the switch itself is set. + out, _ := bdRunFailCode(t, bd, dir, "config", "set", "versioned-history.enabled", "true") + if !strings.Contains(out, offender) { + t.Fatalf("the refused switch does not name %s, so the pin above proves nothing:\n%s", offender, out) + } +}