diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index ce1179ad6..1c83f142e 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -149,6 +149,7 @@ 100 62 TestEmbeddedReadyBlockersAndLabels 100 63 TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead +100 63 TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed 100 64 TestEmbeddedGateWaiterCheckLifecycle 100 64 TestEmbeddedPromoteMovesAWispParent diff --git a/CHANGELOG.md b/CHANGELOG.md index 96fdf4dfd..56cd92481 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1045,6 +1045,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 resolution never performed abbreviation matching in the first place) — a regression test now locks that in rather than leaving it undocumented. +- **`bd delete` no longer resolves an id it cannot find to a different issue + whose id begins with it.** + ([#7375](https://github.com/gastownhall/beads/pull/7375)). The direct + (embedded and server) route resolved + each id with the abbreviation-tolerant resolver, so an id that was already + gone (a retried delete, a re-run `--from-file` list, a parent whose child + survives) resolved by leading-prefix match to whichever surviving issue's id + it begins: after `fx-t00003` was deleted, `bd delete fx-t00003` previewed + `fx-t000031` and printed `bd delete fx-t000031 --force` as the next step, + and with `--force` deleted it. `--quiet` silenced the partial-id notice, so + a `--force --quiet` re-run deleted issues it never named without a word. + `bd delete` now requires an exact id on the preview and with `--force`, as + `bd comment` does and as the team-server route already did; full ids, bare + full hashes, child ids and routed ids resolve as before. An abbreviation is + refused with `issue "t000" not found: bd delete needs the full issue id, and + "t000" is only the start of fx-t000031`, naming every id it matches; under + `--if-revision` it is the guard's lost race instead (`precondition_failed`, + exit 13), as for any other gone id. This is a user-visible change: a script + or habit that deletes by abbreviation now gets that error and must pass the + full id. Reads and other writes keep accepting abbreviations; see [Working + with IDs](docs/core-concepts/hash-ids.md#working-with-ids). + - **A git hook beads never wrote is no longer reported as installed** ([#6084](https://github.com/gastownhall/beads/issues/6084)). `getHookVersion` returns no error for a readable hook file that carries no beads markers, so a diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 3d6b79419..13895fd37 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -684,6 +684,7 @@ go_test( "defer_wake_proxied_integration_test.go", "defer_wake_server_test.go", "delete_embedded_test.go", + "delete_exact_id_test.go", "delete_if_revision_proxied_concurrency_test.go", "delete_input_test.go", "delete_proxied_integration_test.go", diff --git a/cmd/bd/delete.go b/cmd/bd/delete.go index b466b1f76..4d73a0057 100644 --- a/cmd/bd/delete.go +++ b/cmd/bd/delete.go @@ -3,6 +3,7 @@ package main import ( "bufio" "context" + "errors" "fmt" "os" "strings" @@ -13,6 +14,7 @@ import ( storeissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/utils" "github.com/steveyegge/beads/issueops" ) @@ -123,7 +125,12 @@ Force: Delete and orphan dependents // stays in the front door: issueops.DeleteRequest.IDs are exact, because // resolving an ambiguous prefix and then deleting the row it hit is the // one place a convenience is not. - routedResult, err := resolveAndGetIssueForMutation(ctx, store, issueID) + // + // Exact here too, never a leading-prefix abbreviation: an id that is + // gone (already deleted, a re-run script) would otherwise resolve to + // whichever surviving issue's id it begins, and the preview would + // print `bd delete --force` as the next step. + routedResult, err := resolveAndGetIssueForMutationExact(ctx, store, issueID) if err != nil { // mc-zndi7.81: this pre-flight existence check runs before // deleter.Delete() and the per-id lock fence #7244 added, so a @@ -136,6 +143,9 @@ Force: Delete and orphan dependents if isNotFoundErr(err) { return HandleError("issue %s not found", issueID) } + if refusal := deleteAbbreviationRefusal(err); refusal != nil { + return HandleError("%v", refusal) + } return HandleError("%v", err) } defer routedResult.Close() @@ -303,6 +313,34 @@ func renderSingleDeletePreview( return nil } +// deleteAbbreviationRefusal is the refusal of an id that names no issue +// exactly but is the start of one or more: delete needs the full id, so say +// that and name the ids it begins. It is nil for any other error. +func deleteAbbreviationRefusal(err error) error { + var abbrev *utils.AbbreviatedIDError + if !errors.As(err, &abbrev) { + return nil + } + return &deleteAbbreviationError{abbrev: abbrev} +} + +// deleteAbbreviationError is that refusal. To a delete, an id that is only the +// start of other ids names no row, so the text leads with "not found" — the +// words gascity's isBdNotFound reads as an already-gone bead — and the error +// unwraps to storage.ErrNotFound, which lets a guarded `bd delete --cascade` +// report it as the same lost race as any other gone target (see +// reportIfRevisionTargetGone). +type deleteAbbreviationError struct { + abbrev *utils.AbbreviatedIDError +} + +func (e *deleteAbbreviationError) Error() string { + return fmt.Sprintf("issue %q not found: bd delete needs the full issue id, and %q is only the start of %s", + e.abbrev.Input, e.abbrev.Input, strings.Join(e.abbrev.Matches, ", ")) +} + +func (e *deleteAbbreviationError) Unwrap() []error { return []error{storage.ErrNotFound, e.abbrev} } + // deleteIssue removes an issue from the database. func deleteIssue(ctx context.Context, issueID string) error { return store.DeleteIssue(ctx, issueID) @@ -311,9 +349,11 @@ func deleteIssue(ctx context.Context, issueID string) error { // deleteBatch is the multi-id and cascade path, shared by `bd delete`, // `bd cleanup`, `bd wisp gc` and `bd mol burn`. // -// It resolves the ids the way this front door always has - prefix matching and +// It resolves the ids in the front door - exact-id matching and // cross-repository routing, which issueops.DeleteRequest deliberately does not -// do - and hands the RESOLVED ids to the role. +// do - and hands the RESOLVED ids to the role. Never a leading-prefix +// abbreviation: a re-run of a finished --from-file list would otherwise +// delete every surviving issue whose id one of its ids begins. // // ifRevision is non-nil only via `bd delete`'s own --if-revision (beads#4682); // its other three callers always pass nil, and requireSingleIfRevisionID has @@ -332,10 +372,12 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c notFound := []string{} var routedStore storage.DoltStorage for _, id := range issueIDs { - result, err := resolveAndGetIssueForMutation(ctx, store, id) + result, err := resolveAndGetIssueForMutationExact(ctx, store, id) if err != nil { if isNotFoundErr(err) { notFound = append(notFound, id) + } else if refusal := deleteAbbreviationRefusal(err); refusal != nil { + return refusal } else { return fmt.Errorf("getting issue %s: %v", id, err) } diff --git a/cmd/bd/delete_exact_id_test.go b/cmd/bd/delete_exact_id_test.go new file mode 100644 index 000000000..e3638bac6 --- /dev/null +++ b/cmd/bd/delete_exact_id_test.go @@ -0,0 +1,373 @@ +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 --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 --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) + } + }) + } +} diff --git a/cmd/bd/if_revision.go b/cmd/bd/if_revision.go index 4131def27..759f03aec 100644 --- a/cmd/bd/if_revision.go +++ b/cmd/bd/if_revision.go @@ -11,6 +11,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" "github.com/steveyegge/beads/issueops" ) @@ -125,15 +126,19 @@ func classifyIfRevisionFailure(err error, ifRevision *int64) (code, reason strin // and any other resolution failure is not a guard outcome; ok is false for // both and the caller's ordinary failure handling applies unchanged. `bd // delete --cascade` resolves through deleteBatch instead: its not-found error -// keeps the storage.ErrNotFound sentinel, so the caller's -// reportIfRevisionFailure classifies it the same way. +// and its abbreviation refusal both keep the storage.ErrNotFound sentinel, so +// the caller's reportIfRevisionFailure classifies them the same way. // // err is matched with isNotFoundErr, which also accepts ResolvePartialID's -// unwrapped "no issue found matching" text, and reported as the literal -// storage.ErrNotFound sentinel classifyIfRevisionFailure matches via -// errors.Is. +// unwrapped "no issue found matching" text, or as +// utils.ErrAbbreviatedIDNotAllowed: under `bd delete`'s exact resolution an id +// that is only the start of other ids names no row either (a deleted parent +// whose child survives), so it is the same gone target. Either way it is +// reported as the literal storage.ErrNotFound sentinel +// classifyIfRevisionFailure matches via errors.Is. func reportIfRevisionTargetGone(action, id string, err error, ifRevision *int64) (reportedErr error, ok bool) { - if ifRevision == nil || !isNotFoundErr(err) { + gone := isNotFoundErr(err) || errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) + if ifRevision == nil || !gone { return nil, false } return reportIfRevisionFailure(action, id, storage.ErrNotFound, ifRevision) diff --git a/cmd/bd/if_revision_embedded_test.go b/cmd/bd/if_revision_embedded_test.go index 2be7c570f..a9012f20d 100644 --- a/cmd/bd/if_revision_embedded_test.go +++ b/cmd/bd/if_revision_embedded_test.go @@ -245,6 +245,57 @@ func TestIfRevisionDeletePreflightGoneIsPreconditionFailed(t *testing.T) { } } +// TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed is the +// test above with a gone id that is still the start of a surviving one: a +// deleted parent whose orphaned child (.1) outlives it. `bd delete` +// resolves exactly, so the parent's id is refused as an abbreviation of the +// child rather than resolved to it, and under --if-revision that refusal must +// be the same lost race (exit 13, "precondition failed") on the single-id path +// and on --cascade's deleteBatch path, with the child untouched. The +// TestEmbedded name is what puts this test in a CI lane +// (.github/scripts/embedded-test-shard.sh); under any other name it skips +// everywhere. +func TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed(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", "pg") + + parent := bdCreate(t, bd, dir, "Gone parent", "--type", "task") + child := bdCreate(t, bd, dir, "Surviving child", "--type", "task", "--parent", parent.ID) + if !strings.HasPrefix(child.ID, parent.ID) { + t.Fatalf("child id %s does not begin with its parent's id %s; this test needs it to", child.ID, parent.ID) + } + rev0 := bdShowRevision(t, bd, dir, parent.ID) + + bdDelete(t, bd, dir, parent.ID, "--force") + // The parent is gone, yet a read still takes its id as an abbreviation and + // resolves it to the child: the id a delete must not resolve the same way. + if got := bdShow(t, bd, dir, parent.ID); got.ID != child.ID { + t.Fatalf("bd show %s after its delete returned %s; want the surviving child %s", parent.ID, got.ID, child.ID) + } + + for _, extra := range [][]string{nil, {"--cascade"}} { + args := append([]string{"delete", parent.ID, "--if-revision", revStr(rev0), "--force"}, extra...) + out, code := bdRunFailCode(t, bd, dir, args...) + if code != ExitGuardMismatch { + t.Errorf("bd %s exit code = %d, want %d\n%s", strings.Join(args, " "), code, ExitGuardMismatch, out) + } + if !strings.Contains(out, "precondition failed") { + t.Errorf("bd %s should say \"precondition failed\", got:\n%s", strings.Join(args, " "), out) + } + if strings.Contains(out, "not found") { + t.Errorf("bd %s leaked the unguarded refusal instead of the guard envelope:\n%s", strings.Join(args, " "), out) + } + } + if got := bdShow(t, bd, dir, child.ID); got.ID != child.ID { + t.Errorf("bd show %s returned %s; want the child untouched", child.ID, got.ID) + } +} + // TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb pins // ga-vnycm2.10, the close/update/assign/reopen half of mc-zndi7.81: `bd // close`, `bd update`, `bd assign` and `bd reopen` each resolve the row with diff --git a/cmd/bd/if_revision_test.go b/cmd/bd/if_revision_test.go index c788a1ac1..1319be0db 100644 --- a/cmd/bd/if_revision_test.go +++ b/cmd/bd/if_revision_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/utils" "github.com/steveyegge/beads/issueops" ) @@ -303,6 +304,9 @@ func TestReportIfRevisionTargetGone(t *testing.T) { }{ {"sentinel_guarded", fmt.Errorf("resolving: %w", storage.ErrNotFound), &ifRevision, true}, {"partial_id_text_guarded", errors.New(`no issue found matching "bd-x"`), &ifRevision, true}, + // bd delete's exact resolution: bd-x is gone, its child bd-x.1 is not. + {"abbreviation_guarded", &utils.AbbreviatedIDError{Input: "bd-x", Matches: []string{"bd-x.1"}}, &ifRevision, true}, + {"abbreviation_unguarded", &utils.AbbreviatedIDError{Input: "bd-x", Matches: []string{"bd-x.1"}}, nil, false}, {"sentinel_unguarded", storage.ErrNotFound, nil, false}, {"other_error_guarded", errors.New("connection refused"), &ifRevision, false}, } { diff --git a/docs/core-concepts/hash-ids.md b/docs/core-concepts/hash-ids.md index 8c8efd2e6..6845e4185 100644 --- a/docs/core-concepts/hash-ids.md +++ b/docs/core-concepts/hash-ids.md @@ -118,30 +118,40 @@ bd show bd-a1b2c3d4 bd list --full-ids ``` -### `bd comment` requires the full id +### `bd comment` and `bd delete` require the full id -Every command above resolves an abbreviation the same way — but `bd comment - "text"` (and its `bd comments add` twin) is the one deliberate exception: -it accepts only a full, exact id, never an abbreviation. This is a policy -trade for an agent fleet, not an oversight: an abbreviation that happens to be -a leading-prefix match for the wrong issue would silently write the comment -there instead of erroring, and a comment write has no confirmation step to -catch it before the message lands on the wrong issue. Reads and every other -mutation (`show`, `close`, `update`, …) keep accepting abbreviations as -documented above. +Every command above resolves an abbreviation the same way, with two deliberate +exceptions: `bd comment "text"` (and its `bd comments add` twin) and +`bd delete` accept only a full, exact id, never an abbreviation. This is a +policy trade for an agent fleet, not an oversight: an abbreviation that happens +to be a leading-prefix match for the wrong issue would land the write there +instead of erroring. A comment write has no confirmation step to catch it, and +a deletion cannot be undone. + +For `bd delete` the wrong match is easy to reach by accident. The id of an +issue that is already gone is still the start of other ids — its child's +(`bd-a3f8e9.1` after `bd-a3f8e9` is deleted), or a longer hash that happens to +begin with it — so retrying a delete or re-running a `--from-file` list would +otherwise reach an issue nobody named. The refusal says delete needs the full +id and names the ids the input matches. + +Reads and every other mutation (`show`, `close`, `update`, …) keep accepting +abbreviations as documented above. ```bash bd show a1b2 # OK — abbreviation resolves for reads bd close a1b2 # OK — abbreviation resolves for other writes bd comment a1b2 "text" # refused — comment writes require the full id bd comment bd-a1b2c3d4 "text" # OK — use the full id from `bd show` +bd delete a1b2 # refused — deletes require the full id +bd delete bd-a1b2c3d4 # OK — previews the deletion; add --force to delete ``` -A reserved word (`list`, `add`, `rm`, `delete`) as the id positional is -refused the same way, for a related reason: `bd comment list "text"` almost -always means the caller confused the singular shorthand with the plural `bd -comments list`/`bd comments add "text"`, not that an issue is literally -named `list`. +A reserved word (`list`, `add`, `rm`, `delete`) as `bd comment`'s id +positional is refused the same way, for a related reason: `bd comment list +"text"` almost always means the caller confused the singular shorthand with the +plural `bd comments list`/`bd comments add "text"`, not that an issue is +literally named `list`. ## Migration from Sequential IDs @@ -158,7 +168,7 @@ bd show bd-new --json | jq '.original_id' ## Best Practices 1. **Use short references** - `bd-a1b2` is usually unique enough, except on - `bd comment` writes, which require the full id (see + `bd comment` writes and `bd delete`, which require the full id (see [Working with IDs](#working-with-ids) above) 2. **Use `--json` for scripts** - Parse full ID programmatically 3. **Reference by hash in commits** - `Fixed bd-a1b2` in commit messages diff --git a/internal/utils/id_parser.go b/internal/utils/id_parser.go index 93a1ec9ab..8c42c0c95 100644 --- a/internal/utils/id_parser.go +++ b/internal/utils/id_parser.go @@ -34,6 +34,22 @@ var ErrAmbiguousID = errors.New("ambiguous issue ID") // id") — see bd comment's resolveAndGetIssueForMutationExact caller. var ErrAbbreviatedIDNotAllowed = errors.New("id is a valid abbreviation, but exact-match resolution is required here") +// AbbreviatedIDError is the error ResolvePartialIDExact returns when Input +// names no issue exactly but is a leading-prefix abbreviation of Matches. It +// wraps ErrAbbreviatedIDNotAllowed, so errors.Is callers see the sentinel +// unchanged; a caller that wants to name the full ids reads Matches through +// errors.As. +type AbbreviatedIDError struct { + Input string + Matches []string // sorted +} + +func (e *AbbreviatedIDError) Error() string { + return fmt.Sprintf("%v: %q (matches %v)", ErrAbbreviatedIDNotAllowed, e.Input, e.Matches) +} + +func (e *AbbreviatedIDError) Unwrap() error { return ErrAbbreviatedIDNotAllowed } + type PartialIDResolverStore interface { SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error) @@ -310,7 +326,7 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s // resolveAndGetIssueForMutationExact) can surface an accurate, // actionable message rather than claiming the issue is missing. sort.Strings(abbrevOnly) - return "", fmt.Errorf("%w: %q (matches %v)", ErrAbbreviatedIDNotAllowed, input, abbrevOnly) + return "", &AbbreviatedIDError{Input: input, Matches: abbrevOnly} } return "", fmt.Errorf("no issue found matching %q", input) } diff --git a/internal/utils/id_parser_fake_test.go b/internal/utils/id_parser_fake_test.go index e8015a816..eea8e2f5c 100644 --- a/internal/utils/id_parser_fake_test.go +++ b/internal/utils/id_parser_fake_test.go @@ -10,6 +10,7 @@ package utils_test import ( "context" "errors" + "slices" "strings" "testing" @@ -175,6 +176,48 @@ func TestResolvePartialIDExact_AbbreviationRefusalIsDistinguishableFromNotFound( } } +// TestResolvePartialIDExact_AbbreviationErrorNamesTheMatches pins the typed +// error behind ErrAbbreviatedIDNotAllowed: errors.As yields the input and the +// sorted full ids it abbreviates, so a caller can name them (bd delete does), +// while errors.Is and the error text stay what they were. +func TestResolvePartialIDExact_AbbreviationErrorNamesTheMatches(t *testing.T) { + ctx := context.Background() + store := &fakeResolverStore{ + issues: []fakeIssue{ + {id: "hq-a3f8zz", ephemeral: false}, + {id: "hq-a3f8e9", ephemeral: false}, + }, + config: map[string]string{"issue_prefix": "hq"}, + } + + _, err := utils.ResolvePartialIDExact(ctx, store, "a3f8") + var abbrev *utils.AbbreviatedIDError + if !errors.As(err, &abbrev) { + t.Fatalf(`ResolvePartialIDExact("a3f8") error = %v; want an *AbbreviatedIDError`, err) + } + if abbrev.Input != "a3f8" { + t.Errorf("Input = %q; want %q", abbrev.Input, "a3f8") + } + if want := []string{"hq-a3f8e9", "hq-a3f8zz"}; !slices.Equal(abbrev.Matches, want) { + t.Errorf("Matches = %v; want %v (sorted)", abbrev.Matches, want) + } + if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf("error %v no longer wraps ErrAbbreviatedIDNotAllowed", err) + } + if want := `id is a valid abbreviation, but exact-match resolution is required here: "a3f8" (matches [hq-a3f8e9 hq-a3f8zz])`; err.Error() != want { + t.Errorf("error text = %q; want %q", err.Error(), want) + } + + // The wisp branch builds the same error. + _, err = utils.ResolvePartialIDExact(ctx, &fakeResolverStore{ + issues: []fakeIssue{{id: "hq-wisp-list3t0", ephemeral: true}}, + config: map[string]string{"issue_prefix": "hq"}, + }, "list") + if !errors.As(err, &abbrev) || !slices.Equal(abbrev.Matches, []string{"hq-wisp-list3t0"}) { + t.Errorf(`ResolvePartialIDExact("list") error = %v; want an *AbbreviatedIDError naming hq-wisp-list3t0`, err) + } +} + // TestResolvePartialIDExact_RefusesSentinelTokens pins where #6215's bare- // sentinel guard has to live once this PR splits the resolver in two. //