beads/cmd/bd/if_revision.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

209 lines
11 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
)
// ifRevisionFlagHelp is the shared half of --if-revision's --help text across
// `bd update`, `bd close`, `bd assign`, `bd delete` and `bd reopen`: the value
// syntax, the one-id rule and the exit-code contract. Each verb appends what is specific
// to it (close has no other guards to compose with; update composes with
// --if-assignee/--if-status).
const ifRevisionFlagHelp = "Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)."
// parseIfRevisionFlag reads --if-revision with presence detected via
// Changed(), matching --if-assignee/--if-status's idiom, and parses it with
// types.ParseRevisionToken — the one encoding bd uses for a revision token on
// the wire, so a value copied from `bd show --json`'s "revision" field always
// parses and a typo is refused before any write rather than silently never
// matching.
func parseIfRevisionFlag(cmd *cobra.Command) (*int64, error) {
if !cmd.Flags().Changed("if-revision") {
return nil, nil
}
raw, _ := cmd.Flags().GetString("if-revision")
v, err := types.ParseRevisionToken(strings.TrimSpace(raw))
if err != nil {
return nil, HandleErrorRespectJSON("invalid --if-revision %q: must be the decimal int64 revision from `bd show --json` (%v)", raw, err)
}
return &v, nil
}
// requireSingleIfRevisionID enforces A8's "one id only" rule: --if-revision
// names a single row's token, so more than one id is refused before any
// write rather than applying the one token to every id in the batch (T4.8).
func requireSingleIfRevisionID(ifRevision *int64, ids []string) error {
if ifRevision == nil || len(ids) <= 1 {
return nil
}
return HandleErrorRespectJSON("--if-revision guards one issue only; %d ids were given — send one guarded request per issue", len(ids))
}
// Machine body codes this CLI emits for a refused --if-revision write, shared
// verbatim with gascity's bdstore_conditional.go classifier, which switches on
// `code` rather than the exit code.
const (
ifRevisionCodePreconditionFailed = "precondition_failed"
ifRevisionCodeUnsupported = "conditional_write_unsupported"
)
// classifyIfRevisionFailure maps err to the machine code and human reason
// gascity's bdstore_conditional.go classifier expects from a single-id write
// guarded by --if-revision: "precondition_failed" for a stale --if-revision,
// --if-assignee or --if-status guard (T4.5 requires all three to report
// through the one envelope when --if-revision is present), for the row
// having vanished out from under the guard entirely (storage.ErrNotFound),
// or "conditional_write_unsupported" for a backend that cannot honor
// ExpectedVersion at all. ok is false for any other failure, which the
// caller's own (unrelated) failure handling reports unchanged.
//
// ifRevision is the --if-revision flag's own parsed value, used ONLY as the
// expected_revision fallback for the bare storage.ErrVersionMismatch sentinel
// below, which (unlike *issueops.VersionMismatchError) carries no Expected
// field of its own. Every upstream producer in this repo returns the typed
// error; the bare sentinel is what bd-enterprise's HTTP client maps a 409
// precondition_failed onto (internal/enterprise/httpstore/wire/problem.go),
// since the wire body it decodes carries no current revision either. The
// fallback keeps that HTTP-backed path classified correctly instead of
// falling through to the caller's generic (uncoded, exit-1) failure handling.
func classifyIfRevisionFailure(err error, ifRevision *int64) (code, reason string, expected, current *int64, ok bool) {
var vme *issueops.VersionMismatchError
switch {
case errors.As(err, &vme):
return ifRevisionCodePreconditionFailed, "revision mismatch", &vme.Expected, &vme.Current, true
case errors.Is(err, storage.ErrNotFound):
// The row named by a single-id --if-revision write no longer exists:
// a guarded write that lost to a concurrent delete (mc-zndi7.73),
// observed either inside the guarded write or at the verb's
// pre-flight resolution (reportIfRevisionTargetGone). Both are the
// same precondition failure from this guard's point of view: the
// exact revision the caller named is gone, so there is nothing left
// to compare it against. A mistyped id under --if-revision reports
// the same way — the CLI cannot tell "never existed" from "deleted
// a moment ago", and either way the named revision is not current.
// current is omitted (nothing to report); expected falls back to the
// caller's own --if-revision value, same as the bare
// storage.ErrVersionMismatch case below.
return ifRevisionCodePreconditionFailed, "issue no longer exists", ifRevision, nil, true
case errors.Is(err, storage.ErrAssigneeMismatch):
return ifRevisionCodePreconditionFailed, "assignee mismatch", nil, nil, true
case errors.Is(err, storage.ErrStatusMismatch):
return ifRevisionCodePreconditionFailed, "status mismatch", nil, nil, true
case errors.Is(err, storage.ErrVersionMismatch):
// current is deliberately omitted (unknown to this sentinel) rather
// than guessed — gascity tolerates the omission, decoding only the
// fields present in the body.
return ifRevisionCodePreconditionFailed, "revision mismatch", ifRevision, nil, true
}
var unsupported *issueops.ErrUnsupported
if errors.As(err, &unsupported) {
return ifRevisionCodeUnsupported, "", nil, nil, true
}
return "", "", nil, nil, false
}
// reportIfRevisionTargetGone reports a single-id --if-revision write whose
// pre-flight resolution (resolveAndGetIssueForMutation on the direct route,
// the advisory pre-read on the proxied route) found no row. Every guarded
// verb resolves the row BEFORE its guarded write, so a racer that loses to a
// concurrent `bd delete` sees the row vanish either here or inside the guarded
// write, depending only on which side of the delete's commit its resolution
// lands (mc-zndi7.81 for delete, ga-vnycm2.10 for close/update/assign/reopen).
// Both are the same outcome — the revision the caller named is gone — so both
// report precondition_failed / ExitGuardMismatch with the reason "issue no
// longer exists". With no --if-revision there is no guard to report through,
// 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
// 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, 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) {
gone := isNotFoundErr(err) || errors.Is(err, utils.ErrAbbreviatedIDNotAllowed)
if ifRevision == nil || !gone {
return nil, false
}
return reportIfRevisionFailure(action, id, storage.ErrNotFound, ifRevision)
}
// ifRevisionFailureBody is the machine JSON this CLI attaches to a refused
// --if-revision write, decoded by gascity's bdConditionalErrorBody
// (bdstore_conditional.go). ExpectedRevision/CurrentRevision are pointers so
// an absent field (assignee/status guard, or unsupported) is distinguishable
// from a legitimate zero revision, and they marshal as JSON INTEGERS — never
// strings, unlike `bd show --json`'s "revision" — because gascity decodes them
// straight into *int64 and a string there makes its json.Decoder fail closed
// on the whole object (bdstore_conditional.go:134-139).
type ifRevisionFailureBody struct {
Error string `json:"error"`
Code string `json:"code"`
ID string `json:"id"`
ExpectedRevision *int64 `json:"expected_revision,omitempty"`
CurrentRevision *int64 `json:"current_revision,omitempty"`
}
// reportIfRevisionFailure reports a single-id write refused under an active
// --if-revision guard (alone or composed with --if-assignee/--if-status) and
// returns the exit error the CLI contract promises: ExitGuardMismatch (13)
// for a stale guard, 1 for a backend that cannot honor ExpectedVersion at
// all. action is the gerund for the human line ("updating", "closing",
// "assigning", "deleting"), matching this file's existing "Error <gerund>
// <id>: <reason>" convention. ok is false when err is not a guard outcome at
// all, in which case the caller's existing failure handling applies
// unchanged and nothing is printed here.
//
// In --json mode the JSON body is the LAST line on stderr, flat or under
// `data` per jsonEnvelopeEnabled — mirroring reportUpdateFailures — and the
// human "error" text always contains "precondition failed" so gascity's
// code-less fallback (bdstore_conditional.go:320-327) still matches if a
// caller ever loses the `code` field.
func reportIfRevisionFailure(action, id string, err error, ifRevision *int64) (reportedErr error, ok bool) {
code, reason, expected, current, ok := classifyIfRevisionFailure(err, ifRevision)
if !ok {
return nil, false
}
humanErr := "backend does not support --if-revision (conditional write unsupported)"
if code == ifRevisionCodePreconditionFailed {
humanErr = "precondition failed: " + reason
}
fmt.Fprintf(os.Stderr, "Error %s %s: %s\n", action, id, humanErr)
if jsonOutput {
body := ifRevisionFailureBody{Error: humanErr, Code: code, ID: id, ExpectedRevision: expected, CurrentRevision: current}
var payload interface{}
if jsonEnvelopeEnabled() {
payload = map[string]interface{}{"schema_version": JSONSchemaVersion, "data": body}
} else {
payload = struct {
ifRevisionFailureBody
SchemaVersion int `json:"schema_version"`
}{body, JSONSchemaVersion}
}
if data, merr := json.Marshal(payload); merr == nil {
fmt.Fprintln(os.Stderr, string(data))
}
}
if code == ifRevisionCodePreconditionFailed {
return &exitError{Code: ExitGuardMismatch}, true
}
return &exitError{Code: 1}, true
}