beads/cmd/bd/delete_exact_id_test.go
Alex fefcdf6533
fix(delete): resolve ids exactly, never by prefix abbreviation (#7375)
* test(delete): pin that a stale id never deletes the issue it prefixes (be-ksd)

bd delete resolves each id through the abbreviation-tolerant resolver
(resolveAndGetIssueForMutation -> utils.ResolvePartialID). When the exact
id is absent, that resolver falls through to leading-prefix abbreviation,
so an id that was already deleted resolves to a different issue whose id
it happens to begin, and --force deletes that issue.

The shape is ordinary: hash length is adaptive (3 to 8 characters) so a
grown store holds short ids beside longer ones, --id makes any shape, and
a hierarchical child's id always extends its parent's. On a fixture, after
fx-t00003 was deleted, bd delete fx-t00003 resolved to fx-t000031; a
re-run of a finished --from-file list with --force --quiet deleted two
issues it never named, silently.

The test drives deleteCmd in-process against a stub DoltStorage (no cgo,
no Dolt server) and records every request handed to the Deleter role. It
covers the single-id --force path, the preview, a deleted parent's id with
an orphaned child, the --from-file batch path, and an abbreviation of one
and of two live issues; each refusal must say delete needs the full id
and name the ids the input matches. An over-refusal guard checks that
exact ids (full, bare hash, child, batch) still delete exactly what they
name. The six refusal cases fail at this commit; the guard passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman

* fix(delete): resolve ids exactly, never by prefix abbreviation (be-ksd)

bd delete's direct route resolved each id with the abbreviation-tolerant
resolver, so an id that no longer exists resolved to the surviving issue
whose id it begins, and --force deleted that issue. Both of its resolution
sites now use resolveAndGetIssueForMutationExact (#5393's exact sibling,
until now used only by bd comment): the inline single-id path and
deleteBatch, which --from-file, multiple ids and --cascade take.

The resolver cannot tell a stale full id from an abbreviation. Hash length
is adaptive with store size, so one store holds 3- to 8-character ids side
by side and "fx-t00003" is both a valid full id and a valid abbreviation
of "fx-t000031". The rule therefore has to be per command, the way #5393
made it for bd comment. Delete is exact on both preview and --force: the
preview prints the next command to run ("To proceed, run: bd delete
fx-t000031 --force"), so a tolerant preview hands the caller the wrong
deletion to confirm.

This matches the team-server route, which passes ids to issueops.Deleter
unresolved, and DeleteRequest.IDs' own contract ("IDs ARE EXACT"). The
partial-ID notice (#6302) did not protect this path: --quiet silences it,
and a --force --quiet re-run of a finished --from-file list deleted two
issues it never named.

The refusal says what to do: "bd delete needs the full issue id: no issue
has the id "t000", which is the start of fx-t000031". To name the matches,
ResolvePartialIDExact now returns *utils.AbbreviatedIDError, which carries
the input and the sorted matches, wraps ErrAbbreviatedIDNotAllowed and
keeps the old error text, so bd comment's errors.Is checks and messages
are unchanged.

Cost: bd delete <abbreviation> is refused, naming the full ids, so the
caller retypes one. Exact ids, bare full hashes, child, cross-prefix and
routed ids resolve as before. The other deleteBatch callers (cleanup, wisp
gc, mol burn) pass full ids read from the store, so nothing changes for
them except under a race, where they now refuse instead of reaching a
neighbor. Reads and other writes keep abbreviation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman

* docs(ids): say bd delete requires the full id, like bd comment (be-ksd)

The Working with IDs section named bd comment as the one command that
refuses abbreviations and said every other mutation keeps them. bd delete
now requires the exact id too, so the section covers both, says why a
delete reaches the wrong issue so easily (an already-deleted id is still
the start of its child's id, or of a longer hash), and adds the bd delete
lines to the example block. Best Practices #1 names both commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman

* docs(changelog): link the bd delete exact-id entry to #7375 (be-ksd)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman

* fix(delete): report a gone parent's id as a lost race under --if-revision (be-ksd)

Review-loop iteration 1 for #7375: a maintainer fixup on top of the
contributor's branch.

Major (codex+claude): a guarded `bd delete --if-revision` whose target
was deleted, and whose id is still the start of a surviving id (a gone
parent with a live <parent>.1 child), exited 1 with the abbreviation
refusal. Any other gone target gets the documented lost race
(precondition_failed, exit 13), and gascity's conditional deletes
switch on that code, so a benign race read as a hard failure.

- reportIfRevisionTargetGone (the single-id path) also takes
  utils.ErrAbbreviatedIDNotAllowed as a gone target: under delete's
  exact resolution that id names no row either.
- The refusal is a typed error, deleteAbbreviationError, that unwraps
  to storage.ErrNotFound beside the *utils.AbbreviatedIDError, so the
  --cascade caller of deleteBatch classifies it through
  reportIfRevisionFailure the same way. errors.New(msg) dropped every
  sentinel.

Minor (claude), taken: the refusal leads with the not-found fact,
`issue "t000" not found: bd delete needs the full issue id, and "t000"
is only the start of fx-t000031`, so gascity's isBdNotFound reads an
already-gone full id that begins a survivor's id as the idempotent
not-found it reads for any other gone id. The CHANGELOG entry quotes
the new text and the --if-revision outcome.

Minor (gemini), declined: threading the source command into the
refusal's wording. deleteBatch's other callers (bd cleanup, wisp gc,
mol burn) pass store-minted full ids that no user retypes, and the text
now leads with "issue X not found", which holds for every caller.

Tests:
- TestDeleteIfRevisionGoneIDThatPrefixesAnotherIssue: single id,
  --json, --cascade and --cascade --json each exit 13 with "precondition
  failed: issue no longer exists" and the precondition_failed body,
  never the refusal text, and the guarded write never runs. Two
  no-survivor rows are the plain gone id they must match.
- TestReportIfRevisionTargetGone: abbreviation rows, guarded and not.
- TestDeleteRefusesStaleIDThatPrefixesAnotherIssue also asserts the
  refusal says "not found".
- TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed,
  end to end on embedded Dolt: delete a parent, its child survives and
  `bd show <parent>` resolves to it; a guarded delete of the parent
  exits 13 on the single-id and --cascade paths and leaves the child.
  The TestEmbedded name is what puts it in a CI lane; its line in
  embedded-cmd-test-shards.txt is the generator's incremental --write.

Mutation checks, each reverted afterwards: dropping the
ErrAbbreviatedIDNotAllowed match fails the single-id cases and the
abbreviation_guarded row; dropping ErrNotFound from Unwrap fails the
--cascade cases; dropping "not found" from the text fails every
refusal case; reverting both fixes fails both embedded legs (exit 1,
the refusal text, no "precondition failed").

Validation: the focused delete and if-revision tests; the embedded pair
under BEADS_TEST_EMBEDDED_DOLT=1; the scripts shard-manifest policy
tests and the generator's --check; gofmt; git diff --check. The full
./cmd/bd and ./internal/utils packages (-short, BEADS_TEST_SKIP=dolt)
pass but for TestRunApplyAllOK, which fails only because this worktree
sets core.hooksPath=/dev/null ("mkdir /dev/null: not a directory") and
passes with core.hooksPath overridden.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-16 11:25:54 +00:00

373 lines
14 KiB
Go

package main
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// deleteExactStubStore is the store `bd delete` resolves and deletes through,
// reduced to the calls its direct route makes: the resolver's exact-id probe
// (SearchIssues with IDs) and its substring search (SearchIssueIDs), the
// prefix config, GetIssue, the preview's dependency reads, and Deleter. The
// embedded nil DoltStorage makes any other call panic, so a test that wanders
// off this path fails loudly instead of passing on a default. No cgo, no
// Dolt server: the same shape as bulkDepStubStore in dep_add_target_test.go.
type deleteExactStubStore struct {
storage.DoltStorage
ids []string
deleter *deleteRecordingDeleter
}
func (s *deleteExactStubStore) SearchIssues(_ context.Context, _ string, filter types.IssueFilter) ([]*types.Issue, error) {
var out []*types.Issue
for _, id := range s.ids {
if len(filter.IDs) > 0 && !slices.Contains(filter.IDs, id) {
continue
}
out = append(out, &types.Issue{ID: id, Title: "issue " + id})
}
return out, nil
}
// SearchIssueIDs models the id half of the real `id LIKE '%q%'` search. None
// of these issues is ephemeral, so the resolver's wisp-only fallback finds
// nothing, as the real wisps-then-issues search would.
func (s *deleteExactStubStore) SearchIssueIDs(_ context.Context, query string, filter types.IssueFilter) ([]string, error) {
if filter.Ephemeral != nil && *filter.Ephemeral {
return nil, nil
}
var out []string
for _, id := range s.ids {
if strings.Contains(id, query) {
out = append(out, id)
}
}
return out, nil
}
func (s *deleteExactStubStore) GetConfig(_ context.Context, key string) (string, error) {
if key == "issue_prefix" {
return "fx", nil
}
return "", nil
}
func (s *deleteExactStubStore) GetAllConfig(_ context.Context) (map[string]string, error) {
return map[string]string{"issue_prefix": "fx"}, nil
}
func (s *deleteExactStubStore) GetIssue(_ context.Context, id string) (*types.Issue, error) {
if slices.Contains(s.ids, id) {
return &types.Issue{ID: id, Title: "issue " + id}, nil
}
return nil, storage.ErrNotFound
}
func (s *deleteExactStubStore) GetDependencies(context.Context, string) ([]*types.Issue, error) {
return nil, nil
}
func (s *deleteExactStubStore) GetDependents(context.Context, string) ([]*types.Issue, error) {
return nil, nil
}
func (s *deleteExactStubStore) GetDependencyRecords(context.Context, string) ([]*types.Dependency, error) {
return nil, nil
}
func (s *deleteExactStubStore) Deleter() (issueops.Deleter, error) {
return s.deleter, nil
}
// deleteRecordingDeleter records every request the front door hands the role,
// previews (DryRun) included: a preview that names an issue the caller never
// named prints the `bd delete <that id> --force` line the caller is told to run.
type deleteRecordingDeleter struct {
requests []issueops.DeleteRequest
}
func (d *deleteRecordingDeleter) Delete(_ context.Context, req issueops.DeleteRequest) (issueops.DeleteResult, error) {
d.requests = append(d.requests, req)
return issueops.DeleteResult{DryRun: req.DryRun, Deleted: len(req.IDs)}, nil
}
// useDeleteExactStub installs a stub holding ids as the store `bd delete`
// reads, and restores every global the command touches.
func useDeleteExactStub(t *testing.T, ids ...string) *deleteExactStubStore {
t.Helper()
ensureCleanGlobalState(t)
saveAndRestoreGlobals(t)
// The migration-freeze probe in CheckReadonly walks from BEADS_DIR; keep it
// in an empty directory rather than whatever workspace the test runs in.
t.Setenv("BEADS_DIR", t.TempDir())
oldCtx, oldJSON, oldQuiet, oldProxied, oldActor := rootCtx, jsonOutput, quietFlag, proxiedServerMode, actor
oldDidWrite := commandDidWrite.Load()
t.Cleanup(func() {
rootCtx, jsonOutput, quietFlag, proxiedServerMode, actor = oldCtx, oldJSON, oldQuiet, oldProxied, oldActor
commandDidWrite.Store(oldDidWrite)
commandDeletedIssueIDs.reset()
})
s := &deleteExactStubStore{ids: ids, deleter: &deleteRecordingDeleter{}}
store, rootCtx, jsonOutput, quietFlag, proxiedServerMode, actor = s, context.Background(), false, false, false, "test"
return s
}
// setDeleteFlag sets one of deleteCmd's flags for the length of the test.
func setDeleteFlag(t *testing.T, name, value string) {
t.Helper()
if err := deleteCmd.Flags().Set(name, value); err != nil {
t.Fatalf("setting --%s: %v", name, err)
}
t.Cleanup(func() {
flag := deleteCmd.Flags().Lookup(name)
if err := flag.Value.Set(flag.DefValue); err != nil {
t.Fatalf("resetting --%s: %v", name, err)
}
flag.Changed = false
})
}
// runDeleteCmd runs `bd delete` in-process against the installed stub and
// returns its stderr and error.
func runDeleteCmd(t *testing.T, args []string) (string, error) {
t.Helper()
var err error
stderr := captureStderr(t, func() {
err = deleteCmd.RunE(deleteCmd, args)
})
return stderr, err
}
// TestDeleteRefusesStaleIDThatPrefixesAnotherIssue pins that `bd delete`
// handed an id that no longer exists does not resolve it, by leading-prefix
// abbreviation, to a DIFFERENT issue whose id it happens to begin.
//
// The shape is ordinary, not engineered. Hash length is adaptive with store
// size (3 to 8 characters), so a store that grew holds older short ids beside
// newer long ones; `--id` makes any shape; and a hierarchical child's id always
// extends its parent's. Deleting the short id and then naming it again — a
// retried script, a re-run `--from-file` chunk — reached the survivor: measured
// on a fixture, `bd delete fx-t00003` after fx-t00003 was gone resolved to
// fx-t000031, and with --force deleted it.
//
// Every route through the direct front door is covered: the single-id path
// (delete.go's inline resolution), the preview (whose output is the
// `bd delete <id> --force` line a caller is told to run next), and the batch
// path that --from-file and more than one id take (deleteBatch). The proxied
// route never resolves (DeleteRequest.IDs are exact), so it is not here.
//
// An abbreviation of a live issue is refused the same way: the resolver cannot
// tell it from a stale full id. The refusal says the id was not found (the
// words gascity's isBdNotFound reads as an already-gone bead), that delete
// needs the full id, and names the ids the input begins, so the caller can
// retype one.
func TestDeleteRefusesStaleIDThatPrefixesAnotherIssue(t *testing.T) {
cases := []struct {
name string
stored []string
args []string
fromFile []string
force bool
// wantNamed are the full ids the refusal must name.
wantNamed []string
}{
{
name: "single id --force",
stored: []string{"fx-t000031"},
args: []string{"fx-t00003"},
force: true,
wantNamed: []string{"fx-t000031"},
},
{
name: "single id preview",
stored: []string{"fx-t000031"},
args: []string{"fx-t00003"},
wantNamed: []string{"fx-t000031"},
},
{
name: "deleted parent's id with an orphaned child --force",
stored: []string{"fx-ep1.1"},
args: []string{"fx-ep1"},
force: true,
wantNamed: []string{"fx-ep1.1"},
},
{
name: "re-run of a finished --from-file chunk --force",
stored: []string{"fx-t000031", "fx-t000041"},
fromFile: []string{"fx-t00003", "fx-t00004"},
force: true,
wantNamed: []string{"fx-t000031"},
},
{
name: "abbreviation of a live issue --force",
stored: []string{"fx-t000031"},
args: []string{"t000"},
force: true,
wantNamed: []string{"fx-t000031"},
},
{
name: "abbreviation of two live issues",
stored: []string{"fx-t000031", "fx-t000041"},
args: []string{"t000"},
wantNamed: []string{"fx-t000031", "fx-t000041"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := useDeleteExactStub(t, tc.stored...)
if tc.force {
setDeleteFlag(t, "force", "true")
}
named := append([]string{}, tc.args...)
if len(tc.fromFile) > 0 {
path := filepath.Join(t.TempDir(), "ids.txt")
if err := os.WriteFile(path, []byte(strings.Join(tc.fromFile, "\n")+"\n"), 0o600); err != nil {
t.Fatalf("writing --from-file list: %v", err)
}
setDeleteFlag(t, "from-file", path)
named = append(named, tc.fromFile...)
}
stderr, err := runDeleteCmd(t, tc.args)
for _, req := range s.deleter.requests {
for _, id := range req.IDs {
if !slices.Contains(named, id) {
t.Errorf("bd delete %v (force=%v) handed the role %s (DryRun=%v), an issue it never named; stderr:\n%s",
named, tc.force, id, req.DryRun, stderr)
}
}
}
if err == nil {
t.Errorf("bd delete %v (force=%v) succeeded; want a refusal, since no stored issue has that exact id (store holds %v)",
named, tc.force, tc.stored)
}
if !strings.Contains(stderr, "not found") {
t.Errorf("bd delete %v refusal does not say the id was not found; stderr:\n%s", named, stderr)
}
if !strings.Contains(stderr, "bd delete needs the full issue id") {
t.Errorf("bd delete %v refusal does not say delete needs the full id; stderr:\n%s", named, stderr)
}
for _, id := range tc.wantNamed {
if !strings.Contains(stderr, id) {
t.Errorf("bd delete %v refusal does not name the full id %s; stderr:\n%s", named, id, stderr)
}
}
})
}
}
// TestDeleteIfRevisionGoneIDThatPrefixesAnotherIssue pins the --if-revision
// contract for the refusal above: a guarded delete whose target is gone
// reports the guard's lost race (precondition_failed, exit 13) when the gone
// id is the start of a surviving id, a deleted parent whose child survives,
// exactly as it does when the gone id is the start of nothing. gascity's
// conditional deletes switch on that code, so a refusal exiting 1 would read
// as a hard failure of a benign race. The single-id path and --cascade (which
// resolves through deleteBatch) are both covered, and the guarded write never
// runs.
func TestDeleteIfRevisionGoneIDThatPrefixesAnotherIssue(t *testing.T) {
cases := []struct {
name string
stored []string
cascade bool
json bool
}{
{name: "single id", stored: []string{"fx-ep1.1"}},
{name: "single id --json", stored: []string{"fx-ep1.1"}, json: true},
{name: "--cascade", stored: []string{"fx-ep1.1"}, cascade: true},
{name: "--cascade --json", stored: []string{"fx-ep1.1"}, cascade: true, json: true},
// The gone id begins nothing: the plain not-found these must match.
{name: "single id, no survivor", stored: []string{"fx-zz9"}},
{name: "--cascade, no survivor", stored: []string{"fx-zz9"}, cascade: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := useDeleteExactStub(t, tc.stored...)
jsonOutput = tc.json
setDeleteFlag(t, "force", "true")
setDeleteFlag(t, "if-revision", "1")
if tc.cascade {
setDeleteFlag(t, "cascade", "true")
}
stderr, err := runDeleteCmd(t, []string{"fx-ep1"})
if code, ok := exitCodeFromError(err); !ok || code != ExitGuardMismatch {
t.Fatalf("bd delete fx-ep1 --if-revision 1 (cascade=%v, store holds %v): err = %v; want exit %d; stderr:\n%s",
tc.cascade, tc.stored, err, ExitGuardMismatch, stderr)
}
if !strings.Contains(stderr, "Error deleting fx-ep1: precondition failed: issue no longer exists") {
t.Errorf("stderr does not report the lost race:\n%s", stderr)
}
if strings.Contains(stderr, "not found") {
t.Errorf("stderr leaked the unguarded not-found or refusal text beside the guard envelope:\n%s", stderr)
}
if tc.json {
body := decodeIfRevisionBody(t, lastJSONLine(t, stderr), jsonEnvelopeEnabled())
if body["code"] != ifRevisionCodePreconditionFailed || body["id"] != "fx-ep1" || body["expected_revision"] != float64(1) {
t.Errorf("JSON body = %v; want code %q, id fx-ep1, expected_revision 1", body, ifRevisionCodePreconditionFailed)
}
}
if len(s.deleter.requests) != 0 {
t.Errorf("the guarded write ran: role requests %+v", s.deleter.requests)
}
})
}
}
// TestDeleteExactIDsStillResolve is the over-refusal guard beside the test
// above: an id that exactly names an issue, with or without its prefix, alone
// or in a batch, still reaches the role as that issue and nothing else.
func TestDeleteExactIDsStillResolve(t *testing.T) {
cases := []struct {
name string
stored []string
args []string
want []string
}{
{name: "full id", stored: []string{"fx-t000031"}, args: []string{"fx-t000031"}, want: []string{"fx-t000031"}},
{name: "full hash without prefix", stored: []string{"fx-t000031"}, args: []string{"t000031"}, want: []string{"fx-t000031"}},
{name: "child id", stored: []string{"fx-ep1", "fx-ep1.1"}, args: []string{"fx-ep1.1"}, want: []string{"fx-ep1.1"}},
{
name: "batch of full ids",
stored: []string{"fx-t000031", "fx-t000041"},
args: []string{"fx-t000031", "fx-t000041"},
want: []string{"fx-t000031", "fx-t000041"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := useDeleteExactStub(t, tc.stored...)
setDeleteFlag(t, "force", "true")
stderr, err := runDeleteCmd(t, tc.args)
if err != nil {
t.Fatalf("bd delete %v --force: %v; stderr:\n%s", tc.args, err, stderr)
}
if len(s.deleter.requests) != 1 {
t.Fatalf("bd delete %v --force made %d role requests; want 1", tc.args, len(s.deleter.requests))
}
req := s.deleter.requests[0]
if req.DryRun || !req.Force {
t.Errorf("request DryRun=%v Force=%v; want a confirmed delete", req.DryRun, req.Force)
}
if !slices.Equal(req.IDs, tc.want) {
t.Errorf("bd delete %v --force deleted %v; want %v", tc.args, req.IDs, tc.want)
}
})
}
}