* fix(gate): resolve a bead gate whose awaited bead no longer exists (wy-dgfuiu) A gate with await_type=bead whose awaited bead has been purged could never resolve: GetIssue returns storage.ErrNotFound (or a wrapped sql.ErrNoRows) against real storage, checkBeadGate returned (false, "bead gate %q: %v"), the bead arm of evaluateGates never sets r.err, and applyGateCheckResults fell to the "pending" arm with exit 0. The gate stayed pending forever. Treat a missing bead as resolution, reusing the existing gateProxiedNotFound predicate so a genuine backend or transport failure still stays pending. close.go shares checkBeadGate and inherits the fix. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MjQHZQoR8qZTaNj2QTZokr * fix(gate): resolve a deleted bead gate target only after a local sighting Review fixes for #6395 (adopt-pr iterations 1 to 5). The PR resolves a bead gate when its awaited bead no longer exists, but the lookups it relies on turned a routing failure into not-found: the direct getter (getIssueWithRouting) and the proxied getter both returned the local miss when a prefix-routed rig could not be read, so an OPEN bead in an unreachable rig resolved its gate and unblocked the step. An await_id that never named a real bead (a typo, a short ID) also resolved on the first check. - A miss outside this rig's own store is errBeadGateTargetUnconfirmed: a matched routes.jsonl route whose rig fails or does not return the bead, an unreadable routes.jsonl, or the contributor auto-routed store. The gate stays pending and the reason names the cause. inspectBeadGate tests it before not-found, because the wrapped routing error can itself be a not-found. Only this rig's own absence counts as gone. - bd gate check resolves a gone target only if an earlier check saw it in this rig. The first local sighting stamps await_seen=<await_id> in the gate's metadata (an OpSetMetadata merge, so other keys survive, and retargeting the gate invalidates it). A target that is gone and was never seen stays pending with "no earlier gate check saw it; check the await_id, or close the gate with bd gate resolve". A bead read through a route is never stamped, so a misdirected route cannot arm a later local miss. A failed stamp write is an error row, like a failed gh:run await_id persist. - The proxied getter reads the target with workapi.GetIssueOrWisp (the issue use case alone never returns a wisp), stamps inside the apply transaction, and never auto-routes. - bd close applies the same rule (evaluateBeadGate, recording no sighting): a gone bead satisfies the gate only if an earlier check saw it, so closing a gate on a typo'd await_id still needs --force. - bd close reads the awaited bead from the store that owns the gate (RoutedResult.Store), as bd gate check in that rig would. Read from the launcher's store, a routed gate whose awaited bead only its own rig can reach (no route for it from the launcher) saw that open bead as missing and, its sighting recorded, closed without --force. The proxied-server route keeps the fresh-read getter (#5861). - bd rename and bd rename-prefix (both the rename loop and --repair) point a bead gate at its bead's new ID, keeping a <rig>: prefix and carrying the sighting. UpdateIssueID rewrites text references but never await_id, so a seen bead's rename read as a deletion and resolved the gate on its next check. - UpdateIssueID also commits on its own, so a retarget written after it left a window, or after a failure a lasting state, where the gate held a sighting of an ID that no longer existed and resolved while its bead was open under the new ID. All three paths now rename through renameIssueKeepingBeadGates, which orders the writes so no state in between resolves a gate: it moves await_id to the new ID while the sighting still names the old one (dropping, in the same write, a sighting that already names the new ID), renames the bead, and then records the sighting under the new ID. A check in between finds a never-seen ID and stays pending. If moving a gate or renaming the bead fails, the gates are pointed back at the old ID without a sighting, since a failed write may still have landed, and the rename fails: bd rename exits non-zero instead of warning from its text-reference loop. Losing only the final sighting write is a warning; the next check records the sighting again. - A check lists the gate before it looks the bead up, so a rename landing in between left it holding a copy that still waited on the old ID with its sighting: the old ID was gone, and the check closed the gate while the bead was open under its new ID. Once the bead is found gone, evaluateBeadGate reads the gate back from its own store (rereadBeadGate) and resolves only if the stored gate still waits on the same await_id and still records the sighting. The rename moves the gate before the bead takes the new ID, so a read made after the miss sees the move. This covers bd gate check, its proxied route and bd close; a gate that cannot be read back, or is found only through a route, stays pending. - checkBeadGate, the target lookup without the sighting rule, had no production caller left and read like the bead-gate rule, which is how bd close came to skip the sighting. It moves into the tests; inspectBeadGate carries the lookup contract and points callers at evaluateBeadGate. - The gate check help, docs/workflows/gates.md and the CHANGELOG describe the rule, including that a rename does not read as a deletion to a check or bd close that read the gate before it, and that a rename that fails partway leaves the gate pending without a sighting; the #6404 entry no longer says a routed read failure reads as not-found. The CHANGELOG also warns that a rename by an older bd does not move the gate, so once a check has seen the bead, the next check or bd close after that rename closes the gate while the bead is still open: upgrade the clients that rename beads together with the ones that check gates. docs/cli-reference is pinned to v1.2.2, so it is unchanged (generate-cli-docs.sh --check passes). Tests: TestCheckBeadGate_UnconfirmedMissStaysPending, TestEvaluateGates_BeadGateSightingRule, TestEvaluateBeadGate_*, TestBeadGateSeenUpdate_KeepsOtherMetadata, TestBeadGateTargetSeen, TestProxiedFreshReadGetter_LocalMissFollowsRoutes, TestRoutedBeadGateGetter_ReportsWhereTheAnswerCameFrom, TestCheckGateSatisfaction_BeadGateNeedsASighting, TestCloseDirectPreflight_BeadGateReadsTheGatesOwnStore, TestCloseBeadGateGetter_RouteSelection, TestBeadGateRetargetUpdate, TestPlanBeadGateMoves, TestRenameIssueKeepingBeadGates and TestRenameIssueKeepingBeadGates_FailedWritesResolveNoGate, which fails each write of a rename in turn, landed or not, and evaluates every gate after each write, both as stored and as a concurrent check listed it before the rename (unit); the unreadable-rig step of TestCheckBeadGateCrossRigPrefixRoute, TestRepairPrefixesRetargetsBeadGates (gates renamed before and after their bead) and TestRenameFailureLeavesBeadGatesPending (bd rename, --repair and rename-prefix with a failing UpdateIssueID, landed or not) (cgo); TestEmbeddedGateCreate/check_bead_gate_resolves_only_a_missing_target_it_saw and /rename_keeps_a_bead_gate_on_its_target (embedded); TestProxiedServerGateCheck/bead_gate_resolves_when_seen_target_is_deleted and /bead_gate_never_seen_target_stays_pending (proxied). Reordering the unconfirmed case after not-found, dropping the sighting condition, swallowing the routed error, stamping routed sightings, or matching any stamp regardless of await_id each fails these tests, as do closing with the sighting-blind lookup, reading the launcher's store on close, dropping the carried sighting or the rig prefix on a retarget, dropping the retarget from bd rename, the rename-prefix loop or --repair, renaming the bead before moving its gates, keeping the sighting when moving a gate back, keeping a stale sighting of the new ID, skipping the final sighting write, resolving a gone bead without reading the gate back or from a gate read back that moved, lost its sighting or was found only through a route, or reporting an unconfirmed read-back as an error or an unreadable gate as pending. 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 Fable 5.1 <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
270 lines
9 KiB
Go
270 lines
9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
var renameCmd = &cobra.Command{
|
|
Use: "rename <old-id> <new-id>",
|
|
Short: "Rename an issue ID",
|
|
Long: `Rename an issue from one ID to another.
|
|
|
|
This updates:
|
|
- The issue's primary ID
|
|
- All references in other issues (descriptions, titles, notes, etc.)
|
|
- Dependencies pointing to/from this issue
|
|
- Labels, comments, and events
|
|
|
|
Examples:
|
|
bd rename bd-w382l bd-dolt # Rename to memorable ID
|
|
bd rename gt-abc123 gt-auth # Use descriptive ID
|
|
|
|
Note: The new ID must use a valid prefix for this database.`,
|
|
Args: cobra.ExactArgs(2),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runRename,
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(renameCmd)
|
|
}
|
|
|
|
func runRename(cmd *cobra.Command, args []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("rename is not supported in proxied-server mode")
|
|
}
|
|
evt := metrics.NewCommandEvent("rename")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
oldID := args[0]
|
|
newID := args[1]
|
|
|
|
if oldID == newID {
|
|
return HandleError("old and new IDs are the same")
|
|
}
|
|
|
|
idPattern := regexp.MustCompile(`^[a-z]+-[a-zA-Z0-9._-]+$`)
|
|
if !idPattern.MatchString(newID) {
|
|
return HandleError("invalid new ID format %q: must be prefix-suffix (e.g., bd-dolt)", newID)
|
|
}
|
|
|
|
ctx := context.Background()
|
|
if err := ensureStoreActive(); err != nil {
|
|
return HandleError("failed to get storage: %v", err)
|
|
}
|
|
|
|
oldIssue, err := store.GetIssue(ctx, oldID)
|
|
if err != nil {
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
return HandleError("issue %s not found", oldID)
|
|
}
|
|
return HandleError("failed to get issue %s: %v", oldID, err)
|
|
}
|
|
|
|
_, err = store.GetIssue(ctx, newID)
|
|
if err == nil {
|
|
return HandleError("issue %s already exists", newID)
|
|
}
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
return HandleError("failed to check for existing issue: %v", err)
|
|
}
|
|
|
|
gateType := types.TypeGate
|
|
gates, err := store.SearchIssues(ctx, "", types.IssueFilter{IssueType: &gateType})
|
|
if err != nil {
|
|
return HandleError("failed to list gates: %v", err)
|
|
}
|
|
|
|
actor := getActorWithGit()
|
|
if err := renameIssueKeepingBeadGates(ctx, store, oldIssue, newID, beadGatesByTarget(gates)[oldID], actor); err != nil {
|
|
return HandleError("failed to rename issue: %v", err)
|
|
}
|
|
|
|
if err := updateReferencesInAllIssues(ctx, store, oldID, newID, actor); err != nil {
|
|
fmt.Printf("Warning: failed to update some references: %v\n", err)
|
|
}
|
|
|
|
fmt.Printf("Renamed %s -> %s\n", ui.RenderWarn(oldID), ui.RenderAccent(newID))
|
|
|
|
commandDidWrite.Store(true)
|
|
|
|
return nil
|
|
}
|
|
|
|
// updateReferencesInAllIssues updates text references to the old ID in all issues
|
|
func updateReferencesInAllIssues(ctx context.Context, store storage.DoltStorage, oldID, newID, actor string) error {
|
|
// Get all issues
|
|
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to list issues: %w", err)
|
|
}
|
|
|
|
// Pattern to match the old ID as a word boundary
|
|
oldPattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(oldID) + `\b`)
|
|
|
|
for _, issue := range issues {
|
|
if issue.ID == newID {
|
|
continue // Skip the renamed issue itself
|
|
}
|
|
|
|
updated := false
|
|
updates := make(map[string]interface{})
|
|
|
|
// Check and update each text field
|
|
if oldPattern.MatchString(issue.Title) {
|
|
updates["title"] = oldPattern.ReplaceAllString(issue.Title, newID)
|
|
updated = true
|
|
}
|
|
if oldPattern.MatchString(issue.Description) {
|
|
updates["description"] = oldPattern.ReplaceAllString(issue.Description, newID)
|
|
updated = true
|
|
}
|
|
if oldPattern.MatchString(issue.Design) {
|
|
updates["design"] = oldPattern.ReplaceAllString(issue.Design, newID)
|
|
updated = true
|
|
}
|
|
if oldPattern.MatchString(issue.Notes) {
|
|
updates["notes"] = oldPattern.ReplaceAllString(issue.Notes, newID)
|
|
updated = true
|
|
}
|
|
if oldPattern.MatchString(issue.AcceptanceCriteria) {
|
|
updates["acceptance_criteria"] = oldPattern.ReplaceAllString(issue.AcceptanceCriteria, newID)
|
|
updated = true
|
|
}
|
|
|
|
if updated {
|
|
if err := store.UpdateIssue(ctx, issue.ID, updates, actor); err != nil {
|
|
return fmt.Errorf("failed to update references in %s: %w", issue.ID, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// beadGateRenameStore is the part of the store a rename writes through.
|
|
type beadGateRenameStore interface {
|
|
UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error
|
|
UpdateIssueID(ctx context.Context, oldID, newID string, issue *types.Issue, actor string) error
|
|
}
|
|
|
|
// beadGatesByTarget indexes the bead gates in issues by the ID of the bead
|
|
// each one waits on (see beadGateTargetID).
|
|
func beadGatesByTarget(issues []*types.Issue) map[string][]*types.Issue {
|
|
gates := make(map[string][]*types.Issue)
|
|
for _, issue := range issues {
|
|
if issue.IssueType != types.TypeGate || issue.AwaitType != "bead" {
|
|
continue
|
|
}
|
|
if targetID, pendingReason := beadGateTargetID(issue.AwaitID); pendingReason == "" {
|
|
gates[targetID] = append(gates[targetID], issue)
|
|
}
|
|
}
|
|
return gates
|
|
}
|
|
|
|
// beadGateMove is one bead gate following its bead to a new ID.
|
|
type beadGateMove struct {
|
|
gateID string
|
|
fromID string // await_id before the rename
|
|
toID string // await_id after it; a <rig>: prefix is kept
|
|
seen bool // the gate records a sighting of fromID
|
|
staleSeen bool // the gate records a sighting of toID, left from an earlier await_id
|
|
}
|
|
|
|
// planBeadGateMoves lists the moves of gates, which wait on oldID, for its
|
|
// rename to newID.
|
|
func planBeadGateMoves(gates []*types.Issue, oldID, newID string) []beadGateMove {
|
|
moves := make([]beadGateMove, 0, len(gates))
|
|
for _, gate := range gates {
|
|
toID := strings.TrimSuffix(gate.AwaitID, oldID) + newID
|
|
moves = append(moves, beadGateMove{
|
|
gateID: gate.ID,
|
|
fromID: gate.AwaitID,
|
|
toID: toID,
|
|
seen: beadGateTargetSeen(gate),
|
|
staleSeen: beadGateSeenID(gate) == toID,
|
|
})
|
|
}
|
|
return moves
|
|
}
|
|
|
|
// renameIssueKeepingBeadGates renames issue to newID and points gates, the
|
|
// bead gates waiting on it, at the new ID. bd gate check resolves a gate whose
|
|
// awaited bead is missing once await_seen records a sighting of that same
|
|
// await_id, and UpdateIssueID commits on its own, so the writes are ordered
|
|
// to leave no state in between that resolves a gate:
|
|
//
|
|
// 1. Each gate's await_id moves to the new ID while its sighting still names
|
|
// the old one, so until the bead has the new ID the gate reads as never
|
|
// seen and stays pending. A sighting that already names the new ID would
|
|
// match early, so it is dropped in the same write.
|
|
// 2. The issue is renamed. UpdateIssueID writes neither await_id nor
|
|
// metadata, so the moves survive it, a gate's own rename included.
|
|
// 3. Each sighting is recorded again under the new ID. Losing one costs only
|
|
// the sighting, which the next check records again while the bead exists,
|
|
// so a failure here is a warning.
|
|
//
|
|
// If step 1 or 2 fails, the gates are moved back and the error is returned. A
|
|
// failed write may still have landed (a lost commit response), so a gate
|
|
// moved back loses its sighting too: it stays pending until a check sees the
|
|
// bead again. A gate that cannot be moved back is left on the new ID without a
|
|
// sighting of it, which also stays pending.
|
|
func renameIssueKeepingBeadGates(ctx context.Context, st beadGateRenameStore, issue *types.Issue, newID string, gates []*types.Issue, actorName string) error {
|
|
oldID := issue.ID
|
|
moves := planBeadGateMoves(gates, oldID, newID)
|
|
for i, m := range moves {
|
|
if err := st.UpdateIssue(ctx, m.gateID, beadGateRetargetUpdate(m.toID, m.staleSeen), actorName); err != nil {
|
|
err = fmt.Errorf("failed to point gate %s at %s: %w", m.gateID, m.toID, err)
|
|
return errors.Join(err, moveBeadGatesBack(ctx, st, moves[:i+1], actorName))
|
|
}
|
|
}
|
|
|
|
issue.ID = newID
|
|
if err := st.UpdateIssueID(ctx, oldID, newID, issue, actorName); err != nil {
|
|
issue.ID = oldID
|
|
return errors.Join(err, moveBeadGatesBack(ctx, st, moves, actorName))
|
|
}
|
|
|
|
for _, m := range moves {
|
|
if !m.seen {
|
|
continue
|
|
}
|
|
gateID := m.gateID
|
|
if gateID == oldID {
|
|
gateID = newID // the gate waits on itself
|
|
}
|
|
if err := st.UpdateIssue(ctx, gateID, beadGateSeenUpdate(m.toID), actorName); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: gate %s: could not move its sighting of %s to %s: %v\n", gateID, m.fromID, m.toID, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// moveBeadGatesBack points each moved gate at its old await_id again and
|
|
// drops its sighting (see renameIssueKeepingBeadGates).
|
|
func moveBeadGatesBack(ctx context.Context, st beadGateRenameStore, moves []beadGateMove, actorName string) error {
|
|
var errs []error
|
|
for _, m := range moves {
|
|
if err := st.UpdateIssue(ctx, m.gateID, beadGateRetargetUpdate(m.fromID, true), actorName); err != nil {
|
|
errs = append(errs, fmt.Errorf("failed to point gate %s back at %s: %w", m.gateID, m.fromID, err))
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|