diff --git a/beads.go b/beads.go index 3f26ec6ee..109367731 100644 --- a/beads.go +++ b/beads.go @@ -84,6 +84,12 @@ type UpdateIssueOptions = storage.UpdateIssueOptions // name it without importing internal/storage. type CommentPageCursor = storage.CommentPageCursor +// ErrUnsupported reports that an operation is unavailable for a storage +// backend — for example Storage.IssueLifecycle on a backend that cannot serve +// guarded issue mutations. Exported so consumers can match it with errors.As +// without importing internal/storage. +type ErrUnsupported = storage.ErrUnsupported + // RemoteStore provides dolt remote management and replication operations. // Use type assertion on a Storage value to access these methods: // diff --git a/cmd/bd/close.go b/cmd/bd/close.go index 35acbaad3..d361a6b17 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -17,6 +17,7 @@ import ( "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/validation" + "github.com/steveyegge/beads/issueops" ) var closeCmd = &cobra.Command{ @@ -81,6 +82,10 @@ the flags appear in the command line.`, } ctx := rootCtx + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } if continueFlag && len(args) > 1 { return HandleErrorRespectJSON("--continue only works when closing a single issue") @@ -145,11 +150,18 @@ the flags appear in the command line.`, } } - // Delegate the is_blocked guard to the engine (GH#962). CloseIssueChecked - // runs the guard and the close in ONE transaction, so there is no - // read-then-write TOCTOU window between the check and the close. --force - // bypasses the guard; ExpectedVersion is unused on this path. - res, err := activeStore.CloseIssueChecked(ctx, id, actor, storage.CloseIssueOptions{ + // Delegate the is_blocked guard to the engine (GH#962). The close + // operation runs the guard and the close in ONE transaction, so there is + // no read-then-write TOCTOU window between the check and the close. + // --force bypasses the guard; ExpectedVersion is unused on this path. + ops, err := writeOps(activeStore) + if err != nil { + fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err) + continue + } + res, err := ops.Close(opsCtx, issueops.CloseRequest{ + Actor: actor, + IssueID: id, Reason: reason, Session: session, Force: force, @@ -164,7 +176,7 @@ the flags appear in the command line.`, } continue } - if res.Unchanged { + if !res.Changed { // Already closed: an idempotent no-op on the step's stored state. The // old CloseIssue path also returned nil here and still reported the // (already-closed) issue, so keep OUTPUT parity via the shared display @@ -217,9 +229,15 @@ the flags appear in the command line.`, firstSettledID = id } - // Re-fetch for display. A real close and an idempotent no-op both report - // the closed issue here, matching the historical output shape. - closedIssue, _ := activeStore.GetIssue(ctx, id) + // The operation's own post-state snapshot is what gets reported. A + // real close and an idempotent no-op both report the closed issue + // here, matching the historical output shape. Dependency records are + // dropped from it because `bd close` has never printed them: the + // re-read this replaced did not hydrate them either. + closedIssue := res.Issue + if closedIssue != nil { + closedIssue.Dependencies = nil + } if jsonOutput { if closedIssue != nil { diff --git a/cmd/bd/close_embedded_test.go b/cmd/bd/close_embedded_test.go index 901991247..985eb9944 100644 --- a/cmd/bd/close_embedded_test.go +++ b/cmd/bd/close_embedded_test.go @@ -56,7 +56,8 @@ func bdDepAdd(t *testing.T, bd, dir string, args ...string) { } } -// querySessionSQL queries closed_by_session via raw SQL since it's not in IssueSelectColumns. +// querySessionSQL queries closed_by_session via raw SQL. IssueSelectColumns +// selects and hydrates the column too; this reads the stored row directly. func querySessionSQL(t *testing.T, beadsDir, id string) string { t.Helper() dataDir := filepath.Join(beadsDir, "embeddeddolt") diff --git a/cmd/bd/create.go b/cmd/bd/create.go index e1b6367cb..261b3a489 100644 --- a/cmd/bd/create.go +++ b/cmd/bd/create.go @@ -24,6 +24,7 @@ import ( "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/validation" + "github.com/steveyegge/beads/issueops" ) // validateCreateArgs runs as cobra's Args validation, which executes before @@ -551,6 +552,15 @@ var createCmd = &cobra.Command{ ctx := createCtx + // Resolve partial --deps targets the way `bd dep add` does, so a bare + // slug becomes a qualified id rather than a dangling edge, and an + // unknown target fails closed here instead of reaching the write. + resolvedDepSpecs, resolveErr := resolveDepSpecTargets(ctx, store, depSpecs) + if resolveErr != nil { + return HandleErrorRespectJSON("%v", resolveErr) + } + depSpecs = resolvedDepSpecs + // If a discovered-from dependency is present, inherit source_repo // from the referenced parent issue. Reuse the already-parsed specs // (not the raw --deps strings) so this can't drift from parseDepSpec's @@ -563,20 +573,52 @@ var createCmd = &cobra.Command{ // If error getting parent or parent has no source_repo, continue with default } - edges := createDepEdges{parentID: parentID, specs: depSpecs, waitsFor: waitsForSpec} - if err := createIssueWithDeps(ctx, store, issue, actor, edges); err != nil { + ops, err := writeOps(store) + if err != nil { return HandleErrorRespectJSON("%v", err) } + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + // Label inheritance stays CLI-side (mergeCreateLabels above) because the + // dry-run preview needs it too; asking the facade to inherit as well + // would append the parent's labels a second time. + result, err := ops.Create(opsCtx, issueops.CreateRequest{ + Actor: actor, + Issue: issue, + ParentID: parentID, + Dependencies: createDependencyRequests(depSpecs), + WaitsFor: waitsForRequest(waitsForSpec), + ForceIDPrefix: forceCreate, + }) + if err != nil { + // RULING R1: an occupied --id is a refusal, not a silent full-row + // upsert reported as success. + if errors.Is(err, storage.ErrAlreadyExists) && explicitID != "" { + return HandleErrorRespectJSON("%s already exists; use bd update, or bd import for upsert semantics", explicitID) + } + return HandleErrorRespectJSON("%v", err) + } + // Every post-write read comes from the facade's result snapshot, never + // from the local struct: the facade clones its request, so the local + // struct still has no ID for an auto-minted create and no persisted + // timestamps. Dependencies and comments are dropped because `bd create` + // has never printed them. + created := result.Issue + created.Dependencies = nil + created.Comments = nil + edges := createDepEdges{parentID: parentID, specs: depSpecs, waitsFor: waitsForSpec} if edges.empty() { // Bare create: preserve the embedded-mode follow-up Dolt commit. // The deps path commits inside its transaction instead. - shouldCommit, err := shouldCommitCreatePostWrites(issue, false) + shouldCommit, err := shouldCommitCreatePostWrites(created, false) if err != nil { return HandleError("dolt auto-commit failed: %v", err) } if shouldCommit { - commitMsg := fmt.Sprintf("bd: create %s", issue.ID) + commitMsg := fmt.Sprintf("bd: create %s", created.ID) if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) { WarnError("failed to commit: %v", err) } @@ -586,7 +628,7 @@ var createCmd = &cobra.Command{ if repoPath != "." && targetStore != nil { if err := commitPendingIfEmbedded(ctx, targetStore, actor, doltAutoCommitParams{ Command: "create", - IssueIDs: []string{issue.ID}, + IssueIDs: []string{created.ID}, }); err != nil { debug.Logf("warning: failed to commit routed repo: %v", err) } @@ -599,20 +641,20 @@ var createCmd = &cobra.Command{ } if jsonOutput { - if err := outputJSON(issue); err != nil { + if err := outputJSON(created); err != nil { return err } } else if silent { - fmt.Println(issue.ID) + fmt.Println(created.ID) } else { - debug.PrintNormal("%s Created issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(issue.ID, issue.Title)) - debug.PrintNormal(" Priority: P%d\n", issue.Priority) - debug.PrintNormal(" Status: %s\n", issue.Status) + debug.PrintNormal("%s Created issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(created.ID, created.Title)) + debug.PrintNormal(" Priority: P%d\n", created.Priority) + debug.PrintNormal(" Status: %s\n", created.Status) maybeShowTip(store) } - SetLastTouchedID(issue.ID) + SetLastTouchedID(created.ID) return nil }, } @@ -783,17 +825,7 @@ func renderCreateDryRunPreview(issue *types.Issue, labels, deps []string) { } func shouldCommitCreatePostWrites(_ *types.Issue, _ bool) (bool, error) { - if isEmbeddedMode() { - if strings.TrimSpace(doltAutoCommit) == "" { - return true, nil - } - mode, err := getDoltAutoCommitMode() - if err != nil { - return false, err - } - return mode == doltAutoCommitOn, nil - } - return false, nil + return embeddedWritesCommitNow() } func createDepsAcceptedTypeList() string { diff --git a/cmd/bd/create_deps.go b/cmd/bd/create_deps.go index 992fb3cb9..222449193 100644 --- a/cmd/bd/create_deps.go +++ b/cmd/bd/create_deps.go @@ -10,8 +10,38 @@ import ( "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/utils" + "github.com/steveyegge/beads/issueops" ) +// createDependencyRequests translates parsed --deps specs into the create +// request's edge list. The specs are already alias-normalized and deduped by +// parseDepSpecs; the facade rejects the exact duplicates that dedupe removes. +func createDependencyRequests(specs []domain.DependencySpec) []issueops.CreateDependency { + if len(specs) == 0 { + return nil + } + requests := make([]issueops.CreateDependency, 0, len(specs)) + for _, spec := range specs { + requests = append(requests, issueops.CreateDependency{ + TargetID: spec.TargetID, + Type: spec.Type, + Reverse: spec.SwapDirection, + Metadata: spec.Metadata, + ThreadID: spec.ThreadID, + }) + } + return requests +} + +// waitsForRequest translates the parsed --waits-for spec into the create +// request's spawner gate. +func waitsForRequest(spec *domain.WaitsForSpec) *issueops.WaitsFor { + if spec == nil { + return nil + } + return &issueops.WaitsFor{SpawnerID: spec.SpawnerID, Gate: spec.Gate} +} + func parseDepSpecs(deps []string) ([]domain.DependencySpec, error) { // deps arrives already comma-split: cobra's StringSlice flag CSV-decodes // each --deps value, so re-splitting on "," here would double-decode a diff --git a/cmd/bd/dolt_autocommit.go b/cmd/bd/dolt_autocommit.go index e16b42725..e51d4da15 100644 --- a/cmd/bd/dolt_autocommit.go +++ b/cmd/bd/dolt_autocommit.go @@ -46,6 +46,43 @@ func transactHonoringAutoCommit(ctx context.Context, s storage.DoltStorage, comm return err } +// embeddedWritesCommitNow reports whether an embedded-mode CLI write should +// create its Dolt version commit now. Batch and off defer it to an explicit +// commit point (bd dolt commit); an unset value is the embedded default, which +// PersistentPreRun resolves to "on". Server mode is never the CLI's commit to +// make — the storage layer versions those writes itself. +func embeddedWritesCommitNow() (bool, error) { + if !isEmbeddedMode() { + return false, nil + } + if strings.TrimSpace(doltAutoCommit) == "" { + return true, nil + } + mode, err := getDoltAutoCommitMode() + if err != nil { + return false, err + } + return mode == doltAutoCommitOn, nil +} + +// issueOpsContext applies command auto-commit policy to the context a write verb +// hands the issue-operations facade. The facade creates its Dolt version commit +// inside the storage layer, so batch mode cannot blank a commit message the way +// transactHonoringAutoCommit does — it has to say so on the context instead. +func issueOpsContext(ctx context.Context) (context.Context, error) { + if !isEmbeddedMode() { + return ctx, nil + } + commitNow, err := embeddedWritesCommitNow() + if err != nil { + return nil, err + } + if commitNow { + return ctx, nil + } + return issueops.WithDeferredVersionCommit(ctx), nil +} + type doltAutoCommitParams struct { // Command is the top-level bd command name (e.g., "create", "update"). Command string diff --git a/cmd/bd/duplicate.go b/cmd/bd/duplicate.go index 1210b110e..6bf37bc5f 100644 --- a/cmd/bd/duplicate.go +++ b/cmd/bd/duplicate.go @@ -107,12 +107,9 @@ func runDuplicate(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to add duplicate link: %w", err) } - // Close the duplicate issue - closedStatus := string(types.StatusClosed) - updates := map[string]interface{}{ - "status": closedStatus, - } - if err := store.UpdateIssue(ctx, duplicateID, updates, actor); err != nil { + // Close the duplicate issue through the lifecycle operation so it records + // the complete closure state. + if err := store.CloseIssue(ctx, duplicateID, "", actor, ""); err != nil { return fmt.Errorf("failed to close duplicate: %w", err) } @@ -180,12 +177,9 @@ func runSupersede(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to add supersede link: %w", err) } - // Close the superseded issue - closedStatus := string(types.StatusClosed) - updates := map[string]interface{}{ - "status": closedStatus, - } - if err := store.UpdateIssue(ctx, oldID, updates, actor); err != nil { + // Close the superseded issue through the lifecycle operation so it records + // the complete closure state. + if err := store.CloseIssue(ctx, oldID, "", actor, ""); err != nil { return fmt.Errorf("failed to close superseded issue: %w", err) } diff --git a/cmd/bd/duplicate_embedded_test.go b/cmd/bd/duplicate_embedded_test.go index 15802e97e..5467c0a5d 100644 --- a/cmd/bd/duplicate_embedded_test.go +++ b/cmd/bd/duplicate_embedded_test.go @@ -75,6 +75,9 @@ func TestEmbeddedDuplicate(t *testing.T) { if issue.Status != "closed" { t.Errorf("expected status=closed, got %s", issue.Status) } + if issue.ClosedAt == nil { + t.Error("expected duplicate close to set closed_at") + } }) // ===== Creates dependency link ===== diff --git a/cmd/bd/issueops_adapter.go b/cmd/bd/issueops_adapter.go new file mode 100644 index 000000000..7baddb536 --- /dev/null +++ b/cmd/bd/issueops_adapter.go @@ -0,0 +1,27 @@ +package main + +import ( + "github.com/steveyegge/beads" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/issueops" +) + +// newIssueOperations asks a store for its guarded issue-lifecycle surface. +// It is a variable purely as a test seam: the write-verb parity tests +// substitute a counting facade so "which operations did this command perform" +// stays observable. Production always calls the store's own accessor. +var newIssueOperations = func(st beads.Storage) (issueops.Lifecycle, error) { + return st.IssueLifecycle() +} + +// writeOps returns the issue-lifecycle surface for st, the store a write verb +// is actually writing to. +// +// Callers build it per write site — the global store, a RoutedResult's store, +// or a --repo target — rather than once per command, because each store hands +// back a lifecycle carrying its own decorator stack. Building it over the +// store that owns the issue is what keeps a routed write hookless and a local +// write hooked, exactly as the direct store calls did. +func writeOps(st storage.DoltStorage) (issueops.Lifecycle, error) { + return newIssueOperations(st) +} diff --git a/cmd/bd/main_test.go b/cmd/bd/main_test.go index f53dd51bb..63f317681 100644 --- a/cmd/bd/main_test.go +++ b/cmd/bd/main_test.go @@ -18,8 +18,8 @@ import ( "github.com/steveyegge/beads/internal/types" ) -// bd-206: Test updating open issue to closed preserves closed_at -func TestImportOpenToClosedTransition(t *testing.T) { +// TestCloseIssueSetsClosedAt verifies the dedicated close operation owns its lifecycle metadata. +func TestCloseIssueSetsClosedAt(t *testing.T) { tmpDir := t.TempDir() dbPath := filepath.Join(tmpDir, "test.db") @@ -45,13 +45,9 @@ func TestImportOpenToClosedTransition(t *testing.T) { t.Fatalf("Failed to create open issue: %v", err) } - // Step 2: Update via UpdateIssue with closed status (closed_at managed automatically) - updates := map[string]interface{}{ - "status": types.StatusClosed, - } - - if err := testStore.UpdateIssue(ctx, "bd-transition-1", updates, "test"); err != nil { - t.Fatalf("Update failed: %v", err) + // Step 2: Lifecycle transitions use the dedicated close operation. + if err := testStore.CloseIssue(ctx, "bd-transition-1", "", "test", ""); err != nil { + t.Fatalf("CloseIssue failed: %v", err) } // Step 3: Verify the issue is now closed with correct closed_at @@ -69,8 +65,8 @@ func TestImportOpenToClosedTransition(t *testing.T) { } } -// bd-206: Test updating closed issue to open clears closed_at -func TestImportClosedToOpenTransition(t *testing.T) { +// TestReopenIssueClearsClosedAt verifies the dedicated reopen operation clears lifecycle metadata. +func TestReopenIssueClearsClosedAt(t *testing.T) { tmpDir := t.TempDir() dbPath := filepath.Join(tmpDir, "test.db") @@ -97,13 +93,9 @@ func TestImportClosedToOpenTransition(t *testing.T) { t.Fatalf("Failed to create closed issue: %v", err) } - // Step 2: Update via UpdateIssue with open status (closed_at managed automatically) - updates := map[string]interface{}{ - "status": types.StatusOpen, - } - - if err := testStore.UpdateIssue(ctx, "bd-transition-2", updates, "test"); err != nil { - t.Fatalf("Update failed: %v", err) + // Step 2: Lifecycle transitions use the dedicated reopen operation. + if err := testStore.ReopenIssue(ctx, "bd-transition-2", "", "test"); err != nil { + t.Fatalf("ReopenIssue failed: %v", err) } // Step 3: Verify the issue is now open with null closed_at diff --git a/cmd/bd/messaging_test.go b/cmd/bd/messaging_test.go index e75be981d..50715c1e0 100644 --- a/cmd/bd/messaging_test.go +++ b/cmd/bd/messaging_test.go @@ -143,7 +143,7 @@ func TestMessagingSuite(t *testing.T) { t.Fatalf("AddDep(duplicates): %v", err) } // Close the duplicate - if err := testStore.UpdateIssue(ctx, dup.ID, map[string]interface{}{"status": types.StatusClosed}, "test"); err != nil { + if err := testStore.CloseIssue(ctx, dup.ID, "duplicate", "test", ""); err != nil { t.Fatalf("Close dup: %v", err) } @@ -174,10 +174,8 @@ func TestMessagingSuite(t *testing.T) { } // Close (ack) - if err := testStore.UpdateIssue(ctx, lifecycleMsg.ID, map[string]interface{}{ - "status": types.StatusClosed, - }, "test"); err != nil { - t.Fatalf("UpdateIssue (close): %v", err) + if err := testStore.CloseIssue(ctx, lifecycleMsg.ID, "acknowledged", "test", ""); err != nil { + t.Fatalf("CloseIssue (ack): %v", err) } acked, err := testStore.GetIssue(ctx, lifecycleMsg.ID) if err != nil { diff --git a/cmd/bd/reopen.go b/cmd/bd/reopen.go index 5da410c9f..59453e459 100644 --- a/cmd/bd/reopen.go +++ b/cmd/bd/reopen.go @@ -9,6 +9,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" ) var reopenCmd = &cobra.Command{ @@ -36,6 +37,10 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. reason, _ := cmd.Flags().GetString("reason") ctx := rootCtx + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } reopenedIssues := []*types.Issue{} hasError := false @@ -61,17 +66,41 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. result.Close() continue } - if err := issueStore.ReopenIssue(ctx, fullID, reason, actor); err != nil { + ops, err := writeOps(issueStore) + if err != nil { fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err) hasError = true result.Close() continue } + reopened, err := ops.Reopen(opsCtx, issueops.ReopenRequest{ + Actor: actor, + IssueID: fullID, + Reason: reason, + }) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err) + hasError = true + result.Close() + continue + } + if !reopened.Changed { + // RULING R4: only literal closed and configured done statuses + // reopen. Anything else was never closed, so there is nothing to + // report as reopened, nothing to commit, and no hook to fire — + // the same "nothing to do" shape as the already-open skip above. + fmt.Fprintf(os.Stderr, "%s is not closed (status: %s); nothing to do\n", fullID, reopenStatusOf(reopened.Issue, issue)) + result.Close() + continue + } mutatedStores[issueStore] = append(mutatedStores[issueStore], fullID) pendingCloseResults = append(pendingCloseResults, result) if jsonOutput { - updated, _ := issueStore.GetIssue(ctx, fullID) - if updated != nil { + // The operation's own post-state snapshot replaces the re-read. + // Dependency records are dropped because `bd reopen` has never + // printed them. + if updated := reopened.Issue; updated != nil { + updated.Dependencies = nil reopenedIssues = append(reopenedIssues, updated) } } else { @@ -111,6 +140,18 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. }, } +// reopenStatusOf reports the status a no-op reopen left in place, preferring +// the operation's post-state snapshot over the pre-read it was based on. +func reopenStatusOf(post, pre *types.Issue) types.Status { + if post != nil { + return post.Status + } + if pre != nil { + return pre.Status + } + return "" +} + func init() { reopenCmd.Flags().StringP("reason", "r", "", "Reason for reopening") reopenCmd.ValidArgsFunction = issueIDCompletion diff --git a/cmd/bd/reopen_test.go b/cmd/bd/reopen_test.go index 72856570b..696f73d52 100644 --- a/cmd/bd/reopen_test.go +++ b/cmd/bd/reopen_test.go @@ -38,10 +38,9 @@ func (h *reopenTestHelper) closeIssue(issueID, reason string) { } func (h *reopenTestHelper) reopenIssue(issueID string) { - updates := map[string]interface{}{ - "status": string(types.StatusOpen), - } - if err := h.s.UpdateIssue(h.ctx, issueID, updates, "test-user"); err != nil { + // Reopen through the lifecycle operation so the fixture carries the full + // closure teardown, mirroring closeIssue above. + if err := h.s.ReopenIssue(h.ctx, issueID, "", "test-user"); err != nil { h.t.Fatalf("Failed to reopen issue: %v", err) } } diff --git a/cmd/bd/show_unit_helpers.go b/cmd/bd/show_unit_helpers.go index 2716dbd17..b2ce6824b 100644 --- a/cmd/bd/show_unit_helpers.go +++ b/cmd/bd/show_unit_helpers.go @@ -74,39 +74,3 @@ func uowClaimPoolAliases(ctx context.Context, uw uow.UnitOfWork) func() []string return issueops.ParseClaimPools(raw) } } - -func applyLabelUpdates(ctx context.Context, st storage.DoltStorage, issueID, actor string, setLabels, addLabels, removeLabels []string) error { - // Set labels (replaces all existing labels) - if len(setLabels) > 0 { - currentLabels, err := st.GetLabels(ctx, issueID) - if err != nil { - return err - } - for _, label := range currentLabels { - if err := st.RemoveLabel(ctx, issueID, label, actor); err != nil { - return err - } - } - for _, label := range setLabels { - if err := st.AddLabel(ctx, issueID, label, actor); err != nil { - return err - } - } - } - - // Add labels - for _, label := range addLabels { - if err := st.AddLabel(ctx, issueID, label, actor); err != nil { - return err - } - } - - // Remove labels - for _, label := range removeLabels { - if err := st.RemoveLabel(ctx, issueID, label, actor); err != nil { - return err - } - } - - return nil -} diff --git a/cmd/bd/show_unit_helpers_test.go b/cmd/bd/show_unit_helpers_test.go index ba7c5b938..e8d25e1d3 100644 --- a/cmd/bd/show_unit_helpers_test.go +++ b/cmd/bd/show_unit_helpers_test.go @@ -56,62 +56,6 @@ func TestValidateIssueClosable(t *testing.T) { } } -func TestApplyLabelUpdates_SetAddRemove(t *testing.T) { - ctx := context.Background() - st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test") - - issue := &types.Issue{Title: "x", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} - if err := st.CreateIssue(ctx, issue, "tester"); err != nil { - t.Fatalf("CreateIssue: %v", err) - } - - _ = st.AddLabel(ctx, issue.ID, "old1", "tester") - _ = st.AddLabel(ctx, issue.ID, "old2", "tester") - - if err := applyLabelUpdates(ctx, st, issue.ID, "tester", []string{"a", "b"}, []string{"b", "c"}, []string{"a"}); err != nil { - t.Fatalf("applyLabelUpdates: %v", err) - } - labels, _ := st.GetLabels(ctx, issue.ID) - if len(labels) != 2 { - t.Fatalf("expected 2 labels, got %v", labels) - } - // Order is not guaranteed. - foundB := false - foundC := false - for _, l := range labels { - if l == "b" { - foundB = true - } - if l == "c" { - foundC = true - } - if l == "old1" || l == "old2" || l == "a" { - t.Fatalf("unexpected label %q in %v", l, labels) - } - } - if !foundB || !foundC { - t.Fatalf("expected labels b and c, got %v", labels) - } -} - -func TestApplyLabelUpdates_AddRemoveOnly(t *testing.T) { - ctx := context.Background() - st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test") - issue := &types.Issue{Title: "x", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} - if err := st.CreateIssue(ctx, issue, "tester"); err != nil { - t.Fatalf("CreateIssue: %v", err) - } - - _ = st.AddLabel(ctx, issue.ID, "a", "tester") - if err := applyLabelUpdates(ctx, st, issue.ID, "tester", nil, []string{"b"}, []string{"a"}); err != nil { - t.Fatalf("applyLabelUpdates: %v", err) - } - labels, _ := st.GetLabels(ctx, issue.ID) - if len(labels) != 1 || labels[0] != "b" { - t.Fatalf("expected [b], got %v", labels) - } -} - func TestFindRepliesToAndReplies_WorksWithDoltStorage(t *testing.T) { ctx := context.Background() st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test") diff --git a/cmd/bd/supersede_embedded_test.go b/cmd/bd/supersede_embedded_test.go index bacccee23..f05778227 100644 --- a/cmd/bd/supersede_embedded_test.go +++ b/cmd/bd/supersede_embedded_test.go @@ -75,6 +75,9 @@ func TestEmbeddedSupersede(t *testing.T) { if issue.Status != "closed" { t.Errorf("expected status=closed, got %s", issue.Status) } + if issue.ClosedAt == nil { + t.Error("expected supersede close to set closed_at") + } }) // ===== Creates supersedes link ===== diff --git a/cmd/bd/update.go b/cmd/bd/update.go index ce65ebf12..bcc786873 100644 --- a/cmd/bd/update.go +++ b/cmd/bd/update.go @@ -13,12 +13,13 @@ import ( "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/issueops" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/timeparsing" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" "github.com/steveyegge/beads/internal/validation" + "github.com/steveyegge/beads/issueops" ) var updateCmd = &cobra.Command{ @@ -145,7 +146,7 @@ pointless).`, } if cmd.Flags().Changed("append-notes") { appendNotes, _ := cmd.Flags().GetString("append-notes") - updates[issueops.OpAppendNotes] = appendNotes + updates[storageissueops.OpAppendNotes] = appendNotes } if cmd.Flags().Changed("acceptance") || cmd.Flags().Changed("acceptance-criteria") { var acceptanceCriteria string @@ -302,7 +303,7 @@ pointless).`, // Passed as a merge OPERATION, not a pre-merged value: the storage // layer re-reads and merges inside the mutation transaction so a // concurrent writer's keys survive (lost-update fix). - updates[issueops.OpMergeMetadata] = json.RawMessage(metadataJSON) + updates[storageissueops.OpMergeMetadata] = json.RawMessage(metadataJSON) } // Incremental metadata edits (GH#1406) @@ -312,10 +313,10 @@ pointless).`, return HandleErrorRespectJSON("cannot combine --metadata with --set-metadata or --unset-metadata") } if len(setMetadataFlags) > 0 { - updates[issueops.OpSetMetadata] = setMetadataFlags + updates[storageissueops.OpSetMetadata] = setMetadataFlags } if len(unsetMetadataFlags) > 0 { - updates[issueops.OpUnsetMetadata] = unsetMetadataFlags + updates[storageissueops.OpUnsetMetadata] = unsetMetadataFlags } // Get claim flag @@ -337,8 +338,24 @@ pointless).`, if err != nil { return err } + var expectedStatus *issueops.Status + if ifStatus != nil { + expected := issueops.Status(*ifStatus) + expectedStatus = &expected + } + // One typed patch for the whole batch. The flag-derived map is still + // the source (the guard rules and the notes-overwrite warning read it); + // this reshapes it once instead of once per issue. + basePatch, err := buildUpdatePatch(updates) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } ctx := rootCtx + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } updatedIssues := []*types.Issue{} var firstUpdatedID string // Track first successful update for last-touched @@ -424,166 +441,73 @@ pointless).`, } } - // Handle claim operation atomically using compare-and-swap semantics - if claimFlag { - if err := issueStore.ClaimIssue(ctx, result.ResolvedID, actor); err != nil { - fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err) - recordFailure(id, fmt.Sprintf("claiming issue: %v", err)) - closeIfUnmutated(result) - continue - } - trackMutation(result) - } - - // Apply regular field updates if any. Metadata edits (--metadata, - // --set-metadata, --unset-metadata) and --append-notes pass through - // as merge OPERATIONS: the storage layer resolves them against the - // row re-read inside the mutation transaction. Merging here against - // the `issue` snapshot (read in an earlier transaction) silently - // erased concurrent writers' keys — both processes exited 0, one - // process's committed write vanished. - regularUpdates := make(map[string]interface{}) - for k, v := range updates { - if k != "add_labels" && k != "remove_labels" && k != "set_labels" && k != "parent" { - regularUpdates[k] = v - } - } + // One atomic operation carries the claim, every field edit, the + // label edits, the metadata edits and the reparent. Metadata edits + // (--metadata, --set-metadata, --unset-metadata) and --append-notes + // still resolve against the row re-read inside the mutation + // transaction: merging against the `issue` snapshot (read in an + // earlier transaction) silently erased concurrent writers' keys — + // both processes exited 0, one process's committed write vanished. + patch := basePatch // GH#3233: --defer="" restores ready visibility only if the issue // was actually deferred. Other statuses (blocked, in_progress, …) // shouldn't be clobbered just because defer_until was stale. if clearDeferStatus && issue.Status == types.StatusDeferred { - regularUpdates["status"] = string(types.StatusOpen) + patch.Status = issueops.Field[issueops.Status]{Set: true, Value: types.StatusOpen} } notesOverwritten := replacesExistingNotes(issue.Notes, updates) - if len(regularUpdates) > 0 { - // With guards present, route through the checked (CAS) path: a - // stale assignee/status refuses atomically with a typed - // mismatch error and MUST surface as a non-zero exit — never - // collapse it to success (finding #10). - var updateErr error - if ifAssignee != nil || ifStatus != nil { - updateErr = issueStore.UpdateIssueChecked(ctx, result.ResolvedID, regularUpdates, actor, - storage.UpdateIssueOptions{ExpectedAssignee: ifAssignee, ExpectedStatus: ifStatus}) - } else { - updateErr = issueStore.UpdateIssue(ctx, result.ResolvedID, regularUpdates, actor) - } - if updateErr != nil { - fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, updateErr) - failures = append(failures, updateIDFailure{ - ID: id, - Error: fmt.Sprintf("updating issue: %v", updateErr), - GuardMismatch: isGuardMismatch(updateErr), - }) - closeIfUnmutated(result) - continue - } - trackMutation(result) - if notesOverwritten { - notesOverwriteWarnings[issueStore] = append(notesOverwriteWarnings[issueStore], id) - } - // Audit log key field changes (survives Dolt GC flatten) - if s, ok := regularUpdates["status"].(string); ok { - audit.LogFieldChange(result.ResolvedID, "status", string(issue.Status), s, actor, "") - } - if a, ok := regularUpdates["assignee"].(string); ok { - audit.LogFieldChange(result.ResolvedID, "assignee", issue.Assignee, a, actor, "") - } - if p, ok := regularUpdates["priority"].(int); ok { - audit.LogFieldChange(result.ResolvedID, "priority", fmt.Sprintf("%d", issue.Priority), fmt.Sprintf("%d", p), actor, "") - } + ops, err := writeOps(issueStore) + if err != nil { + fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err) + recordFailure(id, fmt.Sprintf("updating issue: %v", err)) + closeIfUnmutated(result) + continue + } + // Guards ride the operation itself: a stale assignee/status refuses + // atomically with a typed mismatch error and MUST surface as a + // non-zero exit — never collapse it to success (finding #10). + updateResult, updateErr := ops.Update(opsCtx, issueops.UpdateRequest{ + Actor: actor, + IssueID: result.ResolvedID, + Patch: patch, + Claim: claimFlag, + ForceAssigneeTransfer: forceFlag, + ExpectedAssignee: ifAssignee, + ExpectedStatus: expectedStatus, + }) + if updateErr != nil { + fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, updateErr) + failures = append(failures, updateIDFailure{ + ID: id, + Error: fmt.Sprintf("updating issue: %v", updateErr), + GuardMismatch: isGuardMismatch(updateErr), + }) + closeIfUnmutated(result) + continue + } + updatedIssue := updateResult.Issue + trackMutation(result) + if notesOverwritten { + notesOverwriteWarnings[issueStore] = append(notesOverwriteWarnings[issueStore], id) + } + // Audit log key field changes (survives Dolt GC flatten) + if patch.Status.Set { + audit.LogFieldChange(result.ResolvedID, "status", string(issue.Status), string(patch.Status.Value), actor, "") + } + if patch.Assignee.Set { + audit.LogFieldChange(result.ResolvedID, "assignee", issue.Assignee, patch.Assignee.Value, actor, "") + } + if patch.Priority.Set { + audit.LogFieldChange(result.ResolvedID, "priority", fmt.Sprintf("%d", issue.Priority), fmt.Sprintf("%d", patch.Priority.Value), actor, "") } - // Handle label operations - var setLabels, addLabels, removeLabels []string - if v, ok := updates["set_labels"].([]string); ok { - setLabels = v + // The operation's own post-state snapshot replaces the re-read. + // Dependency records are dropped from it because `bd update` has + // never printed them: GetIssue did not hydrate them either. + if updatedIssue != nil { + updatedIssue.Dependencies = nil } - if v, ok := updates["add_labels"].([]string); ok { - addLabels = v - } - if v, ok := updates["remove_labels"].([]string); ok { - removeLabels = v - } - if len(setLabels) > 0 || len(addLabels) > 0 || len(removeLabels) > 0 { - if err := applyLabelUpdates(ctx, issueStore, result.ResolvedID, actor, setLabels, addLabels, removeLabels); err != nil { - fmt.Fprintf(os.Stderr, "Error updating labels for %s: %v\n", id, err) - recordFailure(id, fmt.Sprintf("updating labels: %v", err)) - closeIfUnmutated(result) - continue - } - trackMutation(result) - } - - // Handle parent reparenting - if newParent, ok := updates["parent"].(string); ok { - // Validate new parent exists (unless empty string to remove parent) - if newParent != "" { - parentIssue, err := issueStore.GetIssue(ctx, newParent) - if err != nil { - fmt.Fprintf(os.Stderr, "Error getting parent %s: %v\n", newParent, err) - recordFailure(id, fmt.Sprintf("getting parent %s: %v", newParent, err)) - closeIfUnmutated(result) - continue - } - if parentIssue == nil { - fmt.Fprintf(os.Stderr, "Error: parent issue %s not found\n", newParent) - recordFailure(id, fmt.Sprintf("parent issue %s not found", newParent)) - closeIfUnmutated(result) - continue - } - } - - // Find and remove existing parent-child dependency - deps, err := issueStore.GetDependencyRecords(ctx, result.ResolvedID) - if err != nil { - fmt.Fprintf(os.Stderr, "Error getting dependencies for %s: %v\n", id, err) - recordFailure(id, fmt.Sprintf("getting dependencies: %v", err)) - closeIfUnmutated(result) - continue - } - oldParentRemoveFailed := false - for _, dep := range deps { - if dep.Type == types.DepParentChild { - if err := issueStore.RemoveDependency(ctx, result.ResolvedID, dep.DependsOnID, actor); err != nil { - // Reparenting removes the old parent edge before adding - // the new one; if removal fails, adding the new edge would - // leave the issue with two parents. Record the failed ID - // and stop so it surfaces in the nonzero-exit report - // instead of being silently counted as a success. - fmt.Fprintf(os.Stderr, "Error removing old parent dependency: %v\n", err) - recordFailure(id, fmt.Sprintf("removing old parent dependency: %v", err)) - oldParentRemoveFailed = true - } else { - trackMutation(result) - } - break - } - } - if oldParentRemoveFailed { - closeIfUnmutated(result) - continue - } - - // Add new parent-child dependency (if not removing parent) - if newParent != "" { - newDep := &types.Dependency{ - IssueID: result.ResolvedID, - DependsOnID: newParent, - Type: types.DepParentChild, - } - if err := issueStore.AddDependency(ctx, newDep, actor); err != nil { - fmt.Fprintf(os.Stderr, "Error adding parent dependency: %v\n", err) - recordFailure(id, fmt.Sprintf("adding parent dependency: %v", err)) - closeIfUnmutated(result) - continue - } - trackMutation(result) - } - } - - // Re-fetch for display - updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID) updateTitle := "" if updatedIssue != nil { updateTitle = updatedIssue.Title @@ -645,6 +569,167 @@ pointless).`, }, } +// setField marks a patch field as supplied, including when the value is a zero +// value the caller meant to write. +func setField[T any](value T) issueops.Field[T] { + return issueops.Field[T]{Set: true, Value: value} +} + +// buildUpdatePatch reshapes the flag-derived update map into the facade's typed +// patch. Every key it handles is a key the flag parsing above wrote, so an +// unrecognized one is a bug in this file rather than user input. +func buildUpdatePatch(updates map[string]interface{}) (issueops.IssuePatch, error) { + var patch issueops.IssuePatch + var wisp, noHistory *bool + for key, value := range updates { + var ok bool + switch key { + case "title": + patch.Title, ok = stringField(value) + case "description": + patch.Description, ok = stringField(value) + case "design": + patch.Design, ok = stringField(value) + case "acceptance_criteria": + patch.AcceptanceCriteria, ok = stringField(value) + case "notes": + patch.Notes, ok = stringField(value) + case storageissueops.OpAppendNotes: + patch.AppendNotes, ok = stringField(value) + case "spec_id": + patch.SpecID, ok = stringField(value) + case "await_id": + patch.AwaitID, ok = stringField(value) + case "closed_by_session": + patch.ClosedBySession, ok = stringField(value) + case "assignee": + patch.Assignee, ok = stringField(value) + case "parent": + patch.ParentID, ok = stringField(value) + case "status": + var status issueops.Field[string] + if status, ok = stringField(value); ok { + patch.Status = setField(issueops.Status(status.Value)) + } + case "issue_type": + var issueType issueops.Field[string] + if issueType, ok = stringField(value); ok { + patch.IssueType = setField(issueops.IssueType(issueType.Value)) + } + case "priority": + var priority int + if priority, ok = value.(int); ok { + patch.Priority = setField(priority) + } + case "estimated_minutes": + var estimate int + if estimate, ok = value.(int); ok { + patch.EstimatedMinutes = setField(&estimate) + } + case "external_ref": + ok = true + if value == nil { + patch.ExternalRef = setField[*string](nil) + } else if ref, isString := value.(string); isString { + patch.ExternalRef = setField(&ref) + } else { + ok = false + } + case "due_at": + patch.DueAt, ok = optionalTimeField(value) + case "defer_until": + patch.DeferUntil, ok = optionalTimeField(value) + case "add_labels": + patch.Labels.Add, ok = value.([]string) + case "remove_labels": + patch.Labels.Remove, ok = value.([]string) + case "set_labels": + var labels []string + if labels, ok = value.([]string); ok { + patch.Labels.Replace = setField(labels) + } + case storageissueops.OpMergeMetadata: + var merge json.RawMessage + if merge, ok = value.(json.RawMessage); ok { + patch.Metadata.Merge = setField(merge) + } + case storageissueops.OpSetMetadata: + var flags []string + if flags, ok = value.([]string); ok { + set, err := parseSetMetadataFlags(flags) + if err != nil { + return issueops.IssuePatch{}, err + } + patch.Metadata.Set = set + } + case storageissueops.OpUnsetMetadata: + patch.Metadata.Unset, ok = value.([]string) + case "wisp": + var flag bool + if flag, ok = value.(bool); ok { + wisp = &flag + } + case "no_history": + var flag bool + if flag, ok = value.(bool); ok { + noHistory = &flag + } + default: + return issueops.IssuePatch{}, fmt.Errorf("unsupported update field %q", key) + } + if !ok { + return issueops.IssuePatch{}, fmt.Errorf("unsupported value %T for update field %q", value, key) + } + } + // --ephemeral/--persistent/--no-history/--history select one complete + // persistence state. The flag parsing already rejects the contradictory + // pairs; the remaining combinations resolve most-specific-first, which + // reproduces the column pairs the old two-boolean write produced. + switch { + case wisp != nil && *wisp: + patch.Persistence = setField(issueops.PersistenceModeEphemeral) + case noHistory != nil && *noHistory: + patch.Persistence = setField(issueops.PersistenceModeNoHistory) + case wisp != nil || noHistory != nil: + patch.Persistence = setField(issueops.PersistenceModePersistent) + } + return patch, nil +} + +func stringField(value any) (issueops.Field[string], bool) { + text, ok := value.(string) + if !ok { + return issueops.Field[string]{}, false + } + return setField(text), true +} + +func optionalTimeField(value any) (issueops.Field[*time.Time], bool) { + if value == nil { + return setField[*time.Time](nil), true + } + at, ok := value.(time.Time) + if !ok { + return issueops.Field[*time.Time]{}, false + } + return setField(&at), true +} + +// parseSetMetadataFlags splits --set-metadata key=value pairs, matching +// storage.ApplyMetadataEdits' parsing so the CLI contract is unchanged. Values +// are always stored as JSON strings (GH#4146). +func parseSetMetadataFlags(flags []string) (map[string]json.RawMessage, error) { + set := make(map[string]json.RawMessage, len(flags)) + for _, flag := range flags { + key, value, ok := strings.Cut(flag, "=") + if !ok || key == "" { + return nil, fmt.Errorf("invalid --set-metadata: expected key=value, got %q", flag) + } + set[key] = storage.MetadataEditValue(value) + } + return set, nil +} + func replacesExistingNotes(existing string, fields map[string]any) bool { newNotes, replacing := fields["notes"].(string) return replacing && existing != "" && newNotes != existing diff --git a/cmd/bd/update_embedded_test.go b/cmd/bd/update_embedded_test.go index dc833a2ff..ffbee0d9f 100644 --- a/cmd/bd/update_embedded_test.go +++ b/cmd/bd/update_embedded_test.go @@ -872,8 +872,8 @@ func TestEmbeddedUpdate(t *testing.T) { issue := bdCreate(t, bd, dir, "Session test", "--type", "task") bdUpdate(t, bd, dir, issue.ID, "--status", "closed", "--session", "sess-123") got := bdShow(t, bd, dir, issue.ID) - // Verify the issue is closed (closed_by_session is stored but not - // included in IssueSelectColumns, so we verify status + closed_at). + // closed_by_session is selected by IssueSelectColumns and hydrated onto + // the issue; here we just verify the close itself landed. if got.Status != types.StatusClosed { t.Errorf("expected status closed, got %s", got.Status) } diff --git a/cmd/bd/write_verbs_parity_test.go b/cmd/bd/write_verbs_parity_test.go new file mode 100644 index 000000000..7080f4b80 --- /dev/null +++ b/cmd/bd/write_verbs_parity_test.go @@ -0,0 +1,1877 @@ +//go:build cgo + +// Characterization ("parity") suite for the four write verbs — bd create, +// bd update, bd close, bd reopen — pinning the observable CLI contract as it +// stands BEFORE cmd/bd is rewired onto the issue-operations facade +// (internal/storage/issueops). +// +// Everything here is a statement about what the CLI does TODAY, not about what +// it ought to do. Several pinned behaviors are known bugs; four of them have +// already been adjudicated and WILL change during the rewire: +// +// R1 bd create --id -> silent full-row upsert reporting success +// [FLIPPED to a refusal by the bd create rewire] +// R2 compound bd update -> one store call (= one hook firing) per +// field/label/parent edit, plus phantom +// label_added/label_removed events +// [FLIPPED to one atomic op by the bd update +// rewire] +// R3 bd update --parent -> removes only the FIRST parent edge +// [FLIPPED to replace-all by the bd update +// rewire] +// R4 bd reopen on a non-done, +// non-open status -> prints "↻ Reopened" and reports success +// [FLIPPED to "nothing to do" by the bd +// reopen rewire] +// +// Assertions covering those four are tagged `RULING Rn`. When a rewire commit +// flips one, the assertion is updated IN THAT COMMIT with a comment naming the +// ruling. Any OTHER assertion in this file changing is a regression, not a +// refactor. All four have now landed; every remaining assertion is unchanged +// from the pre-rewire CLI and must stay that way. +// +// Harness: the commands' RunE functions are invoked in-process against a real +// storage.DoltStorage, with stdout/stderr captured and the returned error +// mapped to the exit code main.go would produce. The store is wrapped in +// parityStore, a counting decorator shaped exactly like +// storage.HookFiringStore (embed + Unwrap), so mutation-call counts stand in +// for hook-firing counts: HookFiringStore fires exactly one hook per mutating +// store call, so "N store calls" is "N hook firings". + +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "github.com/steveyegge/beads" + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" +) + +// ===== counting store decorator ===== + +// parityStore counts the mutating store calls a command makes. It mirrors +// storage.HookFiringStore's shape (embedded interface for passthrough, inner +// for the real calls, Unwrap for storage.UnwrapStore) so the counts equal the +// number of hooks production would fire for the same command. +type parityStore struct { + storage.DoltStorage + inner storage.DoltStorage + + mu sync.Mutex + calls []string +} + +func newParityStore(inner storage.DoltStorage) *parityStore { + return &parityStore{DoltStorage: inner, inner: inner} +} + +func (p *parityStore) Unwrap() storage.DoltStorage { return p.inner } + +func (p *parityStore) record(name string) { + p.mu.Lock() + p.calls = append(p.calls, name) + p.mu.Unlock() +} + +func (p *parityStore) mutations() []string { + p.mu.Lock() + defer p.mu.Unlock() + return append([]string(nil), p.calls...) +} + +func (p *parityStore) reset() { + p.mu.Lock() + p.calls = nil + p.mu.Unlock() +} + +func (p *parityStore) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error { + p.record("CreateIssue") + return p.inner.CreateIssue(ctx, issue, actor) +} + +func (p *parityStore) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error { + p.record("UpdateIssue") + return p.inner.UpdateIssue(ctx, id, updates, actor) +} + +func (p *parityStore) UpdateIssueChecked(ctx context.Context, id string, updates map[string]interface{}, actor string, opts storage.UpdateIssueOptions) error { + p.record("UpdateIssueChecked") + return p.inner.UpdateIssueChecked(ctx, id, updates, actor, opts) +} + +func (p *parityStore) UpdateIssueType(ctx context.Context, id, issueType, actor string) error { + p.record("UpdateIssueType") + return p.inner.UpdateIssueType(ctx, id, issueType, actor) +} + +func (p *parityStore) ClaimIssue(ctx context.Context, id, actor string) error { + p.record("ClaimIssue") + return p.inner.ClaimIssue(ctx, id, actor) +} + +func (p *parityStore) ReopenIssue(ctx context.Context, id, reason, actor string) error { + p.record("ReopenIssue") + return p.inner.ReopenIssue(ctx, id, reason, actor) +} + +func (p *parityStore) CloseIssue(ctx context.Context, id, reason, actor, session string) error { + p.record("CloseIssue") + return p.inner.CloseIssue(ctx, id, reason, actor, session) +} + +func (p *parityStore) CloseIssueChecked(ctx context.Context, id, actor string, opts storage.CloseIssueOptions) (storage.CloseIssueResult, error) { + p.record("CloseIssueChecked") + return p.inner.CloseIssueChecked(ctx, id, actor, opts) +} + +func (p *parityStore) AddLabel(ctx context.Context, issueID, label, actor string) error { + p.record("AddLabel") + return p.inner.AddLabel(ctx, issueID, label, actor) +} + +func (p *parityStore) RemoveLabel(ctx context.Context, issueID, label, actor string) error { + p.record("RemoveLabel") + return p.inner.RemoveLabel(ctx, issueID, label, actor) +} + +func (p *parityStore) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error { + p.record("AddDependency") + return p.inner.AddDependency(ctx, dep, actor) +} + +func (p *parityStore) RemoveDependency(ctx context.Context, issueID, dependsOnID, actor string) error { + p.record("RemoveDependency") + return p.inner.RemoveDependency(ctx, issueID, dependsOnID, actor) +} + +// ===== counting issue-operations facade ===== + +// parityOps is parityStore's counterpart on the issue-operations facade, the +// surface the write verbs move onto. It records into the SAME call list, so +// `mutations()` stays one entry per hook firing however the verb reached the +// database — a verb still on a direct store call records "UpdateIssue", a +// rewired verb records "Update". +// +// The firing rules mirror beads.hookIssueOperations exactly, which is what +// makes the counts comparable across the rewire: Create, Update and Close fire +// their completion hook on any success; Reopen fires only when it changed +// something. +// +// A facade is required here because the lifecycle accessor never routes +// through the DoltStorage methods parityStore decorates — it builds operations +// straight off the concrete store — so once a verb is rewired, store-level +// counting goes blind and every "no store mutations" assertion would pass +// vacuously. +type parityOps struct { + inner issueops.Lifecycle + store *parityStore +} + +func (o *parityOps) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) { + result, err := o.inner.Create(ctx, request) + if err == nil { + o.store.record("Create") + } + return result, err +} + +func (o *parityOps) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) { + result, err := o.inner.Update(ctx, request) + if err == nil { + o.store.record("Update") + } + return result, err +} + +func (o *parityOps) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) { + result, err := o.inner.Close(ctx, request) + if err == nil { + o.store.record("Close") + } + return result, err +} + +func (o *parityOps) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) { + result, err := o.inner.Reopen(ctx, request) + if err == nil && result.Changed { + o.store.record("Reopen") + } + return result, err +} + +// ===== harness ===== + +type parityEnv struct { + t *testing.T + store *parityStore + beadsDir string +} + +// newParityEnv wires the package globals the write-verb RunE functions read +// (store, rootCtx, actor, jsonOutput, quietFlag, readonlyMode) at a real Dolt +// store, points BEADS_DIR at its .beads dir so SetLastTouchedID is observable, +// and restores everything on cleanup. +// +// quietFlag is set so `bd create`'s random maybeShowTip line cannot appear on +// stdout mid-assertion. It does NOT suppress the "✓ Created issue:" lines: +// those go through debug.PrintNormal, which reads the debug package's own +// quiet flag (set by main.go's PersistentPreRun, which RunE-level tests skip). +// parityOwnerEmail pins the git identity create derives its owner field from. +const parityOwnerEmail = "parity-owner@test" + +func newParityEnv(t *testing.T) *parityEnv { + t.Helper() + + saveAndRestoreGlobals(t) + ensureCleanGlobalState(t) + initConfigForTest(t) + + dir := t.TempDir() + beadsDir := filepath.Join(dir, ".beads") + raw := newTestStore(t, filepath.Join(beadsDir, "beads.db")) + ps := newParityStore(raw) + + savedCtx, savedJSON, savedActor := rootCtx, jsonOutput, actor + savedQuiet, savedReadonly := quietFlag, readonlyMode + savedNewOps := newIssueOperations + t.Cleanup(func() { + rootCtx, jsonOutput, actor = savedCtx, savedJSON, savedActor + quietFlag, readonlyMode = savedQuiet, savedReadonly + newIssueOperations = savedNewOps + }) + + // Count the facade operations the write verbs perform. The real store is + // unwrapped first so the counted lifecycle is the concrete store's, + // whatever parityStore's own passthrough happens to promote. + newIssueOperations = func(target beads.Storage) (issueops.Lifecycle, error) { + if decorated, ok := target.(storage.DoltStorage); ok { + target = storage.UnwrapStore(decorated) + } + inner, err := target.IssueLifecycle() + if err != nil { + return nil, err + } + return &parityOps{inner: inner, store: ps}, nil + } + + store = ps + rootCtx = context.Background() + jsonOutput = false + actor = "parity-actor" + quietFlag = true + readonlyMode = false + + t.Setenv("NO_COLOR", "1") + // getOwner reads GIT_AUTHOR_EMAIL, then falls back to git config user.email, so + // create's owner field — and therefore its --json key set — otherwise varies with + // the ambient git identity. Pin it: CI commonly sets GIT_AUTHOR_EMAIL, a developer + // shell usually does not, and the suite must render the same verdict in both. + t.Setenv("GIT_AUTHOR_EMAIL", parityOwnerEmail) + t.Setenv("BEADS_DIR", beadsDir) + + // Pin every config key the write verbs read. config.Initialize() merges + // whatever config.yaml files happen to exist under the test HOME, and + // other tests in this package mutate these keys globally — an inherited + // value would either break these tests or, worse, silently weaken them + // (output.title-length=0 makes formatFeedbackID drop the title, which + // would turn the exact-line assertions into vacuous id-only comparisons). + setParityConfig(t, map[string]any{ + "issue-prefix": "", // fall through to the store's "test" + "output.title-length": 255, + "create.require-description": false, + "validation.on-create": "", + "validation.on-close": "", + "routing.mode": "", + "routing.default": "", + "routing.maintainer": "", + "routing.contributor": "", + }) + + // Styling must be inert or the exact-line assertions below are comparing + // against ANSI-wrapped text. Fail loudly rather than silently mismatch. + if got := ui.RenderPass("✓"); got != "✓" { + t.Fatalf("parity harness requires unstyled output; ui.RenderPass(\"✓\") = %q", got) + } + // Guard the pin above: the human-output assertions are only meaningful + // while formatFeedbackID actually interpolates the title. + if got := formatFeedbackID("x-1", "T"); got != "x-1 — T" { + t.Fatalf("parity harness requires title interpolation; formatFeedbackID = %q", got) + } + + env := &parityEnv{t: t, store: ps, beadsDir: beadsDir} + env.clearLastTouched() + return env +} + +// setParityConfig overrides config keys for the duration of the test. The +// enclosing initConfigForTest already registers config.ResetForTesting as +// cleanup, which drops these along with the rest of the viper state. +func setParityConfig(t *testing.T, kv map[string]any) { + t.Helper() + for key, value := range kv { + config.Set(key, value) + } +} + +func (e *parityEnv) clearLastTouched() { + e.t.Helper() + _ = os.Remove(filepath.Join(e.beadsDir, lastTouchedFile)) +} + +func (e *parityEnv) lastTouched() string { + e.t.Helper() + data, err := os.ReadFile(filepath.Join(e.beadsDir, lastTouchedFile)) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} + +// runResult is everything a shell would observe from one command invocation. +type runResult struct { + stdout string + stderr string + exitCode int + err error +} + +// run invokes cmd.RunE directly (as the other RunE-level tests in this package +// do), capturing both streams and mapping the returned error to the exit code +// main.go's run() would produce for it. +func (e *parityEnv) run(cmd *cobra.Command, args ...string) runResult { + e.t.Helper() + + stdioMutex.Lock() + defer stdioMutex.Unlock() + + oldOut, oldErr := os.Stdout, os.Stderr + outR, outW, err := os.Pipe() + if err != nil { + e.t.Fatalf("os.Pipe: %v", err) + } + errR, errW, err := os.Pipe() + if err != nil { + e.t.Fatalf("os.Pipe: %v", err) + } + os.Stdout, os.Stderr = outW, errW + + var outBuf, errBuf strings.Builder + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); _, _ = io.Copy(&outBuf, outR) }() + go func() { defer wg.Done(); _, _ = io.Copy(&errBuf, errR) }() + + runErr := cmd.RunE(cmd, args) + + _ = outW.Close() + _ = errW.Close() + os.Stdout, os.Stderr = oldOut, oldErr + wg.Wait() + _ = outR.Close() + _ = errR.Close() + + return runResult{ + stdout: outBuf.String(), + stderr: errBuf.String(), + exitCode: parityExitCode(runErr), + err: runErr, + } +} + +// parityExitCode mirrors main.go's error→exit-status mapping. +func parityExitCode(err error) int { + if err == nil { + return 0 + } + if code, ok := exitCodeFromError(err); ok { + return code + } + return 1 +} + +// setFlags sets flags on cmd and registers a cleanup that returns every flag +// on the command to its declared default. The command objects are package +// globals shared by the whole test binary, so leaking a set flag silently +// corrupts unrelated tests. +func (e *parityEnv) setFlags(cmd *cobra.Command, kv map[string]string) { + e.t.Helper() + e.t.Cleanup(func() { resetCommandFlagsToDefaults(cmd) }) + for name, value := range kv { + if err := cmd.Flags().Set(name, value); err != nil { + e.t.Fatalf("set --%s=%q: %v", name, value, err) + } + } +} + +func resetCommandFlagsToDefaults(cmd *cobra.Command) { + cmd.Flags().VisitAll(func(f *pflag.Flag) { + switch v := f.Value.(type) { + case *closeReasonFlagValue: + // Accumulating flag: Set appends, so it cannot be reset by Set. + v.values = nil + case pflag.SliceValue: + _ = v.Replace(nil) + default: + _ = f.Value.Set(f.DefValue) + } + f.Changed = false + }) +} + +// seed creates an issue directly through the store (bypassing the CLI) so +// fixtures never depend on the behavior under test. +func (e *parityEnv) seed(id, title string, mutate func(*types.Issue)) *types.Issue { + e.t.Helper() + issue := &types.Issue{ + ID: id, + Title: title, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + CreatedBy: "parity-seed", + } + if mutate != nil { + mutate(issue) + } + if err := e.store.inner.CreateIssue(rootCtx, issue, "parity-seed"); err != nil { + e.t.Fatalf("seed %s: %v", id, err) + } + e.store.reset() + return issue +} + +func (e *parityEnv) get(id string) *types.Issue { + e.t.Helper() + issue, err := e.store.inner.GetIssue(rootCtx, id) + if err != nil { + e.t.Fatalf("GetIssue(%s): %v", id, err) + } + return issue +} + +func (e *parityEnv) eventTypes(id string) []string { + e.t.Helper() + events, err := e.store.inner.GetEvents(rootCtx, id, 0) + if err != nil { + e.t.Fatalf("GetEvents(%s): %v", id, err) + } + out := make([]string, 0, len(events)) + for _, ev := range events { + out = append(out, string(ev.EventType)) + } + return out +} + +func countOf(values []string, want string) int { + n := 0 + for _, v := range values { + if v == want { + n++ + } + } + return n +} + +// decodeJSONObject asserts stdout is exactly one pretty-printed JSON object +// and returns it as a map (key order is not preserved; use rawJSONKeyOrder for +// that). +func decodeJSONObject(t *testing.T, stdout string) map[string]any { + t.Helper() + var obj map[string]any + dec := json.NewDecoder(strings.NewReader(stdout)) + if err := dec.Decode(&obj); err != nil { + t.Fatalf("stdout is not a single JSON object: %v\nstdout:\n%s", err, stdout) + } + if rest, _ := io.ReadAll(dec.Buffered()); strings.TrimSpace(string(rest)) != "" { + t.Fatalf("trailing content after JSON object: %q\nstdout:\n%s", rest, stdout) + } + return obj +} + +func decodeJSONArray(t *testing.T, stdout string) []map[string]any { + t.Helper() + var arr []map[string]any + dec := json.NewDecoder(strings.NewReader(stdout)) + if err := dec.Decode(&arr); err != nil { + t.Fatalf("stdout is not a JSON array: %v\nstdout:\n%s", err, stdout) + } + return arr +} + +func parityJSONKeys(m map[string]any) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + // Sorted so the failure message is stable and diffable. + for i := 1; i < len(keys); i++ { + for j := i; j > 0 && keys[j] < keys[j-1]; j-- { + keys[j], keys[j-1] = keys[j-1], keys[j] + } + } + return keys +} + +func assertKeySet(t *testing.T, obj map[string]any, want []string) { + t.Helper() + got := parityJSONKeys(obj) + wantSorted := append([]string(nil), want...) + for i := 1; i < len(wantSorted); i++ { + for j := i; j > 0 && wantSorted[j] < wantSorted[j-1]; j-- { + wantSorted[j], wantSorted[j-1] = wantSorted[j-1], wantSorted[j] + } + } + if strings.Join(got, ",") != strings.Join(wantSorted, ",") { + t.Errorf("JSON key set mismatch\n got: %v\nwant: %v", got, wantSorted) + } +} + +// rawJSONKeyOrder returns the top-level keys of a JSON object in the order +// they appear in the byte stream. Key ORDER is part of the byte shape: an +// object built by re-marshaling a map has sorted keys, one marshaled straight +// from a struct has struct-field order. +func rawJSONKeyOrder(t *testing.T, raw string) []string { + t.Helper() + dec := json.NewDecoder(strings.NewReader(raw)) + tok, err := dec.Token() + if err != nil { + t.Fatalf("read JSON: %v", err) + } + if delim, ok := tok.(json.Delim); !ok || delim != '{' { + t.Fatalf("expected object, got %v", tok) + } + var keys []string + depth := 0 + for dec.More() || depth > 0 { + tok, err := dec.Token() + if err != nil { + t.Fatalf("read JSON: %v", err) + } + if delim, ok := tok.(json.Delim); ok { + switch delim { + case '{', '[': + depth++ + case '}', ']': + depth-- + if depth < 0 { + return keys + } + } + continue + } + if depth == 0 { + key, ok := tok.(string) + if !ok { + t.Fatalf("expected object key, got %T %v", tok, tok) + } + keys = append(keys, key) + // Consume the value. + vtok, err := dec.Token() + if err != nil { + t.Fatalf("read JSON value: %v", err) + } + if delim, ok := vtok.(json.Delim); ok && (delim == '{' || delim == '[') { + depth++ + } + } + } + return keys +} + +func assertRecentUTCTimestamp(t *testing.T, label, value string) { + t.Helper() + if !strings.HasSuffix(value, "Z") { + t.Errorf("%s = %q; want a UTC (Z-suffixed) timestamp", label, value) + } + ts, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + t.Fatalf("%s = %q is not RFC3339Nano: %v", label, value, err) + } + if ts.IsZero() { + t.Errorf("%s is the zero time", label) + } + if delta := time.Since(ts); delta < -time.Minute || delta > 10*time.Minute { + t.Errorf("%s = %q is %v away from now; want a freshly stamped time", label, value, delta) + } +} + +// ===== bd create ===== + +// TestParityCreateJSONShape pins `bd create --json`: a SINGLE pretty-printed +// JSON object (not an array), emitted from the LOCAL *types.Issue the CLI +// built — never a re-read — carrying a synthesized "schema_version" key and, +// because outputJSON round-trips a non-slice through map[string]any, SORTED +// key order. +// +// Source of truth: cmd/bd/create.go:601-604 (outputJSON(issue)) over the +// struct from cmd/bd/create.go:521 (buildCreateIssue), via +// cmd/bd/output.go:68-99 (wrapWithSchemaVersion). +func TestParityCreateJSONShape(t *testing.T) { + env := newParityEnv(t) + jsonOutput = true + + env.setFlags(createCmd, map[string]string{ + "description": "parity body", + "priority": "1", + "type": "bug", + "assignee": "someone", + "labels": "alpha,beta", + }) + + res := env.run(createCmd, "Create json shape") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + obj := decodeJSONObject(t, res.stdout) + + // The exact key set. `dependencies` and `comments` are absent because the + // local struct never carries them — create does not re-read. + assertKeySet(t, obj, []string{ + "id", "title", "description", "status", "priority", "issue_type", + "assignee", "created_at", "created_by", "updated_at", "labels", + "owner", "schema_version", + }) + if obj["owner"] != parityOwnerEmail { + t.Errorf("owner = %v, want %q from the git identity", obj["owner"], parityOwnerEmail) + } + if _, ok := obj["dependencies"]; ok { + t.Error("create --json emitted a `dependencies` key; today it prints a local struct that has none") + } + if _, ok := obj["comments"]; ok { + t.Error("create --json emitted a `comments` key; today it prints a local struct that has none") + } + if obj["schema_version"] != float64(JSONSchemaVersion) { + t.Errorf("schema_version = %v, want %d", obj["schema_version"], JSONSchemaVersion) + } + + // Byte shape: two-space indent, trailing newline, sorted top-level keys. + if !strings.HasPrefix(res.stdout, "{\n \"") { + t.Errorf("create --json is not 2-space-indented: %q", firstLine(res.stdout, 2)) + } + if !strings.HasSuffix(res.stdout, "}\n") { + t.Errorf("create --json does not end with \"}\\n\": %q", res.stdout[max(0, len(res.stdout)-8):]) + } + order := rawJSONKeyOrder(t, res.stdout) + if !isSortedStrings(order) { + t.Errorf("create --json key order = %v; today it is alphabetically sorted (map round-trip in wrapWithSchemaVersion)", order) + } + + // Field values come from the local struct, so the CLI-supplied values — + // not DB-normalized ones — are what get printed. + if obj["priority"] != float64(1) { + t.Errorf("priority = %v, want 1", obj["priority"]) + } + if obj["issue_type"] != "bug" { + t.Errorf("issue_type = %v, want bug", obj["issue_type"]) + } + if obj["status"] != string(types.StatusOpen) { + t.Errorf("status = %v, want %q", obj["status"], types.StatusOpen) + } + labels, _ := obj["labels"].([]any) + if len(labels) != 2 || labels[0] != "alpha" || labels[1] != "beta" { + t.Errorf("labels = %v, want [alpha beta]", obj["labels"]) + } +} + +// TestParityCreateJSONTimestamps pins that `bd create --json` DOES emit +// populated created_at/updated_at (and no closed_at for an open issue). +// +// They are populated by a side effect: the storage layer's +// issueops.PrepareIssueForInsert (internal/storage/issueops/create.go:474-485) +// mutates the very *types.Issue pointer the CLI later prints, stamping +// time.Now().UTC(). So the values are Go-side wall-clock UTC at +// nanosecond precision, NOT the DB's stored representation. Emitting zero +// timestamps here is the predicted failure mode of the facade rewire. +func TestParityCreateJSONTimestamps(t *testing.T) { + env := newParityEnv(t) + jsonOutput = true + + env.setFlags(createCmd, map[string]string{"description": "timestamps"}) + res := env.run(createCmd, "Create timestamps") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + obj := decodeJSONObject(t, res.stdout) + createdAt, _ := obj["created_at"].(string) + updatedAt, _ := obj["updated_at"].(string) + if createdAt == "" || updatedAt == "" { + t.Fatalf("created_at=%q updated_at=%q; both must be populated", createdAt, updatedAt) + } + assertRecentUTCTimestamp(t, "created_at", createdAt) + assertRecentUTCTimestamp(t, "updated_at", updatedAt) + if _, ok := obj["closed_at"]; ok { + t.Error("create --json emitted closed_at for an open issue") + } +} + +// TestParityCreateSilent pins `bd create --silent`: stdout is exactly the new +// ID plus a newline, and nothing else. Source: cmd/bd/create.go:605-606. +func TestParityCreateSilent(t *testing.T) { + env := newParityEnv(t) + + env.setFlags(createCmd, map[string]string{ + "silent": "true", + "description": "silent body", + }) + + res := env.run(createCmd, "Create silent") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + id := strings.TrimSpace(res.stdout) + if id == "" { + t.Fatal("no ID on stdout") + } + if want := id + "\n"; res.stdout != want { + t.Errorf("stdout = %q, want %q", res.stdout, want) + } + env.get(id) // must exist +} + +// TestParityCreateHumanOutput pins the three-line human report, byte for byte. +// Source: cmd/bd/create.go:607-613. +func TestParityCreateHumanOutput(t *testing.T) { + env := newParityEnv(t) + + env.setFlags(createCmd, map[string]string{"description": "human body", "priority": "3"}) + title := "Create human output" + res := env.run(createCmd, title) + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + id := env.lastTouched() + if id == "" { + t.Fatal("no last-touched ID recorded; cannot resolve created ID") + } + want := fmt.Sprintf("✓ Created issue: %s\n Priority: P3\n Status: open\n", formatFeedbackID(id, title)) + if res.stdout != want { + t.Errorf("stdout mismatch\n got: %q\nwant: %q", res.stdout, want) + } + if res.stderr != "" { + t.Errorf("stderr = %q, want empty on the happy path", res.stderr) + } + if !strings.HasPrefix(res.stdout, "✓ Created issue: ") { + t.Errorf("create's success line no longer starts with %q", "✓ Created issue: ") + } +} + +// TestParityCreateSetsLastTouched pins cmd/bd/create.go:615 — a successful +// create records the new ID as last-touched. +func TestParityCreateSetsLastTouched(t *testing.T) { + env := newParityEnv(t) + + env.setFlags(createCmd, map[string]string{"silent": "true", "description": "lt"}) + res := env.run(createCmd, "Create last touched") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + id := strings.TrimSpace(res.stdout) + if got := env.lastTouched(); got != id { + t.Errorf("last-touched = %q, want %q", got, id) + } +} + +// TestParityCreateWithDepsOmitsDependenciesKey pins the create/update JSON +// asymmetry at its sharpest: even when the create actually persists dependency +// edges, `bd create --json` shows none, because it prints the local struct. +// `bd update --json` on the same issue re-reads — and (today) still shows no +// `dependencies` key, because storage GetIssue does not hydrate dependencies +// either (internal/storage/issueops/get_issue.go:37-56). The difference that +// IS observable is the container: object vs array, sorted keys vs struct +// order, schema_version present vs absent. +func TestParityCreateWithDepsOmitsDependenciesKey(t *testing.T) { + env := newParityEnv(t) + target := env.seed("test-dep1", "Dependency target", nil) + + jsonOutput = true + env.setFlags(createCmd, map[string]string{ + "description": "with deps", + "deps": "blocked-by:" + target.ID, + }) + res := env.run(createCmd, "Create with deps") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + obj := decodeJSONObject(t, res.stdout) + if _, ok := obj["dependencies"]; ok { + t.Error("create --json emitted a `dependencies` key even though it prints a local struct") + } + id, _ := obj["id"].(string) + deps, err := env.store.inner.GetDependencyRecords(rootCtx, id) + if err != nil { + t.Fatalf("GetDependencyRecords: %v", err) + } + if len(deps) != 1 { + t.Fatalf("expected the edge to be persisted, got %d dependency records", len(deps)) + } +} + +// TestParityCreateOnOccupiedIDRefuses pins RULING R1 as adopted: `bd create +// --id ` refuses. The facade's create-only guard returns +// storage.ErrAlreadyExists, the CLI maps it to exit 1 with a fixed message +// naming the alternatives, and the pre-existing row is left untouched. +// +// Before the rewire this was a full-row silent upsert that reported success +// (exit 0, "✓ Created issue:") while destroying the existing issue and +// recording no creation event — silent data loss. Source of the new behavior: +// cmd/bd/create.go's ops.Create call -> +// internal/storage/issueops/create_only_guard.go. +func TestParityCreateOnOccupiedIDRefuses(t *testing.T) { + env := newParityEnv(t) + env.seed("test-occ1", "Original title", func(i *types.Issue) { + i.Description = "original description" + i.Priority = 0 + }) + + env.setFlags(createCmd, map[string]string{ + "id": "test-occ1", + "description": "replacement description", + "priority": "4", + }) + res := env.run(createCmd, "Replacement title") + + // RULING R1: the occupied ID is refused. + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstdout:\n%s\nstderr:\n%s", res.exitCode, res.stdout, res.stderr) + } + const wantErr = "Error: test-occ1 already exists; use bd update, or bd import for upsert semantics\n" + if res.stderr != wantErr { + t.Errorf("stderr = %q, want %q", res.stderr, wantErr) + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty on a refused create", res.stdout) + } + + // RULING R1: and the pre-existing row survives intact. + after := env.get("test-occ1") + if after.Title != "Original title" { + t.Errorf("title = %q, want the seeded title", after.Title) + } + if after.Description != "original description" { + t.Errorf("description = %q, want the seeded description", after.Description) + } + if after.Priority != 0 { + t.Errorf("priority = %d, want 0", after.Priority) + } + if got := env.lastTouched(); got != "" { + t.Errorf("last-touched = %q, want it untouched on a refused create", got) + } +} + +// TestParityCreateParentNotFoundExits1 pins a create-side pre-write refusal: +// a missing --parent aborts with exit 1 and a fixed message before any ID is +// reserved or any row written. Source: cmd/bd/create.go:461-469. +func TestParityCreateParentNotFoundExits1(t *testing.T) { + env := newParityEnv(t) + + env.setFlags(createCmd, map[string]string{ + "parent": "test-no-such-parent", + "description": "orphan", + }) + res := env.run(createCmd, "Create with missing parent") + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstderr:\n%s", res.exitCode, res.stderr) + } + const want = "Error: parent issue test-no-such-parent not found\n" + if res.stderr != want { + t.Errorf("stderr = %q, want %q", res.stderr, want) + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty", res.stdout) + } + if got := env.store.mutations(); len(got) != 0 { + t.Errorf("store mutations = %v, want none", got) + } + if got := env.lastTouched(); got != "" { + t.Errorf("last-touched = %q, want it untouched on a failed create", got) + } +} + +// TestParityCreateMissingDepTargetIsFatal pins today's CLI dependency +// contract: a --deps target that does not exist fails the whole create, exit +// 1, with the issue rolled back — the edge is never silently dropped. +// Source: cmd/bd/create_atomic.go:35-68 (one transaction; any edge failure +// returns fatal) via cmd/bd/create.go:567-569. +func TestParityCreateMissingDepTargetIsFatal(t *testing.T) { + env := newParityEnv(t) + + env.setFlags(createCmd, map[string]string{ + "description": "dangling dep", + "deps": "blocked-by:test-no-such-dep", + }) + res := env.run(createCmd, "Create with missing dep target") + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1 (a missing dep target must not silently succeed)\nstdout:\n%s\nstderr:\n%s", + res.exitCode, res.stdout, res.stderr) + } + if !strings.HasPrefix(res.stderr, "Error: ") { + t.Errorf("stderr = %q, want an \"Error: \" prefixed diagnosis", res.stderr) + } + issues, err := env.store.inner.SearchIssues(rootCtx, "", types.IssueFilter{}) + if err != nil { + t.Fatalf("SearchIssues: %v", err) + } + for _, iss := range issues { + if iss.Title == "Create with missing dep target" { + t.Errorf("issue %s survived a failed dependency create; the transaction must roll back", iss.ID) + } + } +} + +// TestParityCreateJSONErrorShape pins where a create error goes in --json +// mode: HandleErrorRespectJSON writes the error object to STDOUT (not stderr), +// with a synthesized schema_version, and exits 1. +// Source: cmd/bd/errors.go:91-97 and :57-84. +func TestParityCreateJSONErrorShape(t *testing.T) { + env := newParityEnv(t) + jsonOutput = true + + env.setFlags(createCmd, map[string]string{ + "description": "bad deps", + "deps": "not-a-valid-spec:::", + }) + res := env.run(createCmd, "Create json error") + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstdout:\n%s\nstderr:\n%s", res.exitCode, res.stdout, res.stderr) + } + obj := decodeJSONObject(t, res.stdout) + assertKeySet(t, obj, []string{"error", "schema_version"}) + if obj["schema_version"] != float64(JSONSchemaVersion) { + t.Errorf("schema_version = %v, want %d", obj["schema_version"], JSONSchemaVersion) + } + if msg, _ := obj["error"].(string); msg == "" { + t.Error("error message is empty") + } + if res.stderr != "" { + t.Errorf("stderr = %q; in --json mode the error belongs on stdout", res.stderr) + } +} + +// ===== bd update ===== + +// TestParityUpdateJSONShape pins `bd update --json`: a JSON ARRAY of re-read +// issues, in struct-field order, with NO schema_version wrapper (outputJSON +// leaves slices alone — cmd/bd/output.go:85-87). +// +// Source: cmd/bd/update.go:586 (re-fetch) and :631-635 (outputJSON). +func TestParityUpdateJSONShape(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd1", "Update json shape", nil) + + jsonOutput = true + env.setFlags(updateCmd, map[string]string{"priority": "0"}) + res := env.run(updateCmd, "test-upd1") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + if !strings.HasPrefix(res.stdout, "[\n {") { + t.Errorf("update --json is not a 2-space-indented array: %q", firstLine(res.stdout, 2)) + } + if !strings.HasSuffix(res.stdout, "]\n") { + t.Errorf("update --json does not end with \"]\\n\"") + } + arr := decodeJSONArray(t, res.stdout) + if len(arr) != 1 { + t.Fatalf("array length = %d, want 1", len(arr)) + } + if _, ok := arr[0]["schema_version"]; ok { + t.Error("update --json array elements carry schema_version; today outputJSON leaves slices unwrapped") + } + if arr[0]["priority"] != float64(0) { + t.Errorf("priority = %v, want 0 (the value written)", arr[0]["priority"]) + } + + // Struct-field order (types.Issue), not sorted: `id` then `title` — the + // reverse of alphabetical, which is what create emits. + inner := res.stdout[strings.Index(res.stdout, "{"):] + order := rawJSONKeyOrder(t, inner) + if len(order) < 2 || order[0] != "id" || order[1] != "title" { + t.Errorf("update --json element key order starts %v; today it is types.Issue struct order (id, title, ...)", order) + } + if isSortedStrings(order) { + t.Errorf("update --json element keys are sorted %v; today they follow struct order", order) + } + + // GetIssue does not hydrate dependencies/comments, so the re-read carries + // neither key even though it is a real re-read. + if _, ok := arr[0]["dependencies"]; ok { + t.Error("update --json emitted `dependencies`; today GetIssue does not hydrate them") + } + assertRecentUTCTimestamp(t, "created_at", arr[0]["created_at"].(string)) + assertRecentUTCTimestamp(t, "updated_at", arr[0]["updated_at"].(string)) +} + +// TestParityUpdateHumanOutput pins the human success line, byte for byte. +// Source: cmd/bd/update.go:597. +func TestParityUpdateHumanOutput(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd2", "Update human output", nil) + + env.setFlags(updateCmd, map[string]string{"status": "in_progress"}) + res := env.run(updateCmd, "test-upd2") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + want := fmt.Sprintf("✓ Updated issue: %s\n", formatFeedbackID("test-upd2", "Update human output")) + if res.stdout != want { + t.Errorf("stdout mismatch\n got: %q\nwant: %q", res.stdout, want) + } + if res.stderr != "" { + t.Errorf("stderr = %q, want empty on the happy path", res.stderr) + } + if !strings.HasPrefix(res.stdout, "✓ Updated issue: ") { + t.Errorf("update's success line no longer starts with %q", "✓ Updated issue: ") + } +} + +// TestParityUpdateSetsLastTouched pins cmd/bd/update.go:627-629 — the FIRST +// successfully updated ID becomes last-touched. +func TestParityUpdateSetsLastTouched(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd3", "First", nil) + env.seed("test-upd4", "Second", nil) + + env.setFlags(updateCmd, map[string]string{"priority": "1"}) + res := env.run(updateCmd, "test-upd3", "test-upd4") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + if got := env.lastTouched(); got != "test-upd3" { + t.Errorf("last-touched = %q, want the FIRST updated ID %q", got, "test-upd3") + } +} + +// TestParityUpdateNoUpdatesShortCircuit pins the pre-write short-circuit at +// cmd/bd/update.go:327-330: with no field flags and no --claim, update prints +// "No updates specified" on STDOUT, exits 0, touches no store, and does NOT +// record a last-touched. +func TestParityUpdateNoUpdatesShortCircuit(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd5", "No updates", nil) + + env.setFlags(updateCmd, nil) + res := env.run(updateCmd, "test-upd5") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + if res.stdout != "No updates specified\n" { + t.Errorf("stdout = %q, want %q", res.stdout, "No updates specified\n") + } + if got := env.store.mutations(); len(got) != 0 { + t.Errorf("store mutations = %v, want none", got) + } + if got := env.lastTouched(); got != "" { + t.Errorf("last-touched = %q, want it untouched", got) + } +} + +// TestParityUpdateDefaultsToLastTouched pins cmd/bd/update.go:58-65: with no +// positional IDs, update targets the last-touched issue. +func TestParityUpdateDefaultsToLastTouched(t *testing.T) { + env := newParityEnv(t) + env.seed("test-updlt", "Default target", nil) + SetLastTouchedID("test-updlt") + + env.setFlags(updateCmd, map[string]string{"priority": "1"}) + res := env.run(updateCmd) + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + if got := env.get("test-updlt").Priority; got != 1 { + t.Errorf("priority = %d, want 1; bare `bd update` must target last-touched", got) + } +} + +// TestParityUpdateNoIDAndNoLastTouchedExits1 pins the other half of the same +// default-target contract (cmd/bd/update.go:59-65). +func TestParityUpdateNoIDAndNoLastTouchedExits1(t *testing.T) { + env := newParityEnv(t) + env.clearLastTouched() + + env.setFlags(updateCmd, map[string]string{"priority": "1"}) + res := env.run(updateCmd) + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstderr:\n%s", res.exitCode, res.stderr) + } + const want = "Error: no issue ID provided and no last touched issue\n" + if res.stderr != want { + t.Errorf("stderr = %q, want %q", res.stderr, want) + } +} + +// TestParityUpdateGuardsRequireFieldUpdate pins the second pre-write +// short-circuit (cmd/bd/update.go:788-798): --if-assignee/--if-status with +// only label/parent edits is rejected before any write, exit 1. +func TestParityUpdateGuardsRequireFieldUpdate(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd6", "Guard needs field", nil) + + env.setFlags(updateCmd, map[string]string{ + "if-status": "open", + "add-label": "x", + }) + res := env.run(updateCmd, "test-upd6") + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1; stderr=%s", res.exitCode, res.stderr) + } + const want = "Error: --if-assignee/--if-status require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard\n" + if res.stderr != want { + t.Errorf("stderr = %q, want %q", res.stderr, want) + } + if got := env.store.mutations(); len(got) != 0 { + t.Errorf("store mutations = %v, want none (rejected pre-write)", got) + } +} + +// TestParityUpdateGuardsRejectClaim pins the third pre-write short-circuit +// (cmd/bd/update.go:785-787): guards combined with --claim exit 1 before any +// write. +func TestParityUpdateGuardsRejectClaim(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd7", "Guard vs claim", nil) + + env.setFlags(updateCmd, map[string]string{ + "if-status": "open", + "claim": "true", + "priority": "1", + }) + res := env.run(updateCmd, "test-upd7") + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1; stderr=%s", res.exitCode, res.stderr) + } + const want = "Error: cannot combine --if-assignee/--if-status with --claim (--claim is already an atomic compare-and-set)\n" + if res.stderr != want { + t.Errorf("stderr = %q, want %q", res.stderr, want) + } + if got := env.store.mutations(); len(got) != 0 { + t.Errorf("store mutations = %v, want none (rejected pre-write)", got) + } +} + +// TestParityUpdateGuardMismatchExits13 pins the bd-wsqvw exit contract: +// when EVERY failure is a stale --if-assignee/--if-status guard, the command +// exits ExitGuardMismatch (13), not 1 — nothing was written and retrying is +// pointless. Source: cmd/bd/update.go:665 (const), :690-731 +// (reportUpdateFailures). +func TestParityUpdateGuardMismatchExits13(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd8", "Guard mismatch", func(i *types.Issue) { + i.Assignee = "someone-else" + }) + + env.setFlags(updateCmd, map[string]string{ + "if-assignee": "not-the-holder", + "priority": "1", + }) + res := env.run(updateCmd, "test-upd8") + if res.exitCode != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstderr:\n%s", res.exitCode, ExitGuardMismatch, res.stderr) + } + if !strings.Contains(res.stderr, "assignee mismatch") { + t.Errorf("stderr lacks the machine-greppable %q sentinel:\n%s", "assignee mismatch", res.stderr) + } + if !strings.Contains(res.stderr, "Error: 1 of 1 issues failed to update") { + t.Errorf("stderr lacks the per-ID failure summary:\n%s", res.stderr) + } + if got := env.get("test-upd8").Priority; got != 2 { + t.Errorf("priority = %d; a refused guard must write nothing (seeded 2)", got) + } + if got := env.lastTouched(); got != "" { + t.Errorf("last-touched = %q; a wholly-failed update must not record one", got) + } +} + +// TestParityUpdateMixedFailureExits1 pins the other half of the same contract: +// a batch whose failures are NOT all guard mismatches exits 1, even though +// some IDs succeeded. Source: cmd/bd/update.go:721-731. +func TestParityUpdateMixedFailureExits1(t *testing.T) { + env := newParityEnv(t) + env.seed("test-upd9", "Real", nil) + + env.setFlags(updateCmd, map[string]string{"priority": "1"}) + res := env.run(updateCmd, "test-upd9", "test-nonexistent-zz") + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstderr:\n%s", res.exitCode, res.stderr) + } + if !strings.Contains(res.stderr, "Error: 1 of 2 issues failed to update") { + t.Errorf("stderr lacks the partial-batch summary:\n%s", res.stderr) + } + // The successful half stays applied — updates are per-ID, not atomic. + if got := env.get("test-upd9").Priority; got != 1 { + t.Errorf("priority = %d, want 1; successful IDs in a partial batch stay applied", got) + } + if got := env.lastTouched(); got != "test-upd9" { + t.Errorf("last-touched = %q, want %q", got, "test-upd9") + } +} + +// TestParityUpdateJSONFailureReport pins the --json failure envelope: stdout +// keeps the plain array of successfully updated issues while the per-ID +// failure report is a single compact JSON line — the LAST line on stderr — +// carrying "error", "failed", "schema_version", and a per-failure +// "guard_mismatch" marker. Source: cmd/bd/update.go:690-732. +func TestParityUpdateJSONFailureReport(t *testing.T) { + env := newParityEnv(t) + env.seed("test-updjf", "Guard mismatch json", func(i *types.Issue) { + i.Assignee = "someone-else" + }) + + jsonOutput = true + env.setFlags(updateCmd, map[string]string{ + "if-assignee": "not-the-holder", + "priority": "1", + }) + res := env.run(updateCmd, "test-updjf") + + if res.exitCode != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstderr:\n%s", res.exitCode, ExitGuardMismatch, res.stderr) + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty (no issue was updated)", res.stdout) + } + + lines := strings.Split(strings.TrimRight(res.stderr, "\n"), "\n") + report := lines[len(lines)-1] + var payload struct { + Error string `json:"error"` + SchemaVersion int `json:"schema_version"` + Failed []struct { + ID string `json:"id"` + Error string `json:"error"` + GuardMismatch bool `json:"guard_mismatch"` + } `json:"failed"` + } + if err := json.Unmarshal([]byte(report), &payload); err != nil { + t.Fatalf("last stderr line is not the JSON failure report: %v\nline: %s\nstderr:\n%s", err, report, res.stderr) + } + if payload.Error != "1 of 1 issues failed to update" { + t.Errorf("error = %q, want %q", payload.Error, "1 of 1 issues failed to update") + } + if payload.SchemaVersion != JSONSchemaVersion { + t.Errorf("schema_version = %d, want %d", payload.SchemaVersion, JSONSchemaVersion) + } + if len(payload.Failed) != 1 { + t.Fatalf("failed entries = %d, want 1", len(payload.Failed)) + } + if payload.Failed[0].ID != "test-updjf" { + t.Errorf("failed[0].id = %q, want %q", payload.Failed[0].ID, "test-updjf") + } + if !payload.Failed[0].GuardMismatch { + t.Error("failed[0].guard_mismatch = false; a stale --if-assignee must be marked") + } +} + +// TestParityUpdateCompoundSideEffectSurface pins RULING R2 as adopted: a +// compound `bd update` is ONE atomic operation, so exactly one on_update hook +// fires for the whole command instead of one per edit group. +// +// Before the rewire this made one store call per edit group — the field +// UPDATE, then each label add/remove — firing three hooks for this command. +// Source of the new behavior: cmd/bd/update.go's single ops.Update call -> +// internal/storage/issueops/execution.go ExecuteUpdate. +// +// The label events themselves are unchanged here because both edits are real +// deltas; the no-op case is TestParityUpdateNoOpLabelEditIsSilent. +func TestParityUpdateCompoundSideEffectSurface(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cmp1", "Compound update", func(i *types.Issue) { + i.Labels = []string{"keep"} + }) + before := env.eventTypes("test-cmp1") + baseAdded := countOf(before, string(types.EventLabelAdded)) + baseRemoved := countOf(before, string(types.EventLabelRemoved)) + + env.setFlags(updateCmd, map[string]string{ + "status": "in_progress", + "add-label": "added", + "remove-label": "keep", + }) + res := env.run(updateCmd, "test-cmp1") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + // RULING R2: one atomic operation => one on_update hook firing. + got := env.store.mutations() + want := []string{"Update"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("operations = %v, want %v (one hook firing)", got, want) + } + + // Real label deltas still emit their own events on top of the update. + after := env.eventTypes("test-cmp1") + if n := countOf(after, string(types.EventLabelAdded)) - baseAdded; n != 1 { + t.Errorf("new label_added events = %d, want 1 (events: %v)", n, after) + } + if n := countOf(after, string(types.EventLabelRemoved)) - baseRemoved; n != 1 { + t.Errorf("new label_removed events = %d, want 1 (events: %v)", n, after) + } + if len(after) <= len(before) { + t.Errorf("event count did not grow: before=%d after=%d (%v)", len(before), len(after), after) + } +} + +// TestParityUpdateNoOpLabelEditIsSilent pins the delta-only half of RULING R2 +// as adopted: adding a label the issue ALREADY has, and removing one it does +// NOT have, write no events at all. +// +// Before the rewire both no-ops emitted label_added/label_removed events +// describing changes that never happened, because the per-label store calls +// inserted their event unconditionally +// (internal/storage/issueops/labels.go). The facade diffs the label set first +// (internal/storage/issueops/aggregate.go ApplyLabelPatch). +func TestParityUpdateNoOpLabelEditIsSilent(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cmp2", "No-op labels", nil) + if err := env.store.inner.AddLabel(rootCtx, "test-cmp2", "present", "parity-seed"); err != nil { + t.Fatalf("seed label: %v", err) + } + env.store.reset() + baseAdded := countOf(env.eventTypes("test-cmp2"), string(types.EventLabelAdded)) + baseRemoved := countOf(env.eventTypes("test-cmp2"), string(types.EventLabelRemoved)) + + env.setFlags(updateCmd, map[string]string{ + "add-label": "present", + "remove-label": "absent", + }) + res := env.run(updateCmd, "test-cmp2") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + // RULING R2: neither no-op produces an event. + after := env.eventTypes("test-cmp2") + if n := countOf(after, string(types.EventLabelAdded)) - baseAdded; n != 0 { + t.Errorf("label_added events = %d, want 0 (re-adding an existing label changes nothing)", n) + } + if n := countOf(after, string(types.EventLabelRemoved)) - baseRemoved; n != 0 { + t.Errorf("label_removed events = %d, want 0 (removing an absent label changes nothing)", n) + } + // The label set itself is untouched. + labels, err := env.store.inner.GetLabels(rootCtx, "test-cmp2") + if err != nil { + t.Fatalf("GetLabels: %v", err) + } + if strings.Join(labels, ",") != "present" { + t.Errorf("labels = %v, want [present]", labels) + } +} + +// TestParityUpdateBareClaimFiresUpdateHook pins the last R2 asymmetry as +// closed: a bare `--claim` is an ordinary update operation, so it fires the +// on_update hook like every other `bd update`. +// +// Before the rewire it went through ClaimIssue, a method +// storage.HookFiringStore does not decorate, so a claim was the one update +// that fired no hook at all. +func TestParityUpdateBareClaimFiresUpdateHook(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cmp3", "Bare claim", nil) + + env.setFlags(updateCmd, map[string]string{"claim": "true"}) + res := env.run(updateCmd, "test-cmp3") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + // RULING R2: one operation, and it fires the update hook. + got := env.store.mutations() + if strings.Join(got, ",") != "Update" { + t.Errorf("operations = %v, want [Update] (one hook firing)", got) + } + claimed := env.get("test-cmp3") + if claimed.Assignee != actor { + t.Errorf("assignee = %q, want %q", claimed.Assignee, actor) + } + if claimed.Status != types.StatusInProgress { + t.Errorf("status = %q, want in_progress", claimed.Status) + } +} + +// TestParityUpdateParentReplacesAllEdges pins RULING R3 as adopted: `bd update +// --parent` replaces EVERY existing parent-child edge with the requested one, +// atomically, in the same operation as the rest of the update. +// +// Before the rewire it removed only the FIRST parent-child edge it found and +// then added the new one across three separate transactions, leaving a +// two-parent issue with a stale parent AND the new one — a silently corrupted +// hierarchy. Source of the new behavior: +// internal/storage/issueops/aggregate.go ApplyParentPatch. +func TestParityUpdateParentReplacesAllEdges(t *testing.T) { + env := newParityEnv(t) + env.seed("test-par1", "Parent one", nil) + env.seed("test-par2", "Parent two", nil) + env.seed("test-par3", "Parent three", nil) + child := env.seed("test-par9", "Child", nil) + + for _, parent := range []string{"test-par1", "test-par2"} { + dep := &types.Dependency{IssueID: child.ID, DependsOnID: parent, Type: types.DepParentChild} + if err := env.store.inner.AddDependency(rootCtx, dep, "parity-seed"); err != nil { + t.Fatalf("seed parent edge %s: %v", parent, err) + } + } + env.store.reset() + + env.setFlags(updateCmd, map[string]string{"parent": "test-par3"}) + res := env.run(updateCmd, child.ID) + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + records, err := env.store.inner.GetDependencyRecords(rootCtx, child.ID) + if err != nil { + t.Fatalf("GetDependencyRecords: %v", err) + } + var parents []string + for _, dep := range records { + if dep.Type == types.DepParentChild { + parents = append(parents, dep.DependsOnID) + } + } + + // RULING R3: both old edges are gone; the requested parent is the only one. + if strings.Join(parents, ",") != "test-par3" { + t.Errorf("parent edges after reparent = %v, want [test-par3] (replace-all)", parents) + } + + // RULING R2/R3: the reparent rides the same single operation as the rest + // of the update, so it is one hook firing, not two store calls. + got := env.store.mutations() + want := []string{"Update"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("operations = %v, want %v (one hook firing)", got, want) + } +} + +// ===== bd close ===== + +// TestParityCloseJSONShape pins `bd close --json`: a JSON ARRAY of re-read +// issues in struct-field order with no schema_version wrapper — the same +// container shape as update, and the opposite of create. +// Source: cmd/bd/close.go:222 (re-fetch) and :340-353 (outputJSON). +func TestParityCloseJSONShape(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cls1", "Close json shape", nil) + + jsonOutput = true + env.setFlags(closeCmd, map[string]string{"reason": "done here"}) + res := env.run(closeCmd, "test-cls1") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + if !strings.HasPrefix(res.stdout, "[\n {") { + t.Errorf("close --json is not a 2-space-indented array: %q", firstLine(res.stdout, 2)) + } + arr := decodeJSONArray(t, res.stdout) + if len(arr) != 1 { + t.Fatalf("array length = %d, want 1", len(arr)) + } + if _, ok := arr[0]["schema_version"]; ok { + t.Error("close --json array elements carry schema_version; today slices are unwrapped") + } + if arr[0]["status"] != string(types.StatusClosed) { + t.Errorf("status = %v, want closed", arr[0]["status"]) + } + // A re-read close DOES carry closed_at and close_reason. + closedAt, _ := arr[0]["closed_at"].(string) + if closedAt == "" { + t.Fatal("close --json omitted closed_at") + } + assertRecentUTCTimestamp(t, "closed_at", closedAt) + if arr[0]["close_reason"] != "done here" { + t.Errorf("close_reason = %v, want %q", arr[0]["close_reason"], "done here") + } +} + +// TestParityCloseHumanOutput pins the human success line, byte for byte, and +// the default reason ("Closed") applied when no --reason is given. +// Source: cmd/bd/close.go:229 and :453-455. +func TestParityCloseHumanOutput(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cls2", "Close human output", nil) + + env.setFlags(closeCmd, nil) + res := env.run(closeCmd, "test-cls2") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + want := fmt.Sprintf("✓ Closed %s: Closed\n", formatFeedbackID("test-cls2", "Close human output")) + if res.stdout != want { + t.Errorf("stdout mismatch\n got: %q\nwant: %q", res.stdout, want) + } + if res.stderr != "" { + t.Errorf("stderr = %q, want empty on the happy path", res.stderr) + } + if !strings.HasPrefix(res.stdout, "✓ Closed ") { + t.Errorf("close's success line no longer starts with %q", "✓ Closed ") + } +} + +// TestParityCloseSetsLastTouched pins cmd/bd/close.go:251-253. +func TestParityCloseSetsLastTouched(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cls3", "Close last touched", nil) + + env.setFlags(closeCmd, nil) + res := env.run(closeCmd, "test-cls3") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + if got := env.lastTouched(); got != "test-cls3" { + t.Errorf("last-touched = %q, want %q", got, "test-cls3") + } +} + +// TestParityCloseDefaultsToLastTouched pins cmd/bd/close.go:53-60: with no +// positional IDs, close targets the last-touched issue. +func TestParityCloseDefaultsToLastTouched(t *testing.T) { + env := newParityEnv(t) + env.seed("test-clslt", "Default close target", nil) + SetLastTouchedID("test-clslt") + + env.setFlags(closeCmd, nil) + res := env.run(closeCmd) + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + if got := env.get("test-clslt").Status; got != types.StatusClosed { + t.Errorf("status = %q, want closed; bare `bd close` must target last-touched", got) + } +} + +// TestParityCloseNoIDAndNoLastTouchedExits1 pins the other half +// (cmd/bd/close.go:54-59). +func TestParityCloseNoIDAndNoLastTouchedExits1(t *testing.T) { + env := newParityEnv(t) + env.clearLastTouched() + + env.setFlags(closeCmd, nil) + res := env.run(closeCmd) + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstderr:\n%s", res.exitCode, res.stderr) + } + const want = "Error: no issue ID provided and no last touched issue\n" + if res.stderr != want { + t.Errorf("stderr = %q, want %q", res.stderr, want) + } +} + +// TestParityClosePartialFailureExitsZero pins the close exit contract's +// permissive half (cmd/bd/close.go:377-380): as long as ONE id settled as +// closed, a batch with refused ids still exits 0. The refusal is reported on +// stderr only. +func TestParityClosePartialFailureExitsZero(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cls4", "Closable", nil) + env.seed("test-cls5", "Owned by another actor", func(i *types.Issue) { + i.Assignee = "someone-else" + }) + + env.setFlags(closeCmd, nil) + res := env.run(closeCmd, "test-cls4", "test-cls5") + + if res.exitCode != 0 { + t.Fatalf("exit = %d, want 0 (partial failure is still success today)\nstderr:\n%s", res.exitCode, res.stderr) + } + wantErr := fmt.Sprintf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override\n", + "test-cls5", "someone-else", actor) + if res.stderr != wantErr { + t.Errorf("stderr = %q, want %q", res.stderr, wantErr) + } + if env.get("test-cls4").Status != types.StatusClosed { + t.Error("the closable ID was not closed") + } + if env.get("test-cls5").Status == types.StatusClosed { + t.Error("the refused ID must not have been closed") + } + // The one that DID close still drives the post-close contracts. + if got := env.lastTouched(); got != "test-cls4" { + t.Errorf("last-touched = %q, want %q", got, "test-cls4") + } +} + +// TestParityCloseNothingSettledExits1 pins the strict half of the same +// contract: when NO id settled as closed, close returns SilentExit() — exit 1 +// with no extra stdout. Source: cmd/bd/close.go:377-380 and +// cmd/bd/errors.go:119-121. +func TestParityCloseNothingSettledExits1(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cls6", "Owned by another actor", func(i *types.Issue) { + i.Assignee = "someone-else" + }) + + env.setFlags(closeCmd, nil) + res := env.run(closeCmd, "test-cls6") + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstderr:\n%s", res.exitCode, res.stderr) + } + if env.get("test-cls6").Status == types.StatusClosed { + t.Error("the refused ID must not have been closed") + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty (SilentExit prints nothing itself)", res.stdout) + } + if got := env.lastTouched(); got != "" { + t.Errorf("last-touched = %q, want it untouched when nothing settled", got) + } +} + +// TestParityCloseAlreadyClosedIsIdempotentSuccess pins the re-close no-op: +// exit 0, the issue still reported on stdout, last-touched still recorded, and +// NO second close event. Source: cmd/bd/close.go:167-195. +func TestParityCloseAlreadyClosedIsIdempotentSuccess(t *testing.T) { + env := newParityEnv(t) + env.seed("test-cls7", "Already closed", nil) + + env.setFlags(closeCmd, nil) + if res := env.run(closeCmd, "test-cls7"); res.exitCode != 0 { + t.Fatalf("first close failed: exit=%d stderr=%s", res.exitCode, res.stderr) + } + closedEventsAfterFirst := countOf(env.eventTypes("test-cls7"), string(types.EventClosed)) + env.clearLastTouched() + env.store.reset() + + res := env.run(closeCmd, "test-cls7") + if res.exitCode != 0 { + t.Fatalf("re-close exit = %d, want 0\nstderr:\n%s", res.exitCode, res.stderr) + } + if !strings.HasPrefix(res.stdout, "✓ Closed ") { + t.Errorf("re-close stdout = %q; today an already-closed re-close still reports success", res.stdout) + } + if got := env.lastTouched(); got != "test-cls7" { + t.Errorf("last-touched = %q, want %q (retry-safe post-close contract)", got, "test-cls7") + } + if n := countOf(env.eventTypes("test-cls7"), string(types.EventClosed)); n != closedEventsAfterFirst { + t.Errorf("closed events = %d, want %d (a re-close must add none)", n, closedEventsAfterFirst) + } +} + +// ===== bd reopen ===== + +// TestParityReopenJSONShape pins `bd reopen --json`: a JSON ARRAY of re-read +// issues, no schema_version — same container as update/close. +// Source: cmd/bd/reopen.go:72-76 and :101-105. +func TestParityReopenJSONShape(t *testing.T) { + env := newParityEnv(t) + env.seed("test-rop1", "Reopen json shape", func(i *types.Issue) { + i.Status = types.StatusClosed + }) + + jsonOutput = true + env.setFlags(reopenCmd, map[string]string{"reason": "back to work"}) + res := env.run(reopenCmd, "test-rop1") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + + if !strings.HasPrefix(res.stdout, "[\n {") { + t.Errorf("reopen --json is not a 2-space-indented array: %q", firstLine(res.stdout, 2)) + } + arr := decodeJSONArray(t, res.stdout) + if len(arr) != 1 { + t.Fatalf("array length = %d, want 1", len(arr)) + } + if _, ok := arr[0]["schema_version"]; ok { + t.Error("reopen --json array elements carry schema_version; today slices are unwrapped") + } + if arr[0]["status"] != string(types.StatusOpen) { + t.Errorf("status = %v, want open", arr[0]["status"]) + } + if _, ok := arr[0]["closed_at"]; ok { + t.Error("reopen --json still carries closed_at; the engine clears it") + } +} + +// TestParityReopenHumanOutput pins the human line, byte for byte, including +// the ": " suffix. Source: cmd/bd/reopen.go:78-83. +func TestParityReopenHumanOutput(t *testing.T) { + env := newParityEnv(t) + env.seed("test-rop2", "Reopen human", func(i *types.Issue) { i.Status = types.StatusClosed }) + + env.setFlags(reopenCmd, map[string]string{"reason": "needs more"}) + res := env.run(reopenCmd, "test-rop2") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + const want = "↻ Reopened test-rop2: needs more\n" + if res.stdout != want { + t.Errorf("stdout mismatch\n got: %q\nwant: %q", res.stdout, want) + } + if res.stderr != "" { + t.Errorf("stderr = %q, want empty on the happy path", res.stderr) + } + if !strings.HasPrefix(res.stdout, "↻ Reopened ") { + t.Errorf("reopen's success line no longer starts with %q", "↻ Reopened ") + } +} + +// TestParityReopenHumanOutputNoReason pins the no-reason variant: no colon +// suffix, and NO title interpolation — unlike create/update/close, reopen +// prints the bare resolved ID. Source: cmd/bd/reopen.go:82. +func TestParityReopenHumanOutputNoReason(t *testing.T) { + env := newParityEnv(t) + env.seed("test-rop3", "A title that must not appear", func(i *types.Issue) { + i.Status = types.StatusClosed + }) + + env.setFlags(reopenCmd, nil) + res := env.run(reopenCmd, "test-rop3") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + const want = "↻ Reopened test-rop3\n" + if res.stdout != want { + t.Errorf("stdout mismatch\n got: %q\nwant: %q", res.stdout, want) + } +} + +// TestParityReopenDoesNotSetLastTouched pins an absence: unlike create, +// update and close, `bd reopen` never calls SetLastTouchedID. Nothing in +// cmd/bd/reopen.go does. +func TestParityReopenDoesNotSetLastTouched(t *testing.T) { + env := newParityEnv(t) + env.seed("test-rop4", "Reopen last touched", func(i *types.Issue) { i.Status = types.StatusClosed }) + + env.setFlags(reopenCmd, nil) + res := env.run(reopenCmd, "test-rop4") + if res.exitCode != 0 { + t.Fatalf("exit=%d err=%v stderr=%s", res.exitCode, res.err, res.stderr) + } + if got := env.lastTouched(); got != "" { + t.Errorf("last-touched = %q; bd reopen does not record one today", got) + } +} + +// TestParityReopenAlreadyOpenSkipsSilently pins the pre-read short-circuit at +// cmd/bd/reopen.go:59-63: an already-open issue reports on stderr, prints +// nothing on stdout, performs no store write, and does NOT set hasError — so +// the command exits 0. +func TestParityReopenAlreadyOpenSkipsSilently(t *testing.T) { + env := newParityEnv(t) + env.seed("test-rop5", "Already open", nil) + + env.setFlags(reopenCmd, nil) + res := env.run(reopenCmd, "test-rop5") + + if res.exitCode != 0 { + t.Fatalf("exit = %d, want 0\nstderr:\n%s", res.exitCode, res.stderr) + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty", res.stdout) + } + if res.stderr != "test-rop5 is already open\n" { + t.Errorf("stderr = %q, want %q", res.stderr, "test-rop5 is already open\n") + } + if got := env.store.mutations(); len(got) != 0 { + t.Errorf("store mutations = %v, want none", got) + } +} + +// TestParityReopenErrorExits1Silently pins the failure exit: any per-ID error +// sets hasError, and the command returns SilentExit() — exit 1 with the +// diagnosis on stderr only. Source: cmd/bd/reopen.go:50-53, :107-109. +func TestParityReopenErrorExits1Silently(t *testing.T) { + env := newParityEnv(t) + + env.setFlags(reopenCmd, nil) + res := env.run(reopenCmd, "test-nonexistent-zz") + + if res.exitCode != 1 { + t.Fatalf("exit = %d, want 1\nstderr:\n%s", res.exitCode, res.stderr) + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty (SilentExit prints nothing itself)", res.stdout) + } + if !strings.HasPrefix(res.stderr, "Error resolving test-nonexistent-zz: ") { + t.Errorf("stderr = %q, want the \"Error resolving : \" prefix", res.stderr) + } +} + +// TestParityReopenNonDoneStatusReportsNothingToDo pins RULING R4 as adopted: +// reopening an issue whose status is neither done nor open reports that there +// was nothing to do and fires no hook. +// +// Before the rewire the engine already no-opped +// (internal/storage/issueops/reopen.go returns Changed=false for a non-done +// category) but the CLI still called ReopenIssue — firing an on_update hook — +// printed "↻ Reopened" and exited 0, so the success report was a lie about a +// status that never moved. +// +// The message goes to stderr, exactly like the already-open skip above: both +// are "nothing to do" reports, and neither issue appears in --json output. +func TestParityReopenNonDoneStatusReportsNothingToDo(t *testing.T) { + env := newParityEnv(t) + env.seed("test-rop6", "In progress", func(i *types.Issue) { + i.Status = types.StatusInProgress + }) + + env.setFlags(reopenCmd, nil) + res := env.run(reopenCmd, "test-rop6") + + // RULING R4: still exit 0 — this is not an error, just a no-op. + if res.exitCode != 0 { + t.Fatalf("exit = %d, want 0\nstderr:\n%s", res.exitCode, res.stderr) + } + if res.stdout != "" { + t.Errorf("stdout = %q, want empty (nothing was reopened)", res.stdout) + } + const wantErr = "test-rop6 is not closed (status: in_progress); nothing to do\n" + if res.stderr != wantErr { + t.Errorf("stderr = %q, want %q", res.stderr, wantErr) + } + // RULING R4: and no hook fires, because no operation reported a change. + if got := env.store.mutations(); len(got) != 0 { + t.Errorf("operations = %v, want none recorded (a no-op reopen fires no hook)", got) + } + // The status is still what it was. + if got := env.get("test-rop6").Status; got != types.StatusInProgress { + t.Errorf("status = %q, want in_progress (the engine no-ops)", got) + } +} + +// ===== small helpers ===== + +func firstLine(s string, n int) string { + lines := strings.SplitN(s, "\n", n+1) + if len(lines) > n { + lines = lines[:n] + } + return strings.Join(lines, "\n") +} + +func isSortedStrings(s []string) bool { + for i := 1; i < len(s); i++ { + if s[i] < s[i-1] { + return false + } + } + return true +} diff --git a/go.mod b/go.mod index 3d98e318e..79040fa5a 100644 --- a/go.mod +++ b/go.mod @@ -137,7 +137,7 @@ require ( github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2 // indirect github.com/dolthub/fslock v0.0.5 // indirect github.com/dolthub/go-icu-regex v0.0.0-20260610153742-72563bc7ca83 // indirect - github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3 // indirect + github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3 github.com/dolthub/gozstd v0.0.0-20240423170813-23a2903bca63 // indirect github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037 // indirect github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71 // indirect diff --git a/internal/jira/tracker_test.go b/internal/jira/tracker_test.go index d8e85cddd..7397bc790 100644 --- a/internal/jira/tracker_test.go +++ b/internal/jira/tracker_test.go @@ -16,6 +16,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/tracker" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" ) func TestRegistered(t *testing.T) { @@ -629,6 +630,9 @@ func (s *configStore) GetAllConfig(_ context.Context) (map[string]string, error) } // Storage interface stubs — not exercised by Init(). +func (s *configStore) IssueLifecycle() (issueops.Lifecycle, error) { + return nil, &storage.ErrUnsupported{Op: "IssueLifecycle", Backend: "jira-config-stub"} +} func (s *configStore) SetConfig(_ context.Context, _, _ string) error { return nil } func (s *configStore) SetLocalMetadata(_ context.Context, _, _ string) error { return nil } func (s *configStore) GetLocalMetadata(_ context.Context, _ string) (string, error) { diff --git a/internal/storage/batch.go b/internal/storage/batch.go index 20b21ab51..9cb022fd2 100644 --- a/internal/storage/batch.go +++ b/internal/storage/batch.go @@ -18,6 +18,9 @@ const ( // BatchCreateOptions contains options for batch issue creation. // This is a backend-agnostic type that can be used by any storage implementation. type BatchCreateOptions struct { + // CreateOnly uses strict insert semantics after the caller has reserved the + // issue ID. It is for guarded public creates; import behavior is unchanged. + CreateOnly bool // OrphanHandling specifies how to handle issues with missing parent references OrphanHandling OrphanHandling // SkipPrefixValidation skips prefix validation for existing IDs (used during import) diff --git a/internal/storage/conformance/audit_issue-lifecycle.go b/internal/storage/conformance/audit_issue-lifecycle.go index 5d72ebeee..2483a1b62 100644 --- a/internal/storage/conformance/audit_issue-lifecycle.go +++ b/internal/storage/conformance/audit_issue-lifecycle.go @@ -32,7 +32,7 @@ func auditCountEventType(events []*types.Event, want types.EventType) int { func RunAudit_issue_lifecycle(t *testing.T, f Factory) { t.Helper() t.Run("CloseIdempotentKeepsFirstReason", func(t *testing.T) { testAuditCloseIdempotentKeepsFirstReason(t, f) }) - t.Run("ReopenOnOpenMintsEvent", func(t *testing.T) { testAuditReopenOnOpenMintsEvent(t, f) }) + t.Run("ReopenEventSemantics", func(t *testing.T) { testAuditReopenEventSemantics(t, f) }) t.Run("ReopenNotFoundIsSentinel", func(t *testing.T) { testAuditReopenNotFoundIsSentinel(t, f) }) t.Run("DeleteIssuesBatchModes", func(t *testing.T) { testAuditDeleteIssuesBatchModes(t, f) }) t.Run("DeleteIssuesDryRunCounts", func(t *testing.T) { testAuditDeleteIssuesDryRunCounts(t, f) }) @@ -80,22 +80,29 @@ func testAuditCloseIdempotentKeepsFirstReason(t *testing.T, f Factory) { } } -// Reopening an already-open issue mints a status_changed event on the reference -// (ReopenIssue -> UpdateIssue always records an event). -func testAuditReopenOnOpenMintsEvent(t *testing.T, f Factory) { +// Reopening an already-open issue is a strict no-op. Reopening the same issue +// after a genuine close mints exactly one reopened event. +func testAuditReopenEventSemantics(t *testing.T, f Factory) { s := f(t) must(t, s.CreateIssue(ctx(), withDefaults(&types.Issue{ID: "ro-1", Title: "T", Status: types.StatusOpen}), "a")) before, err := s.GetEvents(ctx(), "ro-1", 0) must(t, err) - // reason="" so no comment is added; only the status update event should appear. must(t, s.ReopenIssue(ctx(), "ro-1", "", "a")) after, err := s.GetEvents(ctx(), "ro-1", 0) must(t, err) - if len(after) != len(before)+1 { - t.Errorf("events after reopen-on-open = %d, want %d (one new event)", len(after), len(before)+1) + if len(after) != len(before) { + t.Errorf("events after reopen-on-open = %d, want %d (strict no-op)", len(after), len(before)) + } + + must(t, s.CloseIssue(ctx(), "ro-1", "done", "a", "session")) + must(t, s.ReopenIssue(ctx(), "ro-1", "", "a")) + afterClosedReopen, err := s.GetEvents(ctx(), "ro-1", 0) + must(t, err) + if n := auditCountEventType(afterClosedReopen, types.EventReopened); n != 1 { + t.Errorf("EventReopened count after closed reopen = %d, want 1", n) } } diff --git a/internal/storage/conformance/issue_operations_contract.go b/internal/storage/conformance/issue_operations_contract.go new file mode 100644 index 000000000..6b2a80ce8 --- /dev/null +++ b/internal/storage/conformance/issue_operations_contract.go @@ -0,0 +1,286 @@ +package conformance + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the behavior contract every implementation of +// publicops.Lifecycle must satisfy, independent of how it reaches storage. +// There are three of them — the direct store, the embedded store, and the +// unit-of-work backend — and the first two share an execution path the third +// does not. Behavior asserted only against one backend has repeatedly drifted +// on the others, so each of these runs against all three from one spec. + +// RunIssueOperationsCreateRoutesInfraTypesToWisps pins the facade create +// against the same infra-type routing the stores' own CreateIssue applies: a +// configured infra type is ephemeral and lives in the wisp tables, never in +// issues. +func RunIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + for key, value := range map[string]string{"types.custom": "agent", "types.infra": "agent"} { + if err := fixture.SetConfig(ctx, key, value); err != nil { + t.Fatalf("SetConfig(%s): %v", key, err) + } + } + + result, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + Issue: &types.Issue{Title: "infra bead", Status: types.StatusOpen, Priority: 2, IssueType: types.IssueType("agent")}, + }) + if err != nil { + t.Fatalf("Create: %v", err) + } + if !result.Issue.Ephemeral { + t.Errorf("create result Ephemeral = false, want true for infra type %q", result.Issue.IssueType) + } + assertIssueOperationsRowCount(t, ctx, fixture, "wisps", result.Issue.ID, 1) + assertIssueOperationsRowCount(t, ctx, fixture, "issues", result.Issue.ID, 0) + + // A no-history infra create keeps its no-history retention rather than + // being upgraded to ephemeral, matching CreateIssue. + noHistory, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + Issue: &types.Issue{Title: "infra no-history", Status: types.StatusOpen, Priority: 2, IssueType: types.IssueType("agent"), NoHistory: true}, + }) + if err != nil { + t.Fatalf("Create no-history: %v", err) + } + if noHistory.Issue.Ephemeral { + t.Errorf("no-history infra create Ephemeral = true, want false") + } + assertIssueOperationsRowCount(t, ctx, fixture, "wisps", noHistory.Issue.ID, 1) + assertIssueOperationsRowCount(t, ctx, fixture, "issues", noHistory.Issue.ID, 0) + + // A non-infra type is unaffected. + durable, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + Issue: &types.Issue{Title: "durable bead", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + }) + if err != nil { + t.Fatalf("Create durable: %v", err) + } + if durable.Issue.Ephemeral { + t.Errorf("durable create Ephemeral = true, want false") + } + assertIssueOperationsRowCount(t, ctx, fixture, "issues", durable.Issue.ID, 1) + assertIssueOperationsRowCount(t, ctx, fixture, "wisps", durable.Issue.ID, 0) +} + +// RunIssueOperationsCreateRejectsMissingDependencyTargets pins the facade +// create against reporting success for an issue whose requested relationships +// were never written. The batch engine tolerates a dangling edge so a partial +// import still lands; a guarded single create must refuse the whole request +// with a typed error naming the target, and leave nothing behind. +func RunIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + seed := &types.Issue{ID: fixture.IssuePrefix + "-skipdep-seed", Title: "seed", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := fixture.CreateIssue(ctx, seed, "seed"); err != nil { + t.Fatalf("seed: %v", err) + } + + cases := []struct { + name string + id string + request publicops.CreateRequest + target string + }{ + { + name: "explicit dependency", + id: fixture.IssuePrefix + "-skipdep-explicit", + target: fixture.IssuePrefix + "-skipdep-missing-dep", + request: publicops.CreateRequest{ + Dependencies: []publicops.CreateDependency{{TargetID: fixture.IssuePrefix + "-skipdep-missing-dep", Type: types.DepBlocks}}, + }, + }, + { + name: "parent", + id: fixture.IssuePrefix + "-skipdep-parent", + target: fixture.IssuePrefix + "-skipdep-missing-parent", + request: publicops.CreateRequest{ParentID: fixture.IssuePrefix + "-skipdep-missing-parent"}, + }, + { + name: "waits-for spawner", + id: fixture.IssuePrefix + "-skipdep-waits", + target: fixture.IssuePrefix + "-skipdep-missing-spawner", + request: publicops.CreateRequest{ + WaitsFor: &publicops.WaitsFor{SpawnerID: fixture.IssuePrefix + "-skipdep-missing-spawner"}, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + request := tc.request + request.Actor = "writer" + request.ForceIDPrefix = true + request.Issue = &types.Issue{ID: tc.id, Title: tc.name, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + _, err := fixture.Operations.Create(ctx, request) + if err == nil { + t.Fatal("Create returned nil error, want a refusal for the missing dependency target") + } + if !errors.Is(err, publicops.ErrNotFound) { + t.Errorf("Create error = %v, want ErrNotFound", err) + } + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("Create error = %v, want ErrValidation", err) + } + if !strings.Contains(err.Error(), tc.target) { + t.Errorf("Create error = %v, want it to name the missing target %q", err, tc.target) + } + assertIssueOperationsRowCount(t, ctx, fixture, "issues", tc.id, 0) + assertIssueOperationsRowCount(t, ctx, fixture, "wisps", tc.id, 0) + }) + } + + // A create whose targets all exist is unaffected. + result, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{ID: fixture.IssuePrefix + "-skipdep-ok", Title: "ok", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + Dependencies: []publicops.CreateDependency{{TargetID: seed.ID, Type: types.DepBlocks}}, + }) + if err != nil { + t.Fatalf("Create with existing target: %v", err) + } + if len(result.Issue.Dependencies) != 1 || result.Issue.Dependencies[0].DependsOnID != seed.ID { + t.Fatalf("Create result dependencies = %#v, want one edge to %s", result.Issue.Dependencies, seed.ID) + } +} + +// RunIssueOperationsUpdateFoldsMetadataIntoOneEvent pins a compound update to a +// single event. A guarded update is one atomic mutation, so its history must +// read as one entry; a metadata patch riding along with field edits must not +// write the row twice and fabricate a second event in the stream every history +// consumer sees. +func RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + issue := &types.Issue{ + ID: fixture.IssuePrefix + "-metadata-event", Title: "metadata event", Status: types.StatusOpen, + Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"old"}`), + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed: %v", err) + } + events := newIssueOperationsEventCounter(t, ctx, fixture, issue.ID) + + updated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress}, + Metadata: publicops.MetadataPatch{ + Set: map[string]json.RawMessage{"added": json.RawMessage(`"value"`)}, + }, + }}) + if err != nil { + t.Fatalf("compound update: %v", err) + } + if !updated.Changed || updated.Issue.Status != types.StatusInProgress { + t.Fatalf("compound update result = %#v", updated) + } + assertIssueOperationsMetadata(t, "compound update", updated.Issue.Metadata, `{"added":"value","keep":"old"}`) + events.assert(t, "compound update", 1, map[types.EventType]int{types.EventStatusChanged: 1, types.EventUpdated: 0}) + + // A metadata-only patch still records its own single event. + metadataOnly, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{ + Metadata: publicops.MetadataPatch{Unset: []string{"keep"}}, + }}) + if err != nil || !metadataOnly.Changed { + t.Fatalf("metadata-only update = %#v, %v", metadataOnly, err) + } + assertIssueOperationsMetadata(t, "metadata-only update", metadataOnly.Issue.Metadata, `{"added":"value"}`) + events.assert(t, "metadata-only update", 1, map[types.EventType]int{types.EventUpdated: 1}) + + // A metadata patch that changes nothing stays elided. + noOp, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{ + Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"added": json.RawMessage(`"value"`)}}, + }}) + if err != nil || noOp.Changed { + t.Fatalf("no-op metadata update = %#v, %v", noOp, err) + } + events.assert(t, "no-op metadata update", 0, nil) +} + +func assertIssueOperationsRowCount(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, table, id string, want int) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's hardcoded table names + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM "+table+" WHERE id = ?", []any{id}, &got); err != nil { + t.Fatalf("count %s rows for %s: %v", table, id, err) + } + if got != want { + t.Errorf("%s rows for %s = %d, want %d", table, id, got, want) + } +} + +func assertIssueOperationsMetadata(t *testing.T, label string, got json.RawMessage, want string) { + t.Helper() + var gotValue, wantValue any + if err := json.Unmarshal(got, &gotValue); err != nil { + t.Fatalf("%s metadata %s: %v", label, got, err) + } + if err := json.Unmarshal([]byte(want), &wantValue); err != nil { + t.Fatalf("%s want metadata %s: %v", label, want, err) + } + if !reflect.DeepEqual(gotValue, wantValue) { + t.Fatalf("%s metadata = %s, want %s", label, got, want) + } +} + +// issueOperationsEventCounter reports how many event rows each operation adds +// for one issue. +type issueOperationsEventCounter struct { + ctx context.Context + fixture IssueOperationsStagingFixture + id string + total int + byType map[types.EventType]int +} + +func newIssueOperationsEventCounter(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id string) *issueOperationsEventCounter { + t.Helper() + counter := &issueOperationsEventCounter{ctx: ctx, fixture: fixture, id: id, byType: map[types.EventType]int{}} + counter.total = counter.count(t, "") + for _, eventType := range []types.EventType{types.EventUpdated, types.EventStatusChanged} { + counter.byType[eventType] = counter.count(t, eventType) + } + return counter +} + +func (c *issueOperationsEventCounter) count(t *testing.T, eventType types.EventType) int { + t.Helper() + query := "SELECT COUNT(*) FROM events WHERE issue_id = ?" + args := []any{c.id} + if eventType != "" { + query += " AND event_type = ?" + args = append(args, string(eventType)) + } + var got int + if err := c.fixture.QueryScalar(c.ctx, query, args, &got); err != nil { + t.Fatalf("count events for %s (%q): %v", c.id, eventType, err) + } + return got +} + +// assert checks the rows added since the previous assert and re-baselines. +func (c *issueOperationsEventCounter) assert(t *testing.T, label string, wantTotal int, wantByType map[types.EventType]int) { + t.Helper() + total := c.count(t, "") + if got := total - c.total; got != wantTotal { + t.Errorf("%s wrote %d event rows, want %d", label, got, wantTotal) + } + c.total = total + for eventType, want := range wantByType { + current := c.count(t, eventType) + if got := current - c.byType[eventType]; got != want { + t.Errorf("%s wrote %d %q events, want %d", label, got, eventType, want) + } + } + for _, eventType := range []types.EventType{types.EventUpdated, types.EventStatusChanged} { + c.byType[eventType] = c.count(t, eventType) + } +} diff --git a/internal/storage/conformance/issue_operations_staging.go b/internal/storage/conformance/issue_operations_staging.go new file mode 100644 index 000000000..f8ff29d9e --- /dev/null +++ b/internal/storage/conformance/issue_operations_staging.go @@ -0,0 +1,195 @@ +package conformance + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// IssueOperationsStagingFixture supplies adapter-specific storage access for +// the issue-operations assertions. Each Run function documents which fields it +// needs; an adapter supplies only those. +type IssueOperationsStagingFixture struct { + IssuePrefix string + Operations publicops.Lifecycle + CreateIssue func(context.Context, *types.Issue, string) error + AddDependency func(context.Context, *types.Dependency, string) error + GetReadyWork func(context.Context, types.WorkFilter) ([]*types.Issue, error) + SetConfig func(context.Context, string, string) error + Commit func(context.Context, string) error + Exec func(context.Context, string, ...any) error + QueryScalar func(context.Context, string, []any, ...any) error +} + +// RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables proves that a +// reverse nonblocking dependency commits its concrete dependency row without +// sweeping an unrelated dirty durable row into the same commit. +func RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + source := &types.Issue{ + ID: fixture.IssuePrefix + "-create-relates-source", + Title: "source", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + } + dirty := &types.Issue{ + ID: fixture.IssuePrefix + "-create-relates-dirty", + Title: "committed title", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + } + for _, issue := range []*types.Issue{source, dirty} { + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed issue %s: %v", issue.ID, err) + } + } + if err := fixture.Commit(ctx, "seed selective create staging"); err != nil { + t.Fatalf("commit seed state: %v", err) + } + if err := fixture.Exec(ctx, "UPDATE issues SET title = ? WHERE id = ?", "working title", dirty.ID); err != nil { + t.Fatalf("dirty unrelated issue: %v", err) + } + assertIssueOperationsScalar(t, ctx, fixture, "working dirty title", "working title", + "SELECT title FROM issues WHERE id = ?", []any{dirty.ID}) + assertIssueOperationsScalar(t, ctx, fixture, "committed dirty title before create", "committed title", + "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{dirty.ID}) + + created, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{ + Title: "generated wisp", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: true, + }, + Dependencies: []publicops.CreateDependency{{ + TargetID: source.ID, + Type: types.DepRelatesTo, + Reverse: true, + }}, + }) + if err != nil { + t.Fatalf("create generated wisp: %v", err) + } + if created.Issue == nil || created.Issue.ID == "" { + t.Fatalf("created issue = %#v, want generated wisp ID", created.Issue) + } + + assertIssueOperationsScalar(t, ctx, fixture, "committed reverse dependency", 1, + "SELECT COUNT(*) FROM dependencies AS OF 'HEAD' WHERE issue_id = ? AND depends_on_wisp_id = ? AND type = ?", + []any{source.ID, created.Issue.ID, types.DepRelatesTo}) + assertIssueOperationsScalar(t, ctx, fixture, "working source blocked state", false, + "SELECT is_blocked FROM issues WHERE id = ?", []any{source.ID}) + assertIssueOperationsScalar(t, ctx, fixture, "committed source blocked state", false, + "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{source.ID}) + assertIssueOperationsScalar(t, ctx, fixture, "working dirty title after create", "working title", + "SELECT title FROM issues WHERE id = ?", []any{dirty.ID}) + assertIssueOperationsScalar(t, ctx, fixture, "committed dirty title after create", "committed title", + "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{dirty.ID}) +} + +// RunIssueOperationsCreateParentChildRecomputesWaitsForClosure proves that +// creating an open child updates an existing waiter on the child's spawner in +// both the working set and committed readiness state. +func RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + spawner := &types.Issue{ + ID: fixture.IssuePrefix + "-create-spawner", + Title: "spawner", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + } + waiter := &types.Issue{ + ID: fixture.IssuePrefix + "-create-waiter", + Title: "waiter", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + } + for _, issue := range []*types.Issue{spawner, waiter} { + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed issue %s: %v", issue.ID, err) + } + } + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: waiter.ID, + DependsOnID: spawner.ID, + Type: types.DepWaitsFor, + }, "seed"); err != nil { + t.Fatalf("seed waits-for dependency: %v", err) + } + if err := fixture.Commit(ctx, "seed waits-for create closure"); err != nil { + t.Fatalf("commit seed state: %v", err) + } + assertIssueOperationsScalar(t, ctx, fixture, "working waiter before child create", false, + "SELECT is_blocked FROM issues WHERE id = ?", []any{waiter.ID}) + assertIssueOperationsScalar(t, ctx, fixture, "committed waiter before child create", false, + "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{waiter.ID}) + assertIssueOperationsReady(t, ctx, fixture, waiter.ID, true) + + created, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{ + Title: "open child", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + }, + ParentID: spawner.ID, + }) + if err != nil { + t.Fatalf("create open child: %v", err) + } + if created.Issue == nil || created.Issue.ID != spawner.ID+".1" { + t.Fatalf("created issue = %#v, want child %s.1", created.Issue, spawner.ID) + } + + assertIssueOperationsScalar(t, ctx, fixture, "committed parent-child dependency", 1, + "SELECT COUNT(*) FROM dependencies AS OF 'HEAD' WHERE issue_id = ? AND depends_on_issue_id = ? AND type = ?", + []any{created.Issue.ID, spawner.ID, types.DepParentChild}) + assertIssueOperationsScalar(t, ctx, fixture, "working waiter after child create", true, + "SELECT is_blocked FROM issues WHERE id = ?", []any{waiter.ID}) + assertIssueOperationsScalar(t, ctx, fixture, "committed waiter after child create", true, + "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{waiter.ID}) + assertIssueOperationsReady(t, ctx, fixture, waiter.ID, false) +} + +func assertIssueOperationsScalar[T comparable](t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, name string, want T, query string, args []any) { + t.Helper() + var got T + if err := fixture.QueryScalar(ctx, query, args, &got); err != nil { + t.Fatalf("%s: %v", name, err) + } + if got != want { + t.Fatalf("%s = %v, want %v", name, got, want) + } +} + +func assertIssueOperationsReady(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, issueID string, want bool) { + t.Helper() + ready, err := fixture.GetReadyWork(ctx, types.WorkFilter{}) + if err != nil { + t.Fatalf("get ready work: %v", err) + } + for _, issue := range ready { + if issue != nil && issue.ID == issueID { + if !want { + t.Fatalf("ready work contains %s, want absent", issueID) + } + return + } + } + if want { + t.Fatalf("ready work omits %s, want present", issueID) + } +} diff --git a/internal/storage/dberrors/errors.go b/internal/storage/dberrors/errors.go index 03d1cb213..3999eec44 100644 --- a/internal/storage/dberrors/errors.go +++ b/internal/storage/dberrors/errors.go @@ -40,3 +40,22 @@ func IsTableNotExist(err error) bool { quotedTableMissingPattern.MatchString(s) || unquotedTableMissingPattern.MatchString(s) } + +// IsMissingForeignKeyTarget reports whether err is the integrity-constraint +// violation a write hits when it references a row that does not exist: MySQL +// 1452 (ER_NO_REFERENCED_ROW_2) and its older 1216 (ER_NO_REFERENCED_ROW). +// It deliberately does not classify 1451 (ER_ROW_IS_REFERENCED_2), which is +// the opposite direction — deleting a row other rows still point at. +func IsMissingForeignKeyTarget(err error) bool { + if err == nil { + return false + } + + var mysqlErr *mysql.MySQLError + if errors.As(err, &mysqlErr) { + return mysqlErr.Number == 1452 || mysqlErr.Number == 1216 + } + + s := strings.ToLower(err.Error()) + return strings.Contains(s, "error 1452") || strings.Contains(s, "error 1216") +} diff --git a/internal/storage/dolt/claim_verify.go b/internal/storage/dolt/claim_verify.go index 637a694c6..c8015c533 100644 --- a/internal/storage/dolt/claim_verify.go +++ b/internal/storage/dolt/claim_verify.go @@ -48,12 +48,18 @@ type claimPostcondition struct { } func claimedBy(actor string) claimPostcondition { + return claimedAs(actor, types.StatusInProgress) +} + +// claimedAs is claimedBy for a claim whose request overrides the assignee or +// status the bare claim would have written. +func claimedAs(assignee string, status types.Status) claimPostcondition { return claimPostcondition{ op: "claim", - want: func(assignee string, status types.Status) bool { - return assignee == actor && status == types.StatusInProgress + want: func(gotAssignee string, gotStatus types.Status) bool { + return gotAssignee == assignee && gotStatus == status }, - desc: fmt.Sprintf("assignee=%q status=%q", actor, types.StatusInProgress), + desc: fmt.Sprintf("assignee=%q status=%q", assignee, status), } } diff --git a/internal/storage/dolt/close_issue_checked_test.go b/internal/storage/dolt/close_issue_checked_test.go index e23bac9c0..7531bf16a 100644 --- a/internal/storage/dolt/close_issue_checked_test.go +++ b/internal/storage/dolt/close_issue_checked_test.go @@ -1,10 +1,13 @@ package dolt import ( + "database/sql" "errors" "testing" "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/depid" + "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" ) @@ -414,6 +417,315 @@ func TestCloseIssueChecked(t *testing.T) { tc.check(t, id, res, err) }) } + + t.Run("open children refuse and force reports count", func(t *testing.T) { + parent, permanentChild, wispChild := "cic-children-parent", "cic-children-permanent", "cic-children-wisp" + blocker := "cic-children-blocker" + createPerm(t, ctx, store, parent) + createPerm(t, ctx, store, permanentChild) + createWisp(t, ctx, store, wispChild) + createPerm(t, ctx, store, blocker) + if err := store.AddDependency(ctx, &types.Dependency{IssueID: parent, DependsOnID: blocker, Type: types.DepBlocks}, "tester"); err != nil { + t.Fatalf("AddDependency(%s -> %s): %v", parent, blocker, err) + } + for _, child := range []string{permanentChild, wispChild} { + if err := store.AddDependency(ctx, &types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild}, "tester"); err != nil { + t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err) + } + } + res, err := store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "done"}) + var childErr *storage.CloseOpenChildrenError + if !errors.Is(err, storage.ErrCloseOpenChildren) || !errors.As(err, &childErr) || childErr.IssueID != parent || childErr.OpenChildren != 2 { + t.Fatalf("child error = %+v, err = %v; want typed refusal for %s with 2 children", childErr, err, parent) + } + if got, want := getStatus(t, parent), types.StatusOpen; got != want { + t.Fatalf("parent status after refusal = %q, want %q", got, want) + } + res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "override", Force: true}) + if err != nil || res.Unchanged || res.OpenChildren != 2 { + t.Fatalf("force result = %+v, err = %v; want changed close with 2 children", res, err) + } + res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "again"}) + if !errors.Is(err, storage.ErrCloseOpenChildren) { + t.Fatalf("non-force re-close error = %v, want ErrCloseOpenChildren", err) + } + res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "again", Force: true}) + if err != nil || !res.Unchanged || res.OpenChildren != 2 { + t.Fatalf("forced re-close result = %+v, err = %v; want unchanged with 2 children", res, err) + } + + wispParent, childOfWispParent := "cic-children-wisp-parent", "cic-children-wisp-parent-child" + createWisp(t, ctx, store, wispParent) + createPerm(t, ctx, store, childOfWispParent) + if err := store.AddDependency(ctx, &types.Dependency{IssueID: childOfWispParent, DependsOnID: wispParent, Type: types.DepParentChild}, "tester"); err != nil { + t.Fatalf("AddDependency(%s -> %s): %v", childOfWispParent, wispParent, err) + } + res, err = store.CloseIssueChecked(ctx, wispParent, "tester", storage.CloseIssueOptions{Reason: "done"}) + if !errors.Is(err, storage.ErrCloseOpenChildren) { + t.Fatalf("wisp parent close error = %v, want ErrCloseOpenChildren", err) + } + res, err = store.CloseIssueChecked(ctx, wispParent, "tester", storage.CloseIssueOptions{Reason: "override", Force: true}) + if err != nil || res.Unchanged || res.OpenChildren != 1 { + t.Fatalf("wisp parent force result = %+v, err = %v; want changed close with 1 child", res, err) + } + }) + + t.Run("duplicate durable and wisp child edge counts once", func(t *testing.T) { + parent, child := "cic-collision-parent", "cic-collision-child" + createPerm(t, ctx, store, parent) + createPerm(t, ctx, store, child) + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepParentChild, + }, "tester"); err != nil { + t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err) + } + if _, err := store.execContext(ctx, ` + INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, no_history) + VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?) + `, child, "wisp duplicate "+child, types.StatusOpen, 2, types.TypeTask, false, true); err != nil { + t.Fatalf("insert matching wisp child: %v", err) + } + + collisionID := depid.New(child, parent) + if _, err := store.db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_issue_id, type, created_by) VALUES (?, ?, ?, 'parent-child', 'tester')", + collisionID, child, parent); err != nil { + t.Fatalf("seed duplicate child edge: %v", err) + } + + res, err := store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "done"}) + var childErr *storage.CloseOpenChildrenError + if !errors.Is(err, storage.ErrCloseOpenChildren) || !errors.As(err, &childErr) || childErr.OpenChildren != 1 { + t.Fatalf("child error = %+v, err = %v; want typed refusal with 1 child", childErr, err) + } + res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "override", Force: true}) + if err != nil || res.Unchanged || res.OpenChildren != 1 { + t.Fatalf("force result = %+v, err = %v; want changed close with 1 child", res, err) + } + }) + + t.Run("durable dependency wins a cross-table type conflict", func(t *testing.T) { + parent, child := "cic-conflict-parent", "cic-conflict-child" + createPerm(t, ctx, store, parent) + createPerm(t, ctx, store, child) + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepRelated, + }, "tester"); err != nil { + t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err) + } + if _, err := store.execContext(ctx, ` + INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, no_history) + VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?) + `, child, "wisp duplicate "+child, types.StatusOpen, 2, types.TypeTask, false, true); err != nil { + t.Fatalf("insert matching wisp child: %v", err) + } + + collisionID := depid.New(child, parent) + if _, err := store.db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_issue_id, type, created_by) VALUES (?, ?, ?, 'parent-child', 'tester')", + collisionID, child, parent); err != nil { + t.Fatalf("seed conflicting child edge: %v", err) + } + + res, err := store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "done"}) + if err != nil || res.Unchanged || res.OpenChildren != 0 { + t.Fatalf("close result = %+v, err = %v; want changed close with no durable parent-child child", res, err) + } + }) + + t.Run("missing target precedes child count", func(t *testing.T) { + child, missing := "cic-dangling-child", "cic-dangling-parent" + createPerm(t, ctx, store, child) + if _, err := store.db.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 0"); err != nil { + t.Fatalf("disable FK checks: %v", err) + } + if _, err := store.db.ExecContext(ctx, "INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) VALUES (UUID(), ?, ?, 'parent-child', NOW(), 'tester')", child, missing); err != nil { + t.Fatalf("insert dangling parent-child edge: %v", err) + } + if _, err := store.db.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 1"); err != nil { + t.Fatalf("re-enable FK checks: %v", err) + } + _, err := store.CloseIssueChecked(ctx, missing, "tester", storage.CloseIssueOptions{Reason: "done"}) + if !errors.Is(err, storage.ErrNotFound) || errors.Is(err, storage.ErrCloseOpenChildren) { + t.Fatalf("err = %v, want ErrNotFound but not ErrCloseOpenChildren", err) + } + }) +} + +// TestCloseIssueCheckedParentChildInsertCannotPhantomMerge is a controlled +// two-transaction Dolt regression: a close which observes no children and a +// concurrently-created open parent-child edge must not both commit. If they do, +// the resulting durable state can preserve an overlapping stale-snapshot +// decision instead of forcing one writer to retry against the other. +func TestCloseIssueCheckedParentChildInsertCannotPhantomMerge(t *testing.T) { + store, cleanup := setupConcurrentTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + const ( + parent = "close-child-phantom-parent" + child = "close-child-phantom-child" + ) + createPerm(t, ctx, store, parent) + createPerm(t, ctx, store, child) + + // Deliberately start both transactions before either writes. The close reads + // zero children before txAdd inserts its edge; committing close first makes + // this interleaving deterministic rather than timing-dependent. + txClose, err := store.db.BeginTx(ctx, nil) + if err != nil { + t.Fatalf("begin close transaction: %v", err) + } + defer txClose.Rollback() // no-op after Commit; preserves cleanup on early Fatal. + txAdd, err := store.db.BeginTx(ctx, nil) + if err != nil { + t.Fatalf("begin add-child transaction: %v", err) + } + defer txAdd.Rollback() + + closeResult, err := issueops.CloseIssueCheckedInTx(ctx, txClose, parent, "done", "tester", "", false, nil) + if err != nil { + t.Fatalf("checked close before concurrent edge: %v", err) + } + if closeResult.OpenChildren != 0 || closeResult.AlreadyClosed { + t.Fatalf("close precondition result = %+v, want a real close after observing zero children", closeResult) + } + + if _, err := issueops.AddDependencyInTx(ctx, txAdd, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepParentChild, + }, "tester", issueops.AddDependencyOpts{}); err != nil { + t.Fatalf("insert concurrent parent-child edge: %v", err) + } + + closeCommitErr := txClose.Commit() + addCommitErr := txAdd.Commit() + t.Logf("controlled close/add commits: close=%v add=%v", closeCommitErr, addCommitErr) + if closeCommitErr == nil && addCommitErr == nil { + var parentStatus, childStatus string + if err := store.db.QueryRowContext(ctx, "SELECT status FROM issues WHERE id = ?", parent).Scan(&parentStatus); err != nil { + t.Fatalf("read parent after both commits: %v", err) + } + if err := store.db.QueryRowContext(ctx, "SELECT status FROM issues WHERE id = ?", child).Scan(&childStatus); err != nil { + t.Fatalf("read child after both commits: %v", err) + } + t.Fatalf("phantom parent-child merge: checked close and edge insert both committed (parent=%s child=%s); one transaction must conflict or be refused", parentStatus, childStatus) + } + + // A conflict on either commit is the required serialization outcome. Keep + // both errors in the failure below should a future Dolt version return an + // unexpected non-serialization result from a changed transaction contract. + if closeCommitErr != nil && !isSerializationError(closeCommitErr) { + t.Fatalf("close commit error = %v, want a serialization conflict", closeCommitErr) + } + if addCommitErr != nil && !isSerializationError(addCommitErr) { + t.Fatalf("add-child commit error = %v, want a serialization conflict", addCommitErr) + } +} + +// TestCloseIssueCheckedPinnedConnRefusalRestoresCoordinationSavepoint proves +// that the production pinned-connection UOW can catch a checked-close refusal +// and commit a sibling operation without persisting the refused close's +// coordination writes. +func TestCloseIssueCheckedPinnedConnRefusalRestoresCoordinationSavepoint(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + const ( + parent = "close-savepoint-parent" + child = "close-savepoint-child" + sibling = "close-savepoint-sibling" + ) + for _, id := range []string{parent, child, sibling} { + createPerm(t, ctx, store, id) + } + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepParentChild, + }, "tester"); err != nil { + t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err) + } + + coordinationValue := func(t *testing.T, tier string) *string { + t.Helper() + var value string + err := store.db.QueryRowContext(ctx, + "SELECT value FROM local_metadata WHERE `key` LIKE ?", + "dependency-coordination/v1/"+tier+"/%", + ).Scan(&value) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + t.Fatalf("read %s coordination cell: %v", tier, err) + } + return &value + } + beforeDurable := coordinationValue(t, "dependencies") + beforeWisp := coordinationValue(t, "wisp_dependencies") + if beforeDurable == nil || beforeWisp != nil { + t.Fatalf("pre-call coordination = durable:%v wisp:%v, want durable token and absent wisp token", beforeDurable, beforeWisp) + } + + conn, err := store.db.Conn(ctx) + if err != nil { + t.Fatalf("pin transaction connection: %v", err) + } + transactionOpen := true + defer func() { + if transactionOpen { + _, _ = conn.ExecContext(ctx, "ROLLBACK") + } + _ = conn.Close() + }() + if _, err := conn.ExecContext(ctx, "START TRANSACTION"); err != nil { + t.Fatalf("start pinned-connection transaction: %v", err) + } + + _, err = issueops.CloseIssueCheckedInTx(ctx, conn, parent, "done", "tester", "", false, nil) + if !errors.Is(err, storage.ErrCloseOpenChildren) { + t.Fatalf("checked close error = %v, want ErrCloseOpenChildren", err) + } + if _, err := issueops.CloseIssueInTx(ctx, conn, sibling, "done", "tester", ""); err != nil { + t.Fatalf("close sibling after refused parent close: %v", err) + } + if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil { + t.Fatalf("commit sibling close after refusal: %v", err) + } + transactionOpen = false + if err := conn.Close(); err != nil { + t.Fatalf("release committed transaction connection: %v", err) + } + + for _, check := range []struct { + id string + status types.Status + }{{parent, types.StatusOpen}, {sibling, types.StatusClosed}} { + issue, err := store.GetIssue(ctx, check.id) + if err != nil { + t.Fatalf("GetIssue(%s): %v", check.id, err) + } + if issue.Status != check.status { + t.Fatalf("%s status = %q, want %q", check.id, issue.Status, check.status) + } + } + + for _, check := range []struct { + tier string + want *string + }{ + {tier: "dependencies", want: beforeDurable}, + {tier: "wisp_dependencies", want: beforeWisp}, + } { + got := coordinationValue(t, check.tier) + if (got == nil) != (check.want == nil) { + t.Fatalf("%s coordination presence = %v, want %v", check.tier, got != nil, check.want != nil) + } + if got != nil && *got != *check.want { + t.Fatalf("%s coordination value = %q, want pre-call %q", check.tier, *got, *check.want) + } + } } // TestCloseIssueCheckedVersionCAS exercises the optional ExpectedVersion diff --git a/internal/storage/dolt/demote_to_wisp_test.go b/internal/storage/dolt/demote_to_wisp_test.go index 77dcc0cce..b2f48ca61 100644 --- a/internal/storage/dolt/demote_to_wisp_test.go +++ b/internal/storage/dolt/demote_to_wisp_test.go @@ -174,11 +174,13 @@ func TestDemoteToWisp_MetadataAndClosedAtUpdatesApplied(t *testing.T) { if err := store.UpdateIssue(ctx, issue.ID, map[string]interface{}{ "no_history": true, - "status": string(types.StatusClosed), "metadata": `{"review":"kept"}`, }, "tester"); err != nil { t.Fatalf("UpdateIssue: %v", err) } + if err := store.CloseIssue(ctx, issue.ID, "", "tester", ""); err != nil { + t.Fatalf("CloseIssue: %v", err) + } wisp, err := store.GetIssue(ctx, issue.ID) if err != nil { diff --git a/internal/storage/dolt/dependency_coordination_test.go b/internal/storage/dolt/dependency_coordination_test.go new file mode 100644 index 000000000..1d6d8291a --- /dev/null +++ b/internal/storage/dolt/dependency_coordination_test.go @@ -0,0 +1,65 @@ +package dolt + +import ( + "testing" + + "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" +) + +func TestAddDependencyInTxParentChildCoordinationTouch(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + parent, child, blocker, blocked := "coord-parent", "coord-child", "coord-blocker", "coord-blocked" + for _, id := range []string{parent, child, blocker, blocked} { + createPerm(t, ctx, store, id) + } + + key := "dependency-coordination/v1/dependencies/%" + add := func(dep *types.Dependency) { + t.Helper() + tx, err := store.db.BeginTx(ctx, nil) + if err != nil { + t.Fatalf("begin add dependency transaction: %v", err) + } + defer tx.Rollback() + if _, err := issueops.AddDependencyInTx(ctx, tx, dep, "tester", issueops.AddDependencyOpts{}); err != nil { + t.Fatalf("AddDependencyInTx(%s -> %s): %v", dep.IssueID, dep.DependsOnID, err) + } + if err := tx.Commit(); err != nil { + t.Fatalf("commit add dependency: %v", err) + } + } + add(&types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild}) + + var value string + if err := store.db.QueryRowContext(ctx, "SELECT value FROM local_metadata WHERE `key` LIKE ?", key).Scan(&value); err != nil { + t.Fatalf("read new parent-child coordination token: %v", err) + } + if value == "" { + t.Fatal("new parent-child edge did not write a coordination token") + } + if _, err := store.db.ExecContext(ctx, "UPDATE local_metadata SET value = 'sentinel' WHERE `key` LIKE ?", key); err != nil { + t.Fatalf("seed idempotent sentinel: %v", err) + } + + add(&types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild}) + if err := store.db.QueryRowContext(ctx, "SELECT value FROM local_metadata WHERE `key` LIKE ?", key).Scan(&value); err != nil { + t.Fatalf("read idempotent coordination token: %v", err) + } + if value != "sentinel" { + t.Fatalf("idempotent parent-child re-add rewrote coordination token = %q, want sentinel", value) + } + + add(&types.Dependency{IssueID: blocker, DependsOnID: blocked, Type: types.DepBlocks}) + var count int + if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM local_metadata WHERE `key` LIKE ?", key).Scan(&count); err != nil { + t.Fatalf("count coordination rows after non-parent edge: %v", err) + } + if count != 1 { + t.Fatalf("coordination rows after non-parent edge = %d, want 1", count) + } +} diff --git a/internal/storage/dolt/issue_lifecycle_test.go b/internal/storage/dolt/issue_lifecycle_test.go new file mode 100644 index 000000000..665eabff2 --- /dev/null +++ b/internal/storage/dolt/issue_lifecycle_test.go @@ -0,0 +1,29 @@ +package dolt + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" +) + +func TestDoltStoreIssueLifecycleBuildsOperations(t *testing.T) { + lifecycle, err := (&DoltStore{}).IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle() error = %v", err) + } + if lifecycle == nil { + t.Fatal("IssueLifecycle() returned nil operations") + } +} + +func TestDoltStoreIssueLifecycleRejectsNilStore(t *testing.T) { + lifecycle, err := (*DoltStore)(nil).IssueLifecycle() + if lifecycle != nil { + t.Fatalf("IssueLifecycle() lifecycle = %T, want nil", lifecycle) + } + var unsupported *storage.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("IssueLifecycle() error = %v, want *storage.ErrUnsupported", err) + } +} diff --git a/internal/storage/dolt/issue_operations.go b/internal/storage/dolt/issue_operations.go new file mode 100644 index 000000000..7a1be4c3d --- /dev/null +++ b/internal/storage/dolt/issue_operations.go @@ -0,0 +1,143 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// IssueLifecycle returns the guarded issue-lifecycle surface for this store. +func (s *DoltStore) IssueLifecycle() (issueops.Lifecycle, error) { + return NewIssueOperations(s) +} + +// NewIssueOperations returns guarded issue operations backed by store. +func NewIssueOperations(store *DoltStore) (issueops.Lifecycle, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewIssueOperations", Backend: "nil"} + } + return &issueOperations{store: store}, nil +} + +type issueOperations struct{ store *DoltStore } + +// updateCommitMessage names the updated issue in the Dolt commit message. +func updateCommitMessage(issueID string) string { + if issueID == "" { + return "bd: update issue" + } + return "bd: update " + issueID +} + +func (o *issueOperations) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) { + snapshot := storageissueops.CloneCreateRequest(request) + var result issueops.CreateResult + err := o.store.runIssueOperationTx(ctx, "bd: create issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteCreate(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +func (o *issueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) { + snapshot := storageissueops.CloneUpdateRequest(request) + var result issueops.UpdateResult + err := o.verifiedUpdate(ctx, snapshot, func() error { + // The message names the issue because that is the one `bd dolt log` + // affordance callers actually grep, and it is what the CLI's own + // per-command commit wrote before updates moved onto this path. + return o.store.runIssueOperationTx(ctx, updateCommitMessage(snapshot.IssueID), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteUpdate(ctx, tx, snapshot) + return tables, err + }) + }) + return result, err +} + +// verifiedUpdate runs a facade update under claim-family verify-after-write +// (bd-zccb9) when the request writes coordination state, and unwrapped +// otherwise. The facade reaches the same writes as ClaimIssue and +// UpdateIssueWithOptions, so under a degraded server its exit status is no more +// trustworthy than theirs. Replay is safe: the claim CAS and the compare-and-set +// guards are re-checked inside the replayed transaction, so a racing writer +// makes the replay refuse rather than clobber. +func (o *issueOperations) verifiedUpdate(ctx context.Context, request issueops.UpdateRequest, write func() error) error { + post, verify := updateClaimPostcondition(request) + if !verify { + return write() + } + return o.store.verifiedClaimWrite(ctx, request.IssueID, post, write) +} + +// updateClaimPostcondition derives the row state a facade update must leave +// behind to count as applied, and whether the update is claim-family at all. A +// claim always is; an ordinary update is only when a compare-and-set guard +// authorizes a write to assignee or status. The postcondition describes the +// state the request intends, so a patch that overrides the claim's own +// assignee or status is honored rather than read as a lost write. +// +// A request that also moves the issue across the persistence boundary is +// exempt: the row can legitimately leave the issues table mid-write, which the +// re-read would report as an unverifiable claim. +func updateClaimPostcondition(request issueops.UpdateRequest) (claimPostcondition, bool) { + if request.Patch.Persistence.Set { + return claimPostcondition{}, false + } + updates := map[string]interface{}{} + if request.Patch.Assignee.Set { + updates["assignee"] = request.Patch.Assignee.Value + } + if request.Patch.Status.Set { + updates["status"] = string(request.Patch.Status.Value) + } + if request.Claim { + assignee, status := request.Actor, types.StatusInProgress + if request.Patch.Assignee.Set { + assignee = request.Patch.Assignee.Value + } + if request.Patch.Status.Set { + status = request.Patch.Status.Value + } + return claimedAs(assignee, status), true + } + opts := storage.UpdateIssueOptions{ExpectedAssignee: request.ExpectedAssignee} + if request.ExpectedStatus != nil { + expected := string(*request.ExpectedStatus) + opts.ExpectedStatus = &expected + } + return guardedUpdatePostcondition(opts, updates) +} + +func (o *issueOperations) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) { + snapshot := storageissueops.CloneCloseRequest(request) + var result issueops.CloseResult + err := o.store.runIssueOperationTx(ctx, "bd: close issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteClose(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +func (o *issueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) { + snapshot := storageissueops.CloneReopenRequest(request) + var result issueops.ReopenResult + err := o.store.runIssueOperationTx(ctx, "bd: reopen issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteReopen(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +var _ issueops.Lifecycle = (*issueOperations)(nil) diff --git a/internal/storage/dolt/issue_operations_behavior_test.go b/internal/storage/dolt/issue_operations_behavior_test.go new file mode 100644 index 000000000..03b46bc58 --- /dev/null +++ b/internal/storage/dolt/issue_operations_behavior_test.go @@ -0,0 +1,640 @@ +package dolt + +import ( + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestIssueOperationsGuardedVerbs exercises the public operation adapter against +// a real direct store. Each subtest states a guard which the adapter, rather +// than a caller, must enforce. +func TestIssueOperationsGuardedVerbs(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + + create := func(t *testing.T, id string) *types.Issue { + t.Helper() + issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + return issue + } + + t.Run("create rejects occupied ID without overwriting", func(t *testing.T) { + create(t, "ops-duplicate") + _, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-duplicate", Title: "replacement", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}}) + if !errors.Is(err, publicops.ErrAlreadyExists) { + t.Fatalf("Create error = %v, want ErrAlreadyExists", err) + } + got, getErr := store.GetIssue(ctx, "ops-duplicate") + if getErr != nil || got.Title != "ops-duplicate" { + t.Fatalf("stored duplicate = %#v, %v; want original title", got, getErr) + } + }) + + t.Run("create applies aggregate request and validates prefix", func(t *testing.T) { + parent := create(t, "ops-parent") + spawner := create(t, "ops-spawner") + if err := store.AddLabel(ctx, parent.ID, "parent-label", "seed"); err != nil { + t.Fatal(err) + } + target := create(t, "ops-target") + _, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", Issue: &types.Issue{ID: "foreign-aggregate", Title: "aggregate", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, ParentID: parent.ID, InheritLabelsFromParent: true, Dependencies: []publicops.CreateDependency{{TargetID: target.ID, Type: types.DepRelated, ThreadID: "thread"}, {TargetID: target.ID, Type: types.DepRelatesTo, Reverse: true, ThreadID: "reverse-thread"}}, WaitsFor: &publicops.WaitsFor{SpawnerID: spawner.ID}}) + if !errors.Is(err, publicops.ErrPrefixMismatch) { + t.Fatalf("unforced foreign prefix error = %v, want ErrPrefixMismatch", err) + } + result, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", Issue: &types.Issue{ID: "foreign-aggregate", Title: "aggregate", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, ForceIDPrefix: true, ParentID: parent.ID, InheritLabelsFromParent: true, Dependencies: []publicops.CreateDependency{{TargetID: target.ID, Type: types.DepRelated, ThreadID: "thread"}, {TargetID: target.ID, Type: types.DepRelatesTo, Reverse: true, ThreadID: "reverse-thread"}}, WaitsFor: &publicops.WaitsFor{SpawnerID: spawner.ID}}) + if err != nil { + t.Fatalf("forced Create: %v", err) + } + if len(result.Issue.Labels) != 1 || result.Issue.Labels[0] != "parent-label" { + t.Fatalf("Create result aggregate = %#v", result.Issue) + } + if len(result.Issue.Dependencies) != 3 { + t.Fatalf("Create dependencies = %#v, want parent, waits-for, and direct edges", result.Issue.Dependencies) + } + inbound, err := store.GetDependentRecords(ctx, result.Issue.ID, "", 10, "") + if err != nil || len(inbound) != 1 || inbound[0].IssueID != target.ID || inbound[0].ThreadID != "reverse-thread" { + t.Fatalf("reverse dependency = %#v, %v", inbound, err) + } + }) + + t.Run("update enforces CAS claim and patch aggregate", func(t *testing.T) { + issue := create(t, "ops-update") + stale := issue.RowVersion + 1 + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must not persist"}}}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("stale Update error = %v, want ErrVersionMismatch", err) + } + claimed, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Claim: true}) + if err != nil || !claimed.Changed || claimed.Issue.Assignee != "writer" || claimed.Issue.Status != publicops.StatusInProgress { + t.Fatalf("claim result = %#v, %v", claimed, err) + } + updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "note"}, ExternalRef: publicops.Field[*string]{Set: true, Value: stringPtr("external")}, Labels: publicops.LabelPatch{Add: []string{"label"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"key": json.RawMessage(`"value"`)}}, Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}}}) + if err != nil || !updated.Changed || updated.Issue.ExternalRef == nil || *updated.Issue.ExternalRef != "external" || len(updated.Issue.Labels) != 1 { + t.Fatalf("aggregate update = %#v, %v", updated, err) + } + }) + + t.Run("update enforces field guards and reports no-op", func(t *testing.T) { + issue := create(t, "ops-field-guards") + expectedAssignee := "other" + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrAssigneeMismatch) { + t.Fatalf("assignee guard error = %v, want ErrAssigneeMismatch", err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: issue.Title}}}) + if err != nil || noOp.Changed { + t.Fatalf("same-value update = %#v, %v; want unchanged", noOp, err) + } + }) + + t.Run("update applies metadata patch", func(t *testing.T) { + issue := create(t, "ops-metadata") + updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"answer": json.RawMessage(`42`)}}}}) + if err != nil || !updated.Changed || string(updated.Issue.Metadata) != `{"answer":42}` { + t.Fatalf("metadata update = %#v, %v", updated, err) + } + }) + + t.Run("close and reopen enforce lifecycle guards", func(t *testing.T) { + parent := create(t, "ops-close-parent") + child := create(t, "ops-close-child") + if err := store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatal(err) + } + stale := parent.RowVersion + 1 + _, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("stale Close error = %v, want ErrVersionMismatch", err) + } + _, err = operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID}) + if !errors.Is(err, publicops.ErrCloseOpenChildren) { + t.Fatalf("unforced close error = %v, want ErrCloseOpenChildren", err) + } + closed, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true}) + if err != nil || !closed.Changed || closed.OpenChildren != 1 { + t.Fatalf("forced close = %#v, %v", closed, err) + } + stale = closed.Issue.RowVersion + 1 + _, err = operations.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("stale Reopen error = %v, want ErrVersionMismatch", err) + } + }) +} + +func TestIssueOperationsUpdateMetadataPatchOrderingAndReplacementGuard(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + issue := &types.Issue{ID: "ops-metadata-order", Title: "metadata", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"old","remove":"old"}`)} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + + updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{ + Merge: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"keep":"merged","merge":true}`)}, + Set: map[string]json.RawMessage{"after": json.RawMessage(`"set"`), "keep": json.RawMessage(`"set"`)}, + Unset: []string{"keep", "remove"}, + }}}) + if err != nil || !updated.Changed || !sameMetadataJSON(updated.Issue.Metadata, json.RawMessage(`{"after":"set","merge":true}`)) { + t.Fatalf("ordered metadata update = %#v, %v", updated, err) + } + replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)}}}}) + if err != nil || !replaced.Changed || !sameMetadataJSON(replaced.Issue.Metadata, json.RawMessage(`{"replacement":true}`)) { + t.Fatalf("metadata replacement = %#v, %v", replaced, err) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{ + Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)}, + Set: map[string]json.RawMessage{"must_not_persist": json.RawMessage(`true`)}, + }}}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("combined replacement error = %v, want ErrValidation", err) + } + stored, err := store.GetIssue(ctx, issue.ID) + if err != nil || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"replacement":true}`)) { + t.Fatalf("replacement guard persisted metadata = %#v, %v", stored, err) + } +} + +func TestIssueOperationsUpdateLabelPatchOrderingAndNoop(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + issue := &types.Issue{ID: "ops-label-order", Title: "labels", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"old", "shared"}} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + patch := publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "shared"}}, Add: []string{"add", "shared"}, Remove: []string{"old", "shared"}} + updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: patch}}) + if err != nil || !updated.Changed || strings.Join(updated.Issue.Labels, ",") != "add,replace" { + t.Fatalf("ordered labels update = %#v, %v", updated, err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "add"}}, Add: []string{"add"}, Remove: []string{"missing"}}}}) + if err != nil || noOp.Changed || strings.Join(noOp.Issue.Labels, ",") != "add,replace" { + t.Fatalf("same labels update = %#v, %v", noOp, err) + } +} + +func TestIssueOperationsUpdateParentReplacementClearAndNoop(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + create := func(id string) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + parentA, parentB, parentC := create("ops-parent-a"), create("ops-parent-b"), create("ops-parent-c") + child := create("ops-parent-child") + for _, parent := range []*types.Issue{parentA, parentB} { + if err := store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatal(err) + } + } + + replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}}) + if err != nil || !replaced.Changed || issueParentIDs(replaced.Issue) != parentC.ID { + t.Fatalf("parent replacement = %#v, %v", replaced, err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}}) + if err != nil || noOp.Changed || issueParentIDs(noOp.Issue) != parentC.ID { + t.Fatalf("same parent replacement = %#v, %v", noOp, err) + } + cleared, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}}) + if err != nil || !cleared.Changed || issueParentIDs(cleared.Issue) != "" { + t.Fatalf("parent clear = %#v, %v", cleared, err) + } + noOp, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}}) + if err != nil || noOp.Changed || issueParentIDs(noOp.Issue) != "" { + t.Fatalf("same parent clear = %#v, %v", noOp, err) + } +} + +func TestIssueOperationsUpdateClaimCASAndTransferMatrix(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + create := func(id, assignee string, status types.Status, wisp bool) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Assignee: assignee, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + t.Run("CAS and claim eligibility", func(t *testing.T) { + issue := create("ops-cas", "owner", types.StatusOpen, false) + stale := issue.RowVersion + 1 + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("version error = %v", err) + } + expected, status := "other", publicops.StatusOpen + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expected, ExpectedStatus: &status, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrAssigneeMismatch) { + t.Fatalf("assignee error = %v", err) + } + status = publicops.StatusInProgress + expected = "owner" + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expected, ExpectedStatus: &status, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrStatusMismatch) { + t.Fatalf("status error = %v", err) + } + status = publicops.StatusOpen + matched, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expected, ExpectedStatus: &status, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "matched"}}}) + if err != nil || !matched.Changed || matched.Issue.Title != "matched" { + t.Fatalf("matching CAS = %#v, %v", matched, err) + } + claimable := create("ops-claim", "", types.StatusOpen, false) + claimed, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true}) + if err != nil || !claimed.Changed { + t.Fatalf("claim = %#v, %v", claimed, err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true}) + if err != nil || noOp.Changed { + t.Fatalf("same claim = %#v, %v", noOp, err) + } + foreign := create("ops-foreign", "owner", types.StatusOpen, false) + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: foreign.ID, Claim: true}) + if !errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Fatalf("foreign claim = %v", err) + } + if err := store.SetConfig(ctx, "claim.pools", "crew"); err != nil { + t.Fatal(err) + } + pool := create("ops-pool", "crew", types.StatusOpen, false) + pooled, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: pool.ID, Claim: true}) + if err != nil || !pooled.Changed || pooled.Issue.Assignee != "worker" { + t.Fatalf("pool claim = %#v, %v", pooled, err) + } + poolTransfer := create("ops-pool-transfer", "crew", types.StatusInProgress, false) + transferred, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: poolTransfer.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if err != nil || !transferred.Changed || transferred.Issue.Assignee != "next" { + t.Fatalf("pool transfer = %#v, %v", transferred, err) + } + }) + t.Run("transfer override validation and wisp", func(t *testing.T) { + foreign := create("ops-transfer", "owner", types.StatusInProgress, false) + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if !errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Fatalf("unforced transfer = %v", err) + } + forced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, ForceAssigneeTransfer: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if err != nil || !forced.Changed { + t.Fatalf("forced transfer = %#v, %v", forced, err) + } + expected := "owner" + authorized := create("ops-authorized", "owner", types.StatusInProgress, false) + result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: authorized.ID, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if err != nil || !result.Changed { + t.Fatalf("authorized transfer = %#v, %v", result, err) + } + override := create("ops-override", "", types.StatusOpen, false) + result, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: override.ID, Claim: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "reviewer"}, Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen}}}) + if err != nil || !result.Changed || result.Issue.Assignee != "reviewer" || result.Issue.Status != publicops.StatusOpen { + t.Fatalf("override = %#v, %v", result, err) + } + wisp := create("ops-wisp", "", types.StatusOpen, true) + wispResult, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: wisp.ID, Claim: true}) + if err != nil || !wispResult.Changed { + t.Fatalf("wisp claim = %#v, %v", wispResult, err) + } + expected = "" + for _, request := range []publicops.UpdateRequest{{Actor: "worker", IssueID: override.ID, Claim: true, ExpectedAssignee: &expected}, {Actor: "worker", IssueID: override.ID, Claim: true, ForceAssigneeTransfer: true}, {Actor: "worker", IssueID: override.ID, ForceAssigneeTransfer: true}, {Actor: "worker", IssueID: override.ID, ForceAssigneeTransfer: true, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}} { + _, err := operations.Update(ctx, request) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("invalid request = %v", err) + } + } + }) +} + +func TestIssueOperationsLifecycleContractMatrix(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + ops, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + makeIssue := func(id string, status types.Status, wisp bool) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + t.Run("close session and reclose", func(t *testing.T) { + issue := makeIssue("ops-life", types.StatusOpen, false) + result, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID, Reason: "because", Session: "session-1"}) + if err != nil || !result.Changed || result.Issue.ClosedBySession != "session-1" || result.Issue.CloseReason != "because" { + t.Fatalf("first close session=%q reason=%q changed=%t error=%v", result.Issue.ClosedBySession, result.Issue.CloseReason, result.Changed, err) + } + reclose, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID}) + if err != nil || reclose.Changed { + t.Fatalf("idempotent reclose = %#v, %v; want unchanged", reclose, err) + } + }) + t.Run("version force and reopen routes", func(t *testing.T) { + parent, child := makeIssue("ops-life-parent", types.StatusOpen, false), makeIssue("ops-life-child", types.StatusOpen, false) + if err := store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatal(err) + } + _, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID}) + if !errors.Is(err, publicops.ErrCloseOpenChildren) { + t.Fatalf("children refusal = %v", err) + } + forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true}) + if err != nil || forced.OpenChildren != 1 { + t.Fatalf("forced close = %#v, %v", forced, err) + } + stale := forced.Issue.RowVersion + 1 + _, err = ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("close version = %v", err) + } + opened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID}) + if err != nil || !opened.Changed || opened.Issue.Status != publicops.StatusOpen { + t.Fatalf("reopen = %#v, %v", opened, err) + } + noOp, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID}) + if err != nil || noOp.Changed { + t.Fatalf("open reopen = %#v, %v", noOp, err) + } + wisp := makeIssue("ops-life-wisp", types.StatusOpen, true) + closed, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID}) + if err != nil || !closed.Changed { + t.Fatalf("wisp close = %#v, %v", closed, err) + } + if _, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: wisp.ID}); err != nil { + t.Fatal(err) + } + }) +} + +func TestIssueOperationsLifecycleRemainingCausalCases(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + ops, _ := NewIssueOperations(store) + makeIssue := func(id string, status types.Status) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + t.Run("blocker refusal and force leave no partial mutation", func(t *testing.T) { + blocker, target := makeIssue("ops-blocker", types.StatusOpen), makeIssue("ops-blocked", types.StatusOpen) + if err := store.AddDependency(ctx, &types.Dependency{IssueID: target.ID, DependsOnID: blocker.ID, Type: types.DepBlocks}, "seed"); err != nil { + t.Fatal(err) + } + _, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID}) + if !errors.Is(err, publicops.ErrCloseBlocked) { + t.Fatalf("blocker=%v", err) + } + got, _ := store.GetIssue(ctx, target.ID) + if got.Status != types.StatusOpen { + t.Fatalf("refusal mutated=%#v", got) + } + forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID, Force: true}) + if err != nil || !forced.Changed { + t.Fatalf("force=%#v,%v", forced, err) + } + }) + t.Run("reopen version before non-done noop and custom done", func(t *testing.T) { + open := makeIssue("ops-open", types.StatusOpen) + stale := open.RowVersion + 1 + _, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: open.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("reopen version=%v", err) + } + if err := store.SetConfig(ctx, "status.custom", "archived:done"); err != nil { + t.Fatal(err) + } + custom := makeIssue("ops-custom", types.Status("archived")) + reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: custom.ID}) + if err != nil || !reopened.Changed || reopened.Issue.Status != types.StatusOpen { + t.Fatalf("custom=%#v,%v", reopened, err) + } + }) +} + +func issueParentIDs(issue *types.Issue) string { + parents := make([]string, 0) + for _, dependency := range issue.Dependencies { + if dependency.Type == types.DepParentChild { + parents = append(parents, dependency.DependsOnID) + } + } + return strings.Join(parents, ",") +} + +func sameMetadataJSON(left, right json.RawMessage) bool { + var leftValue, rightValue any + return json.Unmarshal(left, &leftValue) == nil && json.Unmarshal(right, &rightValue) == nil && reflect.DeepEqual(leftValue, rightValue) +} + +func stringPtr(value string) *string { return &value } + +func TestIssueOperationsUpdateAllScalarAndPointerFieldsReportChanged(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + ops, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + when := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC) + minutes, external := 15, "external" + base := func(id string) *types.Issue { + return &types.Issue{ID: id, Title: "title", Description: "description", Design: "design", AcceptanceCriteria: "criteria", Notes: "notes", SpecID: "spec", AwaitID: "await", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Assignee: "worker", Owner: "owner", ClosedBySession: "session", EstimatedMinutes: &minutes, ExternalRef: &external, DueAt: &when, DeferUntil: &when} + } + cases := []struct { + name string + patch publicops.IssuePatch + check func(*types.Issue) bool + }{ + {"title", publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "changed"}}, func(i *types.Issue) bool { return i.Title == "changed" }}, + {"description clear", publicops.IssuePatch{Description: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Description == "" }}, + {"design clear", publicops.IssuePatch{Design: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Design == "" }}, + {"acceptance criteria clear", publicops.IssuePatch{AcceptanceCriteria: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AcceptanceCriteria == "" }}, + {"notes clear", publicops.IssuePatch{Notes: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Notes == "" }}, + {"append notes", publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "later"}}, func(i *types.Issue) bool { return i.Notes == "notes\nlater" }}, + {"spec ID clear", publicops.IssuePatch{SpecID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.SpecID == "" }}, + {"await ID clear", publicops.IssuePatch{AwaitID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AwaitID == "" }}, + {"status", publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusInProgress}}, func(i *types.Issue) bool { return i.Status == publicops.StatusInProgress }}, + {"priority zero", publicops.IssuePatch{Priority: publicops.Field[int]{Set: true}}, func(i *types.Issue) bool { return i.Priority == 0 }}, + {"issue type", publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: types.TypeBug}}, func(i *types.Issue) bool { return i.IssueType == types.TypeBug }}, + {"assignee clear", publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Assignee == "" }}, + {"owner clear", publicops.IssuePatch{Owner: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Owner == "" }}, + {"closed by session clear", publicops.IssuePatch{ClosedBySession: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.ClosedBySession == "" }}, + {"estimated minutes clear", publicops.IssuePatch{EstimatedMinutes: publicops.Field[*int]{Set: true}}, func(i *types.Issue) bool { return i.EstimatedMinutes == nil }}, + {"external ref clear", publicops.IssuePatch{ExternalRef: publicops.Field[*string]{Set: true}}, func(i *types.Issue) bool { return i.ExternalRef == nil }}, + {"due at clear", publicops.IssuePatch{DueAt: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DueAt == nil }}, + {"defer until clear", publicops.IssuePatch{DeferUntil: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DeferUntil == nil }}, + } + for n, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + issue := base("ops-scalars-" + tc.name) + issue.ID = strings.ReplaceAll(issue.ID, " ", "-") + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch}) + if err != nil || !result.Changed || !tc.check(result.Issue) { + t.Fatalf("Update(%s) = %#v, %v", tc.name, result, err) + } + stored, err := store.GetIssue(ctx, issue.ID) + if err != nil || !tc.check(stored) { + t.Fatalf("stored %s = %#v, %v", tc.name, stored, err) + } + if tc.name != "append notes" { + noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch}) + if err != nil || noOp.Changed { + t.Fatalf("same-value %s = %#v, %v", tc.name, noOp, err) + } + after, err := store.GetIssue(ctx, issue.ID) + if err != nil || after.RowVersion != stored.RowVersion { + t.Fatalf("same-value %s wrote row version %d -> %d, %v", tc.name, stored.RowVersion, after.RowVersion, err) + } + } + _ = n + }) + } + issue := base("ops-notes-conflict") + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + _, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Notes: publicops.Field[string]{Set: true, Value: "replace"}, AppendNotes: publicops.Field[string]{Set: true, Value: "append"}}}) + if err == nil { + t.Fatal("Notes plus AppendNotes succeeded") + } + stored, err := store.GetIssue(ctx, issue.ID) + if err != nil || stored.Title != "title" || stored.Notes != "notes" { + t.Fatalf("notes conflict persisted %#v, %v", stored, err) + } +} + +func TestIssueOperationsUpdatePersistenceContributionAndRollback(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + ops, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + for _, transition := range []struct { + from, to publicops.PersistenceMode + }{ + {publicops.PersistenceModePersistent, publicops.PersistenceModeEphemeral}, {publicops.PersistenceModeEphemeral, publicops.PersistenceModeNoHistory}, {publicops.PersistenceModeNoHistory, publicops.PersistenceModePersistent}, + } { + id := "ops-persistence-" + string(transition.from) + "-" + string(transition.to) + ephemeral := transition.from == publicops.PersistenceModeEphemeral + noHistory := transition.from == publicops.PersistenceModeNoHistory + if err := store.CreateIssue(ctx, &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral, NoHistory: noHistory}, "seed"); err != nil { + t.Fatal(err) + } + result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}}) + if err != nil || !result.Changed || result.Issue.Ephemeral != (transition.to == publicops.PersistenceModeEphemeral) || result.Issue.NoHistory != (transition.to == publicops.PersistenceModeNoHistory) { + t.Fatalf("transition %s->%s = %#v, %v", transition.from, transition.to, result, err) + } + noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}}) + if err != nil || noOp.Changed { + t.Fatalf("same persistence %s = %#v, %v", transition.to, noOp, err) + } + } + unversioned := &types.Issue{ID: "ops-persistence-rollback", Title: "original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`)} + if err := store.CreateIssue(ctx, unversioned, "seed"); err != nil { + t.Fatal(err) + } + _, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: unversioned.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Labels: publicops.LabelPatch{Add: []string{"must-rollback"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"must_rollback": json.RawMessage(`true`)}}, Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}}}) + if err == nil { + t.Fatal("unversioned demotion succeeded") + } + stored, err := store.GetIssue(ctx, unversioned.ID) + if err != nil || stored.Title != "original" || strings.Join(stored.Labels, ",") != "keep" || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"keep":true}`)) || stored.Ephemeral || stored.NoHistory { + t.Fatalf("failed demotion left state %#v, %v", stored, err) + } +} + +func TestIssueOperationsWispAggregateLifecycleAndResultDetachment(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + ops, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + external := "external" + wisp := &types.Issue{ID: "ops-wisp-detached", Title: "wisp", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`), ExternalRef: &external} + if err := store.CreateIssue(ctx, wisp, "seed"); err != nil { + t.Fatal(err) + } + updated, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: wisp.ID, Patch: publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "after"}, Labels: publicops.LabelPatch{Add: []string{"added"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"added": json.RawMessage(`true`)}}}}) + if err != nil || !updated.Changed || updated.Issue.Notes != "before\nafter" || strings.Join(updated.Issue.Labels, ",") != "added,keep" { + t.Fatalf("wisp update = %#v, %v", updated, err) + } + updated.Issue.Labels[0], updated.Issue.Metadata[2], *updated.Issue.ExternalRef = "corrupt", 'X', "corrupt" + stored, err := store.GetIssue(ctx, wisp.ID) + if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) || stored.ExternalRef == nil || *stored.ExternalRef != "external" { + t.Fatalf("update result aliases store %#v, %v", stored, err) + } + closed, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID}) + if err != nil || !closed.Changed || closed.Issue.Status != publicops.StatusClosed { + t.Fatalf("wisp close = %#v, %v", closed, err) + } + closed.Issue.Metadata[2] = 'X' + reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: wisp.ID}) + if err != nil || !reopened.Changed || reopened.Issue.Status != publicops.StatusOpen { + t.Fatalf("wisp reopen = %#v, %v", reopened, err) + } + reopened.Issue.Labels[0] = "corrupt" + stored, err = store.GetIssue(ctx, wisp.ID) + if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) { + t.Fatalf("lifecycle result aliases store %#v, %v", stored, err) + } +} diff --git a/internal/storage/dolt/issue_operations_claim_verify_test.go b/internal/storage/dolt/issue_operations_claim_verify_test.go new file mode 100644 index 000000000..9f5a9ae5b --- /dev/null +++ b/internal/storage/dolt/issue_operations_claim_verify_test.go @@ -0,0 +1,197 @@ +package dolt + +import ( + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// The public facade reaches the same coordination-critical writes the store's +// own ClaimIssue/UpdateIssue do, so it needs the same verify-after-write +// resolution (bd-zccb9). Failure injection happens at the write-func seam, +// matching claim_verify_test.go. + +// TestIssueOperationsClaimVerifyPostcondition pins which facade updates are +// claim-family and what state each one must leave behind. +func TestIssueOperationsClaimVerifyPostcondition(t *testing.T) { + assignee := func(v string) *string { return &v } + status := func(v types.Status) *types.Status { return &v } + + cases := []struct { + name string + request publicops.UpdateRequest + wantVerified bool + wantDesc string + holds [][2]string // assignee, status pairs the postcondition accepts + rejects [][2]string + }{ + { + name: "bare claim", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true}, + wantVerified: true, + wantDesc: `assignee="alice" status="in_progress"`, + holds: [][2]string{{"alice", "in_progress"}}, + rejects: [][2]string{{"", "open"}, {"bob", "in_progress"}, {"alice", "open"}}, + }, + { + name: "claim with overriding status patch", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true, Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusBlocked}, + }}, + wantVerified: true, + wantDesc: `assignee="alice" status="blocked"`, + holds: [][2]string{{"alice", "blocked"}}, + rejects: [][2]string{{"alice", "in_progress"}}, + }, + { + name: "claim with overriding assignee patch", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true, Patch: publicops.IssuePatch{ + Assignee: publicops.Field[string]{Set: true, Value: "dispatcher"}, + }}, + wantVerified: true, + wantDesc: `assignee="dispatcher" status="in_progress"`, + holds: [][2]string{{"dispatcher", "in_progress"}}, + rejects: [][2]string{{"alice", "in_progress"}}, + }, + { + name: "claim that moves the issue to a wisp is not verified", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true, Patch: publicops.IssuePatch{ + Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}, + }}, + }, + { + name: "guarded assignee transfer", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", ExpectedAssignee: assignee("bob"), Patch: publicops.IssuePatch{ + Assignee: publicops.Field[string]{Set: true, Value: "carol"}, + }}, + wantVerified: true, + wantDesc: `assignee="carol"`, + holds: [][2]string{{"carol", "open"}, {"carol", "in_progress"}}, + rejects: [][2]string{{"bob", "open"}}, + }, + { + name: "guarded status write", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", ExpectedStatus: status(types.StatusOpen), Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress}, + }}, + wantVerified: true, + wantDesc: `status="in_progress"`, + holds: [][2]string{{"", "in_progress"}, {"bob", "in_progress"}}, + rejects: [][2]string{{"", "open"}}, + }, + { + name: "guarded edit of ordinary fields is not claim-family", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", ExpectedStatus: status(types.StatusOpen), Patch: publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "new title"}, + }}, + }, + { + name: "unguarded ordinary update is not claim-family", + request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Patch: publicops.IssuePatch{ + Assignee: publicops.Field[string]{Set: true, Value: "carol"}, + }}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + post, verified := updateClaimPostcondition(tc.request) + if verified != tc.wantVerified { + t.Fatalf("updateClaimPostcondition verified = %v, want %v", verified, tc.wantVerified) + } + if !verified { + return + } + if post.desc != tc.wantDesc { + t.Errorf("postcondition desc = %q, want %q", post.desc, tc.wantDesc) + } + for _, state := range tc.holds { + if !post.want(state[0], types.Status(state[1])) { + t.Errorf("postcondition rejected accepted state assignee=%q status=%q", state[0], state[1]) + } + } + for _, state := range tc.rejects { + if post.want(state[0], types.Status(state[1])) { + t.Errorf("postcondition accepted lost state assignee=%q status=%q", state[0], state[1]) + } + } + }) + } +} + +// TestIssueOperationsClaimVerifyFailsLoudlyOnLostFacadeClaim: a facade claim +// whose transaction reports success without landing must fail loudly, exactly +// like the store's own ClaimIssue. A silent phantom claim through the facade +// costs the same duplicated implementation the incident did. +func TestIssueOperationsClaimVerifyFailsLoudlyOnLostFacadeClaim(t *testing.T) { + s, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + id := claimVerifyTestIssue(t, s) + operations := &issueOperations{store: s} + + err := operations.verifiedUpdate(ctx, publicops.UpdateRequest{Actor: "alice", IssueID: id, Claim: true}, func() error { + return nil // lie: report success without writing anything + }) + if err == nil { + t.Fatal("expected loud failure for a success-reported-but-lost facade claim, got nil") + } + if !strings.Contains(err.Error(), "did not land") { + t.Fatalf("error should say the claim did not land, got: %v", err) + } +} + +// TestIssueOperationsClaimVerifyLeavesOrdinaryUpdatesUnwrapped: an update that +// is not claim-family keeps its exit status. A lost label or notes edit is an +// annoyance, not a phantom claim, and re-reading every update would cost a +// round trip per write. +func TestIssueOperationsClaimVerifyLeavesOrdinaryUpdatesUnwrapped(t *testing.T) { + s, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + id := claimVerifyTestIssue(t, s) + operations := &issueOperations{store: s} + + request := publicops.UpdateRequest{Actor: "alice", IssueID: id, Patch: publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "retitled"}, + }} + if err := operations.verifiedUpdate(ctx, request, func() error { return nil }); err != nil { + t.Fatalf("ordinary update must keep its exit status, got: %v", err) + } +} + +// TestIssueOperationsClaimVerifyPassesHealthyFacadeClaim: the verify layer does +// not disturb a claim that actually lands. +func TestIssueOperationsClaimVerifyPassesHealthyFacadeClaim(t *testing.T) { + s, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + id := claimVerifyTestIssue(t, s) + operations, err := NewIssueOperations(s) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + + result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "alice", IssueID: id, Claim: true}) + if err != nil { + t.Fatalf("facade claim: %v", err) + } + if !result.Changed || result.Issue.Assignee != "alice" || result.Issue.Status != types.StatusInProgress { + t.Fatalf("facade claim result = %#v", result) + } + assignee, status, err := s.readClaimState(ctx, id) + if err != nil { + t.Fatalf("read claim state: %v", err) + } + if assignee != "alice" || status != types.StatusInProgress { + t.Fatalf("post-claim state: assignee=%q status=%q", assignee, status) + } +} diff --git a/internal/storage/dolt/issue_operations_contract_test.go b/internal/storage/dolt/issue_operations_contract_test.go new file mode 100644 index 000000000..d47cee087 --- /dev/null +++ b/internal/storage/dolt/issue_operations_contract_test.go @@ -0,0 +1,51 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/storage/conformance" +) + +func TestIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsCreateRoutesInfraTypesToWisps(t, ctx, fixture) +} + +func TestIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsCreateRejectsMissingDependencyTargets(t, ctx, fixture) +} + +func TestIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t, ctx, fixture) +} + +func newDoltIssueOperationsFixture(t *testing.T) (conformance.IssueOperationsStagingFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + operations, err := NewIssueOperations(store) + if err != nil { + cancel() + storeCleanup() + t.Fatalf("NewIssueOperations: %v", err) + } + fixture := conformance.IssueOperationsStagingFixture{ + IssuePrefix: "test", + Operations: operations, + CreateIssue: store.CreateIssue, + SetConfig: store.SetConfig, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + return store.db.QueryRowContext(ctx, query, args...).Scan(dest...) + }, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/issue_operations_persistence_test.go b/internal/storage/dolt/issue_operations_persistence_test.go new file mode 100644 index 000000000..6670ffc09 --- /dev/null +++ b/internal/storage/dolt/issue_operations_persistence_test.go @@ -0,0 +1,303 @@ +package dolt + +import ( + "context" + "database/sql" + "testing" + + "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" +) + +func TestMoveIssuePersistenceInTxMovesAggregateAndReportsTables(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "persist-move", Title: "move", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"label"}} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if _, err := store.AddIssueComment(ctx, issue.ID, "tester", "comment"); err != nil { + t.Fatal(err) + } + depender := &types.Issue{ID: "persist-depender", Title: "depender", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, depender, "tester"); err != nil { + t.Fatal(err) + } + if err := store.AddDependency(ctx, &types.Dependency{IssueID: depender.ID, DependsOnID: issue.ID, Type: types.DepBlocks}, "tester"); err != nil { + t.Fatal(err) + } + if _, err := store.db.ExecContext(ctx, `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 4); err != nil { + t.Fatal(err) + } + var moved issueops.PersistenceMoveResult + if err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + moved, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral) + return err + }); err != nil { + t.Fatal(err) + } + if !moved.Changed || !moved.ChangedTables["issues"] || !moved.ChangedTables["wisps"] || !moved.ChangedTables["wisp_comments"] || !moved.ChangedTables["wisp_labels"] || !moved.ChangedTables["dependencies"] { + t.Fatalf("move result = %#v, want changed aggregate tables", moved) + } + got, err := store.GetIssue(ctx, issue.ID) + if err != nil { + t.Fatal(err) + } + if !got.Ephemeral || got.NoHistory || len(got.Labels) != 1 || got.Labels[0] != "label" { + t.Fatalf("moved issue = %#v", got) + } + comments, err := store.GetIssueComments(ctx, issue.ID) + if err != nil { + t.Fatal(err) + } + if len(comments) != 1 || comments[0].Text != "comment" { + t.Fatalf("comments = %#v", comments) + } + var durableTarget, wispTarget *string + if err := store.db.QueryRowContext(ctx, `SELECT depends_on_issue_id, depends_on_wisp_id FROM dependencies WHERE issue_id = ?`, depender.ID).Scan(&durableTarget, &wispTarget); err != nil { + t.Fatal(err) + } + if durableTarget != nil || wispTarget == nil || *wispTarget != issue.ID { + t.Fatalf("inbound target = (%v,%v), want (nil,%q)", durableTarget, wispTarget, issue.ID) + } + var sourceEvents, targetEvents, sourceCounters, targetCounters int + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM events WHERE issue_id = ?`, issue.ID).Scan(&sourceEvents); err != nil { + t.Fatal(err) + } + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisp_events WHERE issue_id = ?`, issue.ID).Scan(&targetEvents); err != nil { + t.Fatal(err) + } + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM child_counters WHERE parent_id = ?`, issue.ID).Scan(&sourceCounters); err != nil { + t.Fatal(err) + } + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ? AND last_child = 4`, issue.ID).Scan(&targetCounters); err != nil { + t.Fatal(err) + } + if sourceEvents != 0 || targetEvents == 0 || sourceCounters != 0 || targetCounters != 1 { + t.Fatalf("moved event/counter rows = events(%d,%d) counters(%d,%d)", sourceEvents, targetEvents, sourceCounters, targetCounters) + } +} + +func TestMoveIssuePersistenceInTxSameModeIsNoop(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "persist-noop", Title: "noop", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + result, err := issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModePersistent) + if err != nil { + return err + } + if result.Changed { + t.Fatal("same persistence mode changed issue") + } + return nil + }); err != nil { + t.Fatal(err) + } +} + +func TestMoveIssuePersistenceInTxTransitions(t *testing.T) { + for _, transition := range []struct { + name string + from types.PersistenceMode + to types.PersistenceMode + }{ + {"persistent-to-ephemeral", types.PersistenceModePersistent, types.PersistenceModeEphemeral}, + {"persistent-to-no-history", types.PersistenceModePersistent, types.PersistenceModeNoHistory}, + {"ephemeral-to-persistent", types.PersistenceModeEphemeral, types.PersistenceModePersistent}, + {"ephemeral-to-no-history", types.PersistenceModeEphemeral, types.PersistenceModeNoHistory}, + {"no-history-to-persistent", types.PersistenceModeNoHistory, types.PersistenceModePersistent}, + {"no-history-to-ephemeral", types.PersistenceModeNoHistory, types.PersistenceModeEphemeral}, + } { + t.Run(transition.name, func(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + ephemeral, noHistory, _, err := types.NormalizePersistenceMode(types.Issue{}, transition.from) + if err != nil { + t.Fatal(err) + } + issue := &types.Issue{ID: "transition-" + transition.name, Title: transition.name, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral, NoHistory: noHistory} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, transition.to) + return err + }); err != nil { + t.Fatal(err) + } + got, err := store.GetIssue(ctx, issue.ID) + if err != nil { + t.Fatal(err) + } + wantEphemeral, wantNoHistory, _, err := types.NormalizePersistenceMode(types.Issue{Ephemeral: ephemeral, NoHistory: noHistory}, transition.to) + if err != nil { + t.Fatal(err) + } + if got.Ephemeral != wantEphemeral || got.NoHistory != wantNoHistory { + t.Fatalf("persistence = (%t,%t), want (%t,%t)", got.Ephemeral, got.NoHistory, wantEphemeral, wantNoHistory) + } + }) + } +} + +func TestMoveIssuePersistenceInTxRefusesUnversionedDemotion(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "unversioned", Title: "unversioned", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral) + return err + }) + if err == nil { + t.Fatal("unversioned demotion succeeded") + } + got, err := store.GetIssue(ctx, issue.ID) + if err != nil || got.Ephemeral || got.NoHistory { + t.Fatalf("refusal state = %#v, %v", got, err) + } +} + +func TestMoveIssuePersistenceInTxDeletesLeaseOnDemotion(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "persist-lease", Title: "lease", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if err := store.ClaimIssue(ctx, issue.ID, "tester"); err != nil { + t.Fatal(err) + } + var before int + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM leases WHERE issue_id = ?`, issue.ID).Scan(&before); err != nil || before != 1 { + t.Fatalf("lease before move = %d, %v", before, err) + } + if err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral) + return err + }); err != nil { + t.Fatal(err) + } + var after int + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM leases WHERE issue_id = ?`, issue.ID).Scan(&after); err != nil || after != 0 { + t.Fatalf("lease after demotion = %d, %v", after, err) + } +} + +func TestMoveIssuePersistenceInTxTargetCollisionRollsBackSource(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "persist-collision", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"source-label"}} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if _, err := store.db.ExecContext(ctx, `INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, is_blocked) VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?)`, issue.ID, "target", types.StatusOpen, 2, types.TypeTask, true, 0); err != nil { + t.Fatal(err) + } + err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral) + return err + }) + if err == nil { + t.Fatal("move into occupied target succeeded") + } + var sourceLabels int + if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = 'source-label'`, issue.ID).Scan(&sourceLabels); err != nil { + t.Fatal(err) + } + if sourceLabels != 1 { + t.Fatalf("source aggregate was not rolled back; labels = %d", sourceLabels) + } +} + +func TestMoveIssuePersistenceInTxLateCounterConflictRollsBack(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "persist-late-rollback", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"source-label"}} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if _, err := store.AddIssueComment(ctx, issue.ID, "tester", "source comment"); err != nil { + t.Fatal(err) + } + if _, err := store.db.ExecContext(ctx, `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 3); err != nil { + t.Fatal(err) + } + // wisp_child_counters deliberately allows orphaned rows while a target wisp + // is absent. This duplicate is reached after the target issue, labels, + // comments, and events have been inserted, so it proves transaction rollback. + if _, err := store.db.ExecContext(ctx, `SET FOREIGN_KEY_CHECKS = 0`); err != nil { + t.Fatal(err) + } + if _, err := store.db.ExecContext(ctx, `INSERT INTO wisp_child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 9); err != nil { + t.Fatal(err) + } + if _, err := store.db.ExecContext(ctx, `SET FOREIGN_KEY_CHECKS = 1`); err != nil { + t.Fatal(err) + } + err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral) + return err + }) + if err == nil { + t.Fatal("late child-counter conflict did not fail move") + } + var sourceIssue, targetIssue, sourceLabels, sourceComments, targetLabels, targetComments, sourceCounter, targetCounter int + for _, check := range []struct { + query string + dest *int + }{ + {`SELECT COUNT(*) FROM issues WHERE id = ?`, &sourceIssue}, {`SELECT COUNT(*) FROM wisps WHERE id = ?`, &targetIssue}, + {`SELECT COUNT(*) FROM labels WHERE issue_id = ?`, &sourceLabels}, {`SELECT COUNT(*) FROM comments WHERE issue_id = ?`, &sourceComments}, + {`SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ?`, &targetLabels}, {`SELECT COUNT(*) FROM wisp_comments WHERE issue_id = ?`, &targetComments}, + {`SELECT COUNT(*) FROM child_counters WHERE parent_id = ? AND last_child = 3`, &sourceCounter}, {`SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ? AND last_child = 9`, &targetCounter}, + } { + if err := store.db.QueryRowContext(ctx, check.query, issue.ID).Scan(check.dest); err != nil { + t.Fatal(err) + } + } + if sourceIssue != 1 || targetIssue != 0 || sourceLabels != 1 || sourceComments != 1 || targetLabels != 0 || targetComments != 0 || sourceCounter != 1 || targetCounter != 1 { + t.Fatalf("rollback state issues(%d,%d) labels(%d,%d) comments(%d,%d) counters(%d,%d)", sourceIssue, targetIssue, sourceLabels, targetLabels, sourceComments, targetComments, sourceCounter, targetCounter) + } +} diff --git a/internal/storage/dolt/issue_operations_staging_test.go b/internal/storage/dolt/issue_operations_staging_test.go new file mode 100644 index 000000000..0118bd097 --- /dev/null +++ b/internal/storage/dolt/issue_operations_staging_test.go @@ -0,0 +1,449 @@ +package dolt + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage/conformance" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +func TestIssueOperationsCreateIgnoresDerivedFieldsAndRejectsMalformedAggregate(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + created, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-staging-create", Title: "create", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, RowVersion: 91, LeaseExpiresAt: &now, ContentHash: "derived"}}) + if err != nil { + t.Fatal(err) + } + if created.Issue.RowVersion == 91 || created.Issue.LeaseExpiresAt != nil || created.Issue.ContentHash == "derived" { + t.Fatalf("derived fields persisted: %#v", created.Issue) + } + _, err = operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-staging-invalid-create", Title: "invalid", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, Dependencies: []publicops.CreateDependency{{TargetID: "ops-staging-invalid-create", Type: types.DepBlocks}}}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("malformed aggregate error = %v, want ErrValidation", err) + } + if _, err := store.GetIssue(ctx, "ops-staging-invalid-create"); !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("malformed aggregate persisted issue: %v", err) + } +} + +func TestIssueOperationsCreateEmptyIDUsesChildIDAndStagesCounter(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + parent := &types.Issue{ID: "ops-staging-create-parent", Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic} + if err := store.CreateIssue(ctx, parent, "seed"); err != nil { + t.Fatal(err) + } + + create := func(title string) *types.Issue { + t.Helper() + result, err := operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: title, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + ParentID: parent.ID, + }) + if err != nil { + t.Fatalf("Create(%q): %v", title, err) + } + return result.Issue + } + + first := create("first child") + if first.ID != parent.ID+".1" { + t.Fatalf("first child ID = %q, want %q", first.ID, parent.ID+".1") + } + if !hasIssueOperationDependency(first.Dependencies, first.ID, parent.ID, types.DepParentChild, "{}", "") { + t.Fatalf("first child dependencies = %#v, want parent edge", first.Dependencies) + } + var counter int + if err := store.db.QueryRowContext(ctx, "SELECT last_child FROM child_counters AS OF 'HEAD' WHERE parent_id = ?", parent.ID).Scan(&counter); err != nil || counter != 1 { + t.Fatalf("committed first child counter = %d, %v; want 1", counter, err) + } + + second := create("second child") + if second.ID != parent.ID+".2" { + t.Fatalf("second child ID = %q, want %q", second.ID, parent.ID+".2") + } + if err := store.db.QueryRowContext(ctx, "SELECT last_child FROM child_counters AS OF 'HEAD' WHERE parent_id = ?", parent.ID).Scan(&counter); err != nil || counter != 2 { + t.Fatalf("committed second child counter = %d, %v; want 2", counter, err) + } +} + +func TestIssueOperationsCreateEmptyIDPersistsReverseDependenciesInSourceTier(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + durableSource := &types.Issue{ID: "test-staging-durable-source", Title: "durable source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + wispSource := &types.Issue{ID: "test-staging-wisp-source", Title: "wisp source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true} + for _, issue := range []*types.Issue{durableSource, wispSource} { + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + } + + t.Run("durable source points at generated wisp", func(t *testing.T) { + result, err := operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: "generated wisp", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, + Dependencies: []publicops.CreateDependency{{TargetID: durableSource.ID, Type: types.DepBlocks, Reverse: true, Metadata: `{"direction":"durable"}`, ThreadID: "durable-thread"}}, + }) + if err != nil { + t.Fatal(err) + } + if result.Issue.ID == "" { + t.Fatal("generated wisp ID is empty") + } + var metadata, threadID string + if err := store.db.QueryRowContext(ctx, "SELECT metadata, thread_id FROM dependencies WHERE issue_id = ? AND depends_on_wisp_id = ?", durableSource.ID, result.Issue.ID).Scan(&metadata, &threadID); err != nil || metadata != `{"direction":"durable"}` || threadID != "durable-thread" { + t.Fatalf("durable dependency = metadata %q, thread %q, err %v", metadata, threadID, err) + } + if blocked, _, err := store.IsBlocked(ctx, durableSource.ID); err != nil || !blocked { + t.Fatalf("durable source blocked = %t, %v; want true", blocked, err) + } + }) + + t.Run("wisp source points at generated durable issue", func(t *testing.T) { + result, err := operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: "generated durable", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + Dependencies: []publicops.CreateDependency{{TargetID: wispSource.ID, Type: types.DepBlocks, Reverse: true, Metadata: `{"direction":"wisp"}`, ThreadID: "wisp-thread"}}, + }) + if err != nil { + t.Fatal(err) + } + if result.Issue.ID == "" { + t.Fatal("generated durable issue ID is empty") + } + var metadata, threadID string + if err := store.db.QueryRowContext(ctx, "SELECT metadata, thread_id FROM wisp_dependencies WHERE issue_id = ? AND depends_on_issue_id = ?", wispSource.ID, result.Issue.ID).Scan(&metadata, &threadID); err != nil || metadata != `{"direction":"wisp"}` || threadID != "wisp-thread" { + t.Fatalf("wisp dependency = metadata %q, thread %q, err %v", metadata, threadID, err) + } + if blocked, _, err := store.IsBlocked(ctx, wispSource.ID); err != nil || !blocked { + t.Fatalf("wisp source blocked = %t, %v; want true", blocked, err) + } + }) +} + +func TestIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + + conformance.RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t, ctx, conformance.IssueOperationsStagingFixture{ + IssuePrefix: "test", + Operations: operations, + CreateIssue: store.CreateIssue, + Commit: store.Commit, + Exec: func(ctx context.Context, query string, args ...any) error { + _, err := store.db.ExecContext(ctx, query, args...) + return err + }, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + return store.db.QueryRowContext(ctx, query, args...).Scan(dest...) + }, + }) +} + +func TestIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + + conformance.RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t, ctx, conformance.IssueOperationsStagingFixture{ + IssuePrefix: "test", + Operations: operations, + CreateIssue: store.CreateIssue, + AddDependency: store.AddDependency, + GetReadyWork: store.GetReadyWork, + Commit: store.Commit, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + return store.db.QueryRowContext(ctx, query, args...).Scan(dest...) + }, + }) +} + +func hasIssueOperationDependency(dependencies []*types.Dependency, issueID, dependsOnID string, dependencyType types.DependencyType, metadata, threadID string) bool { + for _, dependency := range dependencies { + if dependency != nil && dependency.IssueID == issueID && dependency.DependsOnID == dependsOnID && dependency.Type == dependencyType && dependency.Metadata == metadata && dependency.ThreadID == threadID { + return true + } + } + return false +} + +func TestIssueOperationsReopenWispStagesOnlyConcreteDurableChanges(t *testing.T) { + newStore := func(t *testing.T) (*DoltStore, context.Context) { + t.Helper() + store, cleanup := setupTestStore(t) + t.Cleanup(cleanup) + ctx, cancel := testContext(t) + t.Cleanup(cancel) + return store, ctx + } + t.Run("isolated wisp leaves dirty durable rows uncommitted", func(t *testing.T) { + store, ctx := newStore(t) + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + createPerm(t, ctx, store, "ops-staging-reopen-dirty") + createWisp(t, ctx, store, "ops-staging-reopen-wisp") + if err := store.CloseIssue(ctx, "ops-staging-reopen-wisp", "done", "tester", ""); err != nil { + t.Fatal(err) + } + before := reopenDoltHead(t, ctx, store) + stageReopenDirtyIssue(t, ctx, store, "ops-staging-reopen-dirty") + stageReopenDirtyEvent(t, ctx, store, "ops-staging-reopen-event", "ops-staging-reopen-dirty") + if _, err := operations.Reopen(ctx, publicops.ReopenRequest{Actor: "tester", IssueID: "ops-staging-reopen-wisp"}); err != nil { + t.Fatal(err) + } + if after := reopenDoltHead(t, ctx, store); after != before { + t.Fatalf("isolated adapter reopen changed HEAD from %s to %s", before, after) + } + assertReopenDirtyRowsUncommitted(t, ctx, store, "ops-staging-reopen-dirty", "ops-staging-reopen-event") + }) + t.Run("durable recompute stages issues only", func(t *testing.T) { + store, ctx := newStore(t) + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + createPerm(t, ctx, store, "ops-staging-reopen-depender") + createWisp(t, ctx, store, "ops-staging-reopen-flip") + if err := store.AddDependency(ctx, &types.Dependency{IssueID: "ops-staging-reopen-depender", DependsOnID: "ops-staging-reopen-flip", Type: types.DepBlocks}, "tester"); err != nil { + t.Fatal(err) + } + if err := store.CloseIssue(ctx, "ops-staging-reopen-flip", "done", "tester", ""); err != nil { + t.Fatal(err) + } + commitReopenIssueWorkingSet(t, ctx, store, "seed closed wisp") + before := reopenDoltHead(t, ctx, store) + stageReopenDirtyEvent(t, ctx, store, "ops-staging-reopen-flip-event", "ops-staging-reopen-depender") + if _, err := operations.Reopen(ctx, publicops.ReopenRequest{Actor: "tester", IssueID: "ops-staging-reopen-flip"}); err != nil { + t.Fatal(err) + } + if after := reopenDoltHead(t, ctx, store); after == before { + t.Fatal("durable recompute did not advance HEAD") + } + var blocked bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", "ops-staging-reopen-depender").Scan(&blocked); err != nil || !blocked { + t.Fatalf("committed durable recompute = %t, %v", blocked, err) + } + // events is dolt_ignored since migration 0062 (bd-red8u): the unrelated + // audit row has no HEAD state and cannot ride the issues commit, but it + // must survive it in the working set. assertEventsNotCommitted keeps the + // plane invariant pinned here, where the recompute does advance HEAD. + var events int + if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE id = ?", "ops-staging-reopen-flip-event").Scan(&events); err != nil || events != 1 { + t.Fatalf("unrelated working-set event = %d, %v", events, err) + } + assertEventsNotCommitted(ctx, t, store.db) + }) +} + +func TestIssueOperationsUpdateClaimPatchAppliesAfterClaim(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + issue := &types.Issue{ID: "ops-staging-claim-patch", Title: "claim patch", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + + result, err := operations.Update(ctx, publicops.UpdateRequest{ + Actor: "worker", + IssueID: issue.ID, + Claim: true, + Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen}, + Assignee: publicops.Field[string]{Set: true}, + }, + }) + if err != nil { + t.Fatal(err) + } + if !result.Changed || result.Issue.Status != publicops.StatusOpen || result.Issue.Assignee != "" { + t.Fatalf("claim then patch = %#v, want open and unassigned", result) + } +} + +func TestIssueOperationsUpdateInvalidIssueTypePreservesValidationSentinel(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + issue := &types.Issue{ID: "ops-staging-invalid-type", Title: "invalid type", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: "not-a-type"}}}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("invalid issue type error = %v, want ErrValidation", err) + } +} + +func TestIssueOperationsUpdateNotesConflictPreservesValidationSentinel(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + issue := &types.Issue{ID: "ops-staging-notes-conflict", Title: "notes conflict", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", + IssueID: issue.ID, + Patch: publicops.IssuePatch{ + Notes: publicops.Field[string]{Set: true, Value: "replacement"}, + AppendNotes: publicops.Field[string]{Set: true, Value: "append"}, + }, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("notes conflict error = %v, want ErrValidation", err) + } + stored, err := store.GetIssue(ctx, issue.ID) + if err != nil || stored.Notes != "before" { + t.Fatalf("notes conflict persisted notes = %q, %v; want before", stored.Notes, err) + } +} + +func TestIssueOperationsUpdateParentStagesBlockedStateAndRollsBackFailure(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + issues := []*types.Issue{ + {ID: "ops-staging-parent-blocker", Title: "blocker", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + {ID: "ops-staging-parent-clean", Title: "clean parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic}, + {ID: "ops-staging-parent-blocked", Title: "blocked parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic}, + {ID: "ops-staging-parent-child", Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + {ID: "ops-staging-parent-rollback", Title: "rollback child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + } + for _, issue := range issues { + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + } + for _, dependency := range []*types.Dependency{ + {IssueID: "ops-staging-parent-blocked", DependsOnID: "ops-staging-parent-blocker", Type: types.DepBlocks}, + {IssueID: "ops-staging-parent-child", DependsOnID: "ops-staging-parent-clean", Type: types.DepParentChild}, + {IssueID: "ops-staging-parent-rollback", DependsOnID: "ops-staging-parent-blocked", Type: types.DepParentChild}, + } { + if err := store.AddDependency(ctx, dependency, "seed"); err != nil { + t.Fatal(err) + } + } + if err := store.Commit(ctx, "seed blocked parent state"); err != nil { + t.Fatal(err) + } + operations, err := NewIssueOperations(store) + if err != nil { + t.Fatal(err) + } + + result, err := operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", + IssueID: "ops-staging-parent-child", + Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-blocked"}}, + }) + if err != nil || !result.Changed || issueParentIDs(result.Issue) != "ops-staging-parent-blocked" { + t.Fatalf("blocked parent replacement = %#v, %v", result, err) + } + var workingBlocked, headBlocked bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", "ops-staging-parent-child").Scan(&workingBlocked); err != nil { + t.Fatal(err) + } + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", "ops-staging-parent-child").Scan(&headBlocked); err != nil { + t.Fatal(err) + } + if !workingBlocked || !headBlocked { + t.Fatalf("blocked child state = working %t, HEAD %t; want both true", workingBlocked, headBlocked) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", + IssueID: "ops-staging-parent-rollback", + Patch: publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "must rollback"}, + ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-missing"}, + }, + }) + if err == nil { + t.Fatal("missing parent replacement succeeded") + } + rolledBack, err := store.GetIssue(ctx, "ops-staging-parent-rollback") + if err != nil { + t.Fatal(err) + } + dependencies, err := store.GetDependencyRecords(ctx, rolledBack.ID) + if err != nil { + t.Fatal(err) + } + if rolledBack.Title != "rollback child" || !hasIssueOperationDependency(dependencies, rolledBack.ID, "ops-staging-parent-blocked", types.DepParentChild, "{}", "") { + t.Fatalf("failed parent replacement persisted issue = %#v, dependencies %#v", rolledBack, dependencies) + } + var rollbackWorkingTitle, rollbackHeadTitle string + if err := store.db.QueryRowContext(ctx, "SELECT title, is_blocked FROM issues WHERE id = ?", rolledBack.ID).Scan(&rollbackWorkingTitle, &workingBlocked); err != nil { + t.Fatal(err) + } + if err := store.db.QueryRowContext(ctx, "SELECT title, is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", rolledBack.ID).Scan(&rollbackHeadTitle, &headBlocked); err != nil { + t.Fatal(err) + } + if rollbackWorkingTitle != "rollback child" || rollbackHeadTitle != "rollback child" || !workingBlocked || !headBlocked { + t.Fatalf("failed parent replacement state = working (%q, %t), HEAD (%q, %t)", rollbackWorkingTitle, workingBlocked, rollbackHeadTitle, headBlocked) + } +} diff --git a/internal/storage/dolt/issue_operations_tx.go b/internal/storage/dolt/issue_operations_tx.go new file mode 100644 index 000000000..60f9f3a15 --- /dev/null +++ b/internal/storage/dolt/issue_operations_tx.go @@ -0,0 +1,27 @@ +package dolt + +import ( + "context" + "database/sql" + "sort" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" +) + +func (s *DoltStore) runIssueOperationTx(ctx context.Context, commitMsg string, fn func(*sql.Tx) (storageissueops.ChangedTables, error)) error { + return s.withRetryTx(ctx, func(tx *sql.Tx) error { + tables, err := fn(tx) + if err != nil { + return err + } + if len(tables) == 0 { + return nil + } + staged := make([]string, 0, len(tables)) + for table := range tables { + staged = append(staged, table) + } + sort.Strings(staged) + return s.doltAddAndCommitInTx(ctx, tx, staged, commitMsg) + }) +} diff --git a/internal/storage/dolt/issues.go b/internal/storage/dolt/issues.go index 514275a90..2361d4843 100644 --- a/internal/storage/dolt/issues.go +++ b/internal/storage/dolt/issues.go @@ -209,9 +209,13 @@ func (s *DoltStore) UpdateIssue(ctx context.Context, id string, updates map[stri // (https://www.dolthub.com/blog/2023-10-23-hold-my-beer/) — so retry is the // only safety net. withRetryTx owns BeginTx and the final Commit. return s.withRetryTx(ctx, func(tx *sql.Tx) error { - if _, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor); err != nil { + result, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor) + if err != nil { return err } + if !result.Changed { + return nil + } for _, table := range []string{"issues", "events"} { _ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table) @@ -283,9 +287,13 @@ func (s *DoltStore) UpdateIssueChecked(ctx context.Context, id string, updates m if err := issueops.CheckExpectedFieldsInTx(ctx, tx, id, opts.ExpectedAssignee, opts.ExpectedStatus); err != nil { return err } - if _, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor); err != nil { + result, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor) + if err != nil { return err } + if !result.Changed { + return nil + } for _, table := range []string{"issues", "events"} { _ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table) @@ -568,23 +576,26 @@ func (s *DoltStore) UnclaimIssueIfAssignee(ctx context.Context, id string, actor }) } -// ReopenIssue reopens a closed issue, setting status to open and clearing -// closed_at and defer_until. If reason is non-empty, it is recorded as a comment. -// Wraps UpdateIssue for Dolt-specific concerns (wisp routing, DOLT_COMMIT, etc.). +// ReopenIssue reopens a done-category issue atomically and stages only the +// versioned tables that this transaction concretely changed. func (s *DoltStore) ReopenIssue(ctx context.Context, id string, reason string, actor string) error { - updates := map[string]interface{}{ - "status": string(types.StatusOpen), - "defer_until": nil, - } - if err := s.UpdateIssue(ctx, id, updates, actor); err != nil { - return err - } - if reason != "" { - if err := s.AddComment(ctx, id, actor, reason); err != nil { - return fmt.Errorf("reopen comment: %w", err) + return s.withRetryTx(ctx, func(tx *sql.Tx) error { + res, err := issueops.ReopenIssueInTx(ctx, tx, id, reason, actor) + if err != nil { + return err } - } - return nil + if !res.Changed { + return nil + } + switch { + case !res.IsWisp: + return s.doltAddAndCommitInTx(ctx, tx, []string{"issues", "events"}, fmt.Sprintf("bd: reopen %s", id)) + case res.IssueRowsChanged: + return s.doltAddAndCommitInTx(ctx, tx, []string{"issues"}, fmt.Sprintf("bd: reopen %s", id)) + default: + return nil + } + }) } // UpdateIssueType changes the issue_type field of an issue. @@ -654,7 +665,7 @@ func (s *DoltStore) CloseIssueChecked(ctx context.Context, id string, actor stri if err != nil { return err } - result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed} + result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed, OpenChildren: res.OpenChildren} // Dolt versioning for permanent issues. // GH#2455: Stage only the tables we modified, then commit without -A. @@ -937,8 +948,6 @@ func generateHashID(prefix, title, description, creator string, timestamp time.T // Thin wrappers around exported issueops functions, kept for internal callers. var ( isAllowedUpdateField = issueops.IsAllowedUpdateField - manageClosedAt = issueops.ManageClosedAt - determineEventType = issueops.DetermineEventType ) // Aliases for shared nullable helpers from issueops. diff --git a/internal/storage/dolt/reopen_category_test.go b/internal/storage/dolt/reopen_category_test.go new file mode 100644 index 000000000..174fc8c14 --- /dev/null +++ b/internal/storage/dolt/reopen_category_test.go @@ -0,0 +1,225 @@ +package dolt + +import ( + "context" + "database/sql" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +func TestReopenIssueCategorySemantics(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + setStatus := func(t *testing.T, table, id, status string) int64 { + t.Helper() + if _, err := store.db.ExecContext(ctx, ` + UPDATE `+table+` + SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?, + defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY) + WHERE id = ? + `, status, "completed", "session-1", id); err != nil { + t.Fatalf("set %s status: %v", table, err) + } + var rowLock int64 + if err := store.db.QueryRowContext(ctx, + "SELECT row_lock FROM "+table+" WHERE id = ?", id).Scan(&rowLock); err != nil { + t.Fatalf("read %s row_lock: %v", table, err) + } + return rowLock + } + + insertCustomStatus := func(t *testing.T, name string, category types.StatusCategory) { + t.Helper() + if _, err := store.db.ExecContext(ctx, + "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", name, string(category)); err != nil { + t.Fatalf("insert custom status: %v", err) + } + } + + assertLifecycleCleared := func(t *testing.T, table, id string, priorRowLock int64) { + t.Helper() + var status, reason, session string + var closedAt, deferred sql.NullTime + var rowLock int64 + if err := store.db.QueryRowContext(ctx, ` + SELECT status, closed_at, close_reason, closed_by_session, defer_until, row_lock + FROM `+table+` WHERE id = ? + `, id).Scan(&status, &closedAt, &reason, &session, &deferred, &rowLock); err != nil { + t.Fatalf("read reopened %s: %v", table, err) + } + if status != string(types.StatusOpen) || closedAt.Valid || reason != "" || session != "" || deferred.Valid { + t.Fatalf("reopened lifecycle = status=%q closed_at=%v reason=%q session=%q defer=%v", + status, closedAt.Valid, reason, session, deferred.Valid) + } + if rowLock == 0 || rowLock == priorRowLock { + t.Fatalf("reopened row_lock = %d, want fresh non-zero token different from %d", rowLock, priorRowLock) + } + } + + t.Run("custom done permanent clears lifecycle and records events", func(t *testing.T) { + const id = "ro-category-permanent" + createPerm(t, ctx, store, id) + insertCustomStatus(t, "archived", types.CategoryDone) + priorRowLock := setStatus(t, "issues", id, "archived") + before := reopenDoltHead(t, ctx, store) + + if err := store.ReopenIssue(ctx, id, "needs review", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + assertLifecycleCleared(t, "issues", id, priorRowLock) + if after := reopenDoltHead(t, ctx, store); after == before { + t.Fatal("permanent reopen did not create a Dolt commit") + } + + var reopened, comments int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", id, string(types.EventReopened)).Scan(&reopened); err != nil { + t.Fatalf("count reopened events: %v", err) + } + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", id, string(types.EventCommented)).Scan(&comments); err != nil { + t.Fatalf("count comment events: %v", err) + } + if reopened != 1 || comments != 1 { + t.Fatalf("events = reopened:%d comments:%d, want 1 each", reopened, comments) + } + }) + + t.Run("custom done wisp mutates without a Dolt commit", func(t *testing.T) { + const id = "ro-category-wisp" + createWisp(t, ctx, store, id) + insertCustomStatus(t, "retired", types.CategoryDone) + priorRowLock := setStatus(t, "wisps", id, "retired") + before := reopenDoltHead(t, ctx, store) + + if err := store.ReopenIssue(ctx, id, "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + assertLifecycleCleared(t, "wisps", id, priorRowLock) + if after := reopenDoltHead(t, ctx, store); after != before { + t.Fatalf("wisp reopen changed Dolt HEAD from %s to %s", before, after) + } + }) + + t.Run("wisp reopen commits durable depender recomputation", func(t *testing.T) { + const ( + dependerID = "ro-category-wisp-depender" + targetID = "ro-category-wisp-target" + ) + createPerm(t, ctx, store, dependerID) + createWisp(t, ctx, store, targetID) + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: dependerID, DependsOnID: targetID, Type: types.DepBlocks, + }, "tester"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + if err := store.CloseIssue(ctx, targetID, "done", "tester", ""); err != nil { + t.Fatalf("CloseIssue: %v", err) + } + before := reopenDoltHead(t, ctx, store) + + if err := store.ReopenIssue(ctx, targetID, "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + var blocked bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", dependerID).Scan(&blocked); err != nil { + t.Fatalf("read durable depender: %v", err) + } + if !blocked { + t.Fatal("permanent depender was not re-blocked by reopened wisp") + } + if after := reopenDoltHead(t, ctx, store); after == before { + t.Fatal("wisp reopen with durable recomputation did not create a Dolt commit") + } + }) + + t.Run("custom non done and unknown statuses stay untouched", func(t *testing.T) { + const activeID = "ro-category-active" + const unknownID = "ro-category-unknown" + createPerm(t, ctx, store, activeID) + createPerm(t, ctx, store, unknownID) + insertCustomStatus(t, "triaged", types.CategoryActive) + setStatus(t, "issues", activeID, "triaged") + setStatus(t, "issues", unknownID, "unknown-status") + + for _, check := range []struct { + id string + status string + }{{activeID, "triaged"}, {unknownID, "unknown-status"}} { + before := reopenDoltHead(t, ctx, store) + var beforeEvents int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ?", check.id).Scan(&beforeEvents); err != nil { + t.Fatalf("count events before reopen for %s: %v", check.id, err) + } + if err := store.ReopenIssue(ctx, check.id, "ignored", "tester"); err != nil { + t.Fatalf("ReopenIssue(%s): %v", check.id, err) + } + if after := reopenDoltHead(t, ctx, store); after != before { + t.Fatalf("ineligible reopen for %s changed Dolt HEAD", check.id) + } + var status, reason string + var afterEvents int + if err := store.db.QueryRowContext(ctx, + "SELECT status, close_reason FROM issues WHERE id = ?", check.id).Scan(&status, &reason); err != nil { + t.Fatalf("read unchanged issue %s: %v", check.id, err) + } + if status != check.status || reason != "completed" { + t.Fatalf("unchanged issue %s = status:%q reason:%q", check.id, status, reason) + } + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ?", check.id).Scan(&afterEvents); err != nil { + t.Fatalf("count events for %s: %v", check.id, err) + } + if afterEvents != beforeEvents { + t.Fatalf("ineligible reopen for %s changed event count from %d to %d", check.id, beforeEvents, afterEvents) + } + } + }) + + t.Run("literal open is a strict no-op", func(t *testing.T) { + const id = "ro-category-open" + createPerm(t, ctx, store, id) + before := reopenDoltHead(t, ctx, store) + beforeEvents, err := store.GetEvents(ctx, id, 0) + if err != nil { + t.Fatalf("GetEvents before reopen: %v", err) + } + + if err := store.ReopenIssue(ctx, id, "ignored", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + if after := reopenDoltHead(t, ctx, store); after != before { + t.Fatalf("literal-open no-op changed Dolt HEAD from %s to %s", before, after) + } + afterEvents, err := store.GetEvents(ctx, id, 0) + if err != nil { + t.Fatalf("GetEvents after reopen: %v", err) + } + if len(afterEvents) != len(beforeEvents) { + t.Fatalf("literal-open no-op events = %+v, want no new events", afterEvents) + } + }) + + t.Run("missing target wraps not found", func(t *testing.T) { + err := store.ReopenIssue(ctx, "ro-category-missing", "", "tester") + if !errors.Is(err, storage.ErrNotFound) { + t.Fatalf("err = %v, want ErrNotFound", err) + } + }) +} + +func reopenDoltHead(t *testing.T, ctx context.Context, store *DoltStore) string { + t.Helper() + var head string + if err := store.db.QueryRowContext(ctx, "SELECT HASHOF('HEAD')").Scan(&head); err != nil { + t.Fatalf("read Dolt HEAD: %v", err) + } + return head +} diff --git a/internal/storage/dolt/reopen_routing_test.go b/internal/storage/dolt/reopen_routing_test.go new file mode 100644 index 000000000..5e73dbf20 --- /dev/null +++ b/internal/storage/dolt/reopen_routing_test.go @@ -0,0 +1,154 @@ +package dolt + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "io" + "reflect" + "strings" + "sync" + "testing" +) + +// reopenPromotionDriver models the promotion seam: a pre-transaction probe +// finds an active wisp, while the write transaction sees the same ID only in +// the permanent issues table. +type reopenPromotionDriver struct { + mu sync.Mutex + + inTx bool + preTxWispProbe bool + doltAddTables []string + doltCommitCalled bool + issueUpdated bool +} + +func (d *reopenPromotionDriver) Open(string) (driver.Conn, error) { + return &reopenPromotionConn{driver: d}, nil +} + +func (d *reopenPromotionDriver) Connect(context.Context) (driver.Conn, error) { + return &reopenPromotionConn{driver: d}, nil +} + +func (d *reopenPromotionDriver) Driver() driver.Driver { return d } + +type reopenPromotionConn struct { + driver *reopenPromotionDriver +} + +func (c *reopenPromotionConn) Prepare(string) (driver.Stmt, error) { + return nil, errors.New("reopen promotion driver does not prepare statements") +} + +func (c *reopenPromotionConn) Close() error { return nil } + +func (c *reopenPromotionConn) Begin() (driver.Tx, error) { + c.driver.mu.Lock() + c.driver.inTx = true + c.driver.mu.Unlock() + return &reopenPromotionTx{driver: c.driver}, nil +} + +func (c *reopenPromotionConn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + c.driver.mu.Lock() + defer c.driver.mu.Unlock() + + if strings.Contains(query, "SELECT 1 FROM wisps WHERE id = ? LIMIT 1") { + if !c.driver.inTx { + c.driver.preTxWispProbe = true + return &reopenPromotionRows{columns: []string{"exists"}, values: [][]driver.Value{{int64(1)}}}, nil + } + return &reopenPromotionRows{columns: []string{"exists"}}, nil + } + if strings.Contains(query, "SELECT status FROM issues WHERE id = ?") { + return &reopenPromotionRows{ + columns: []string{"status"}, + values: [][]driver.Value{{string("closed")}}, + }, nil + } + if strings.Contains(query, "CALL DOLT_ADD") && len(args) == 1 { + if table, ok := args[0].Value.(string); ok { + c.driver.doltAddTables = append(c.driver.doltAddTables, table) + } + } + if strings.Contains(query, "CALL DOLT_COMMIT") { + c.driver.doltCommitCalled = true + } + return &reopenPromotionRows{columns: []string{"value"}}, nil +} + +func (c *reopenPromotionConn) ExecContext(_ context.Context, query string, _ []driver.NamedValue) (driver.Result, error) { + c.driver.mu.Lock() + defer c.driver.mu.Unlock() + + if strings.Contains(query, "UPDATE issues") && strings.Contains(query, "SET status") { + c.driver.issueUpdated = true + return driver.RowsAffected(1), nil + } + return driver.RowsAffected(0), nil +} + +type reopenPromotionTx struct { + driver *reopenPromotionDriver +} + +func (t *reopenPromotionTx) Commit() error { + t.driver.mu.Lock() + t.driver.inTx = false + t.driver.mu.Unlock() + return nil +} + +func (t *reopenPromotionTx) Rollback() error { + t.driver.mu.Lock() + t.driver.inTx = false + t.driver.mu.Unlock() + return nil +} + +type reopenPromotionRows struct { + columns []string + values [][]driver.Value + index int +} + +func (r *reopenPromotionRows) Columns() []string { return r.columns } +func (r *reopenPromotionRows) Close() error { return nil } +func (r *reopenPromotionRows) Next(dest []driver.Value) error { + if r.index >= len(r.values) { + return io.EOF + } + copy(dest, r.values[r.index]) + r.index++ + return nil +} + +var _ driver.Connector = (*reopenPromotionDriver)(nil) + +func TestReopenIssuePromotionRaceUsesTransactionRouting(t *testing.T) { + routingDriver := &reopenPromotionDriver{} + store := &DoltStore{db: sql.OpenDB(routingDriver)} + defer func() { _ = store.db.Close() }() + + if err := store.ReopenIssue(context.Background(), "promoted-wisp", "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + + routingDriver.mu.Lock() + defer routingDriver.mu.Unlock() + if routingDriver.preTxWispProbe { + t.Fatal("reopen probed wisp routing before its write transaction") + } + if !routingDriver.issueUpdated { + t.Fatal("promoted permanent issue was not updated") + } + if got, want := routingDriver.doltAddTables, []string{"issues", "events"}; !reflect.DeepEqual(got, want) { + t.Fatalf("DOLT_ADD tables = %v, want %v for promoted permanent issue", got, want) + } + if !routingDriver.doltCommitCalled { + t.Fatal("promoted permanent issue did not create a Dolt commit") + } +} diff --git a/internal/storage/dolt/reopen_staging_test.go b/internal/storage/dolt/reopen_staging_test.go new file mode 100644 index 000000000..d53b77862 --- /dev/null +++ b/internal/storage/dolt/reopen_staging_test.go @@ -0,0 +1,187 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func TestReopenWispStagesOnlyConcreteIssueChanges(t *testing.T) { + newStore := func(t *testing.T) (*DoltStore, context.Context) { + t.Helper() + store, cleanup := setupTestStore(t) + t.Cleanup(cleanup) + ctx, cancel := testContext(t) + t.Cleanup(cancel) + return store, ctx + } + + t.Run("isolated wisp leaves unrelated dirty issues and events uncommitted", func(t *testing.T) { + store, ctx := newStore(t) + const ( + wispID = "ro-stage-isolated-wisp" + issueID = "ro-stage-unrelated-issue" + eventID = "ro-stage-unrelated-event" + ) + createPerm(t, ctx, store, issueID) + createWisp(t, ctx, store, wispID) + if err := store.CloseIssue(ctx, wispID, "done", "tester", ""); err != nil { + t.Fatalf("CloseIssue: %v", err) + } + before := reopenDoltHead(t, ctx, store) + stageReopenDirtyIssue(t, ctx, store, issueID) + stageReopenDirtyEvent(t, ctx, store, eventID, issueID) + + if err := store.ReopenIssue(ctx, wispID, "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + if after := reopenDoltHead(t, ctx, store); after != before { + t.Fatalf("isolated wisp reopen changed HEAD from %s to %s", before, after) + } + assertReopenDirtyRowsUncommitted(t, ctx, store, issueID, eventID) + }) + + t.Run("affected issue without a SQL flip remains uncommitted", func(t *testing.T) { + store, ctx := newStore(t) + const ( + dependerID = "ro-stage-no-flip-depender" + wispID = "ro-stage-no-flip-wisp" + dirtyID = "ro-stage-no-flip-dirty" + ) + createPerm(t, ctx, store, dependerID) + createPerm(t, ctx, store, dirtyID) + createWisp(t, ctx, store, wispID) + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks, + }, "tester"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + if err := store.CloseIssue(ctx, wispID, "done", "tester", ""); err != nil { + t.Fatalf("CloseIssue: %v", err) + } + if _, err := store.db.ExecContext(ctx, + "UPDATE issues SET is_blocked = 1 WHERE id = ?", dependerID); err != nil { + t.Fatalf("pre-converge affected issue: %v", err) + } + before := reopenDoltHead(t, ctx, store) + stageReopenDirtyIssue(t, ctx, store, dirtyID) + + if err := store.ReopenIssue(ctx, wispID, "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + if after := reopenDoltHead(t, ctx, store); after != before { + t.Fatalf("no-flip wisp reopen changed HEAD from %s to %s", before, after) + } + var headNotes string + if err := store.db.QueryRowContext(ctx, + "SELECT notes FROM issues AS OF 'HEAD' WHERE id = ?", dirtyID).Scan(&headNotes); err != nil { + t.Fatalf("read dirty issue AS OF HEAD: %v", err) + } + if headNotes == "uncommitted reopen sentinel" { + t.Fatal("no-flip wisp reopen staged an unrelated dirty issue") + } + }) + + t.Run("durable issue flip commits issues but not unrelated event", func(t *testing.T) { + store, ctx := newStore(t) + const ( + dependerID = "ro-stage-flip-depender" + wispID = "ro-stage-flip-wisp" + eventID = "ro-stage-flip-dirty-event" + ) + createPerm(t, ctx, store, dependerID) + createWisp(t, ctx, store, wispID) + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks, + }, "tester"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + if err := store.CloseIssue(ctx, wispID, "done", "tester", ""); err != nil { + t.Fatalf("CloseIssue: %v", err) + } + commitReopenIssueWorkingSet(t, ctx, store, "seed closed-wisp projection") + before := reopenDoltHead(t, ctx, store) + stageReopenDirtyEvent(t, ctx, store, eventID, dependerID) + + if err := store.ReopenIssue(ctx, wispID, "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + if after := reopenDoltHead(t, ctx, store); after == before { + t.Fatal("wisp reopen with an actual issues-row flip did not advance HEAD") + } + var blocked bool + if err := store.db.QueryRowContext(ctx, + "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", dependerID).Scan(&blocked); err != nil { + t.Fatalf("read durable depender AS OF HEAD: %v", err) + } + if !blocked { + t.Fatal("recomputed durable issue is not visible AS OF HEAD") + } + // events is dolt_ignored since migration 0062 (bd-red8u), so it has no + // HEAD state of its own: the sentinel row cannot ride the issues commit, + // but it must survive that commit in the working set. The plane + // invariant — no events row ever reaches committed history — is what + // assertEventsNotCommitted still checks here, where HEAD does advance. + var workingEvent int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE id = ?", eventID).Scan(&workingEvent); err != nil { + t.Fatalf("read dirty event in working set: %v", err) + } + if workingEvent != 1 { + t.Fatalf("dirty working-set event count = %d, want 1 (the issues commit dropped it)", workingEvent) + } + assertEventsNotCommitted(ctx, t, store.db) + }) +} + +func stageReopenDirtyIssue(t *testing.T, ctx context.Context, store *DoltStore, id string) { + t.Helper() + if _, err := store.db.ExecContext(ctx, + "UPDATE issues SET notes = ? WHERE id = ?", "uncommitted reopen sentinel", id); err != nil { + t.Fatalf("stage dirty issue: %v", err) + } +} + +func stageReopenDirtyEvent(t *testing.T, ctx context.Context, store *DoltStore, eventID, issueID string) { + t.Helper() + if _, err := store.db.ExecContext(ctx, + "INSERT INTO events (id, issue_id, event_type, actor, old_value, new_value) VALUES (?, ?, ?, ?, ?, ?)", + eventID, issueID, string(types.EventUpdated), "other", "", "uncommitted reopen event", + ); err != nil { + t.Fatalf("stage dirty event: %v", err) + } +} + +func assertReopenDirtyRowsUncommitted( + t *testing.T, ctx context.Context, store *DoltStore, issueID, eventID string, +) { + t.Helper() + var headNotes string + if err := store.db.QueryRowContext(ctx, + "SELECT notes FROM issues AS OF 'HEAD' WHERE id = ?", issueID).Scan(&headNotes); err != nil { + t.Fatalf("read dirty issue AS OF HEAD: %v", err) + } + if headNotes == "uncommitted reopen sentinel" { + t.Fatal("isolated wisp reopen staged an unrelated dirty issue") + } + // events is dolt_ignored since migration 0062 (bd-red8u): there is no HEAD + // state to read. Both callers already assert that HEAD did not move at all, + // which covers "nothing was published"; what is left to check about the + // sentinel event is that the reopen did not destroy it in the working set. + var workingEvent int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE id = ?", eventID).Scan(&workingEvent); err != nil { + t.Fatalf("read dirty event in working set: %v", err) + } + if workingEvent != 1 { + t.Fatalf("dirty working-set event count = %d, want 1 (the reopen dropped it)", workingEvent) + } +} + +func commitReopenIssueWorkingSet(t *testing.T, ctx context.Context, store *DoltStore, message string) { + t.Helper() + if err := store.doltAddAndCommit(ctx, []string{"issues"}, message); err != nil { + t.Fatalf("doltAddAndCommit issues: %v", err) + } +} diff --git a/internal/storage/dolt/transaction.go b/internal/storage/dolt/transaction.go index 9f3829019..9925471b3 100644 --- a/internal/storage/dolt/transaction.go +++ b/internal/storage/dolt/transaction.go @@ -33,6 +33,7 @@ type doltTransaction struct { // role: it deliberately drops wisp_* tables because they are dolt-ignored. wroteRegularDep bool wroteWispDep bool + lifecycle bool } func (t *doltTransaction) txFor(table string) *sql.Tx { @@ -68,6 +69,31 @@ func (s *DoltStore) RunInTransaction(ctx context.Context, commitMsg string, fn f }) } +// RunInIssueLifecycleTransaction runs a lifecycle transition and its durable +// side effects through one SQL transaction and one Dolt commit attempt. +func (s *DoltStore) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx storage.IssueLifecycleTransaction) error) error { + return s.withRetryTx(ctx, func(sqlTx *sql.Tx) error { + tx := &doltTransaction{regularTx: sqlTx, ignoredTx: sqlTx, store: s, lifecycle: true} + if err := fn(tx); err != nil { + return err + } + tables := tx.dirtyTableNames() + if len(tables) == 0 { + return nil + } + return s.doltAddAndCommitInTx(ctx, sqlTx, tables, commitMsg) + }) +} + +func (t *doltTransaction) dirtyTableNames() []string { + tables := make([]string, 0, len(t.dirty.DirtyTables())) + for table := range t.dirty.DirtyTables() { + tables = append(tables, table) + } + sort.Strings(tables) + return tables +} + func (s *DoltStore) runDoltTransaction(ctx context.Context, commitMsg string, fn func(tx storage.Transaction) error) error { // Pin a single connection for the entire operation: SQL transaction, // config protection, and DOLT_COMMIT must all run on the same Dolt @@ -650,10 +676,22 @@ func (t *doltTransaction) UpdateIssue(ctx context.Context, id string, updates ma } } - if _, err := issueops.UpdateIssueWithoutEventInTx(ctx, t.txFor(table), id, updates, actor); err != nil { + update := issueops.UpdateIssueWithoutEventInTx + if t.lifecycle { + update = issueops.UpdateIssueInTx + } + result, err := update(ctx, t.txFor(table), id, updates, actor) + if err != nil { return wrapExecError("update issue in tx", err) } + if !result.Changed { + return nil + } t.dirty.MarkDirty(table) + if t.lifecycle { + _, _, eventTable, _ := issueops.WispTableRouting(table == "wisps") + t.dirty.MarkDirty(eventTable) + } return nil } @@ -674,9 +712,33 @@ func (t *doltTransaction) CloseIssue(ctx context.Context, id string, reason stri } t.dirty.MarkDirty(table) t.dirty.MarkDirty(eventTable) + if result.IssueRowsChanged { + t.dirty.MarkDirty("issues") + } return nil } +// ReopenIssueWithResult reopens an issue within this transaction and reports +// whether the lifecycle state changed. +func (t *doltTransaction) ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) { + table, eventTable := "issues", "events" + if t.isActiveWisp(ctx, id) { + table, eventTable = "wisps", "wisp_events" + } + result, err := issueops.ReopenIssueInTx(ctx, t.txFor(table), id, reason, actor) + if err != nil { + return false, wrapExecError("reopen issue in tx", err) + } + if result.Changed { + t.dirty.MarkDirty(table) + t.dirty.MarkDirty(eventTable) + if result.IssueRowsChanged { + t.dirty.MarkDirty("issues") + } + } + return result.Changed, nil +} + func (t *doltTransaction) DeleteIssue(ctx context.Context, id string) error { isWisp := t.isActiveWisp(ctx, id) table := "issues" diff --git a/internal/storage/dolt/transaction_wisp_lifecycle_persistence_test.go b/internal/storage/dolt/transaction_wisp_lifecycle_persistence_test.go new file mode 100644 index 000000000..b49b2a875 --- /dev/null +++ b/internal/storage/dolt/transaction_wisp_lifecycle_persistence_test.go @@ -0,0 +1,368 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +// TestRunInTransactionWispLifecyclePersistsDurableDependent verifies that a +// transactional lifecycle transition of an ignored wisp still publishes the +// durable is_blocked recomputation of an issue that depends on it. +func TestRunInTransactionWispLifecyclePersistsDurableDependent(t *testing.T) { + ctx, store := newTransactionWispLifecycleStore(t) + + t.Run("close", func(t *testing.T) { + const ( + dependerID = "tx-wisp-close-depender" + wispID = "tx-wisp-close-blocker" + ) + seedTransactionWispBlocker(t, ctx, store, dependerID, wispID) + before := transactionWispLifecycleHead(t, ctx, store) + + if err := store.RunInIssueLifecycleTransaction(ctx, "test: close wisp blocker", func(tx storage.IssueLifecycleTransaction) error { + return tx.CloseIssue(ctx, wispID, "done", "tester", "session") + }); err != nil { + t.Fatalf("RunInTransaction CloseIssue: %v", err) + } + + assertTransactionWispLifecyclePostState(t, ctx, store, dependerID, before, false) + }) + + t.Run("reopen", func(t *testing.T) { + const ( + dependerID = "tx-wisp-reopen-depender" + wispID = "tx-wisp-reopen-blocker" + ) + seedTransactionWispBlocker(t, ctx, store, dependerID, wispID) + if err := store.CloseIssue(ctx, wispID, "done", "tester", "session"); err != nil { + t.Fatalf("seed CloseIssue: %v", err) + } + if err := store.Commit(ctx, "test: seed closed wisp blocker"); err != nil { + t.Fatalf("Commit closed seed: %v", err) + } + before := transactionWispLifecycleHead(t, ctx, store) + + if err := store.RunInIssueLifecycleTransaction(ctx, "test: reopen wisp blocker", func(tx storage.IssueLifecycleTransaction) error { + changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester") + if err != nil { + return err + } + if !changed { + t.Fatal("transactional reopen reported Changed=false") + } + return nil + }); err != nil { + t.Fatalf("RunInTransaction reopen: %v", err) + } + + assertTransactionWispLifecyclePostState(t, ctx, store, dependerID, before, true) + }) +} + +// TestRunInIssueLifecycleTransactionStandaloneWispPersistsWithoutDoltCommit +// verifies that ignored-only lifecycle work commits its SQL transaction without +// attempting a version-control commit. +func TestRunInIssueLifecycleTransactionStandaloneWispPersistsWithoutDoltCommit(t *testing.T) { + ctx, store := newTransactionWispLifecycleStore(t) + + t.Run("close", func(t *testing.T) { + const wispID = "tx-standalone-wisp-close" + createWisp(t, ctx, store, wispID) + before := transactionWispLifecycleHead(t, ctx, store) + + if err := store.RunInIssueLifecycleTransaction(ctx, "test: close standalone wisp", func(tx storage.IssueLifecycleTransaction) error { + return tx.CloseIssue(ctx, wispID, "done", "tester", "session") + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction CloseIssue: %v", err) + } + assertStandaloneWispLifecycleState(t, ctx, store, wispID, before, types.StatusClosed) + }) + + t.Run("reopen", func(t *testing.T) { + const wispID = "tx-standalone-wisp-reopen" + createWisp(t, ctx, store, wispID) + if err := store.CloseIssue(ctx, wispID, "done", "tester", "session"); err != nil { + t.Fatalf("seed CloseIssue: %v", err) + } + before := transactionWispLifecycleHead(t, ctx, store) + + if err := store.RunInIssueLifecycleTransaction(ctx, "test: reopen standalone wisp", func(tx storage.IssueLifecycleTransaction) error { + changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester") + if err != nil { + return err + } + if !changed { + t.Fatal("transactional reopen reported Changed=false") + } + return nil + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction ReopenIssueWithResult: %v", err) + } + assertStandaloneWispLifecycleState(t, ctx, store, wispID, before, types.StatusOpen) + }) +} + +func TestRunInIssueLifecycleTransactionSameStatusDoesNotPublishUnrelatedDurableChanges(t *testing.T) { + ctx, store := newTransactionWispLifecycleStore(t) + const ( + targetID = "tx-same-status-target" + dirtyID = "tx-same-status-dirty" + ) + createPerm(t, ctx, store, targetID) + createPerm(t, ctx, store, dirtyID) + before := transactionWispLifecycleHead(t, ctx, store) + + if _, err := store.db.ExecContext(ctx, "UPDATE issues SET title = ? WHERE id = ?", "working-only title", dirtyID); err != nil { + t.Fatalf("stage unrelated issue edit: %v", err) + } + if _, err := store.db.ExecContext(ctx, + "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?", + "working-only event", dirtyID, string(types.EventCreated), + ); err != nil { + t.Fatalf("stage unrelated event edit: %v", err) + } + + if err := store.RunInIssueLifecycleTransaction(ctx, "test: same-status update", func(tx storage.IssueLifecycleTransaction) error { + return tx.UpdateIssue(ctx, targetID, map[string]interface{}{"status": types.StatusOpen}, "tester") + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction: %v", err) + } + if after := transactionWispLifecycleHead(t, ctx, store); after != before { + t.Errorf("same-status transaction changed HEAD from %s to %s", before, after) + } + + assertDirectSameStatusUnrelatedChangesWorkingOnly(t, ctx, store, dirtyID) +} + +func TestRunInIssueLifecycleTransactionStandaloneWispMutationDoesNotPublishUnrelatedDurableChanges(t *testing.T) { + ctx, store := newTransactionWispLifecycleStore(t) + const ( + durableID = "tx-wisp-isolation-durable" + wispID = "tx-wisp-isolation-wisp" + baselineLabel = "durable-baseline" + workingLabel = "durable-working-only" + removeWispLabel = "remove-from-wisp" + addWispLabel = "add-to-wisp" + ) + + createPerm(t, ctx, store, durableID) + if err := store.AddLabel(ctx, durableID, baselineLabel, "tester"); err != nil { + t.Fatalf("AddLabel durable baseline: %v", err) + } + createWisp(t, ctx, store, wispID) + if err := store.AddLabel(ctx, wispID, removeWispLabel, "tester"); err != nil { + t.Fatalf("AddLabel wisp baseline: %v", err) + } + if err := store.Commit(ctx, "test: seed durable baseline"); err != nil { + t.Fatalf("Commit baseline: %v", err) + } + before := transactionWispLifecycleHead(t, ctx, store) + + if _, err := store.db.ExecContext(ctx, "UPDATE issues SET title = ? WHERE id = ?", "durable working-only", durableID); err != nil { + t.Fatalf("stage durable issue edit: %v", err) + } + if _, err := store.db.ExecContext(ctx, "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?", + "durable working-only", durableID, string(types.EventCreated)); err != nil { + t.Fatalf("stage durable event edit: %v", err) + } + if _, err := store.db.ExecContext(ctx, "UPDATE labels SET label = ? WHERE issue_id = ? AND label = ?", + workingLabel, durableID, baselineLabel); err != nil { + t.Fatalf("stage durable label edit: %v", err) + } + + if err := store.RunInIssueLifecycleTransaction(ctx, "test: mutate standalone wisp", func(tx storage.IssueLifecycleTransaction) error { + if err := tx.UpdateIssue(ctx, wispID, map[string]interface{}{"title": "wisp updated"}, "tester"); err != nil { + return err + } + if err := tx.RemoveLabel(ctx, wispID, removeWispLabel, "tester"); err != nil { + return err + } + return tx.AddLabel(ctx, wispID, addWispLabel, "tester") + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction: %v", err) + } + if after := transactionWispLifecycleHead(t, ctx, store); after != before { + t.Errorf("standalone wisp mutation changed HEAD from %s to %s", before, after) + } + + wisp, err := store.GetIssue(ctx, wispID) + if err != nil { + t.Fatalf("GetIssue wisp: %v", err) + } + if wisp.Title != "wisp updated" { + t.Errorf("wisp title = %q, want %q", wisp.Title, "wisp updated") + } + labels, err := store.GetLabels(ctx, wispID) + if err != nil { + t.Fatalf("GetLabels wisp: %v", err) + } + if len(labels) != 1 || labels[0] != addWispLabel { + t.Errorf("wisp labels = %v, want [%s]", labels, addWispLabel) + } + events, err := store.GetEvents(ctx, wispID, 0) + if err != nil { + t.Fatalf("GetEvents wisp: %v", err) + } + eventCounts := make(map[types.EventType]int) + for _, event := range events { + eventCounts[event.EventType]++ + } + if eventCounts[types.EventUpdated] != 1 || eventCounts[types.EventLabelRemoved] != 1 || eventCounts[types.EventLabelAdded] != 2 { + t.Errorf("wisp event counts = updated:%d label_removed:%d label_added:%d", + eventCounts[types.EventUpdated], eventCounts[types.EventLabelRemoved], eventCounts[types.EventLabelAdded]) + } + + var workingTitle, headTitle string + if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues WHERE id = ?", durableID).Scan(&workingTitle); err != nil { + t.Fatalf("read working durable issue: %v", err) + } + if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", durableID).Scan(&headTitle); err != nil { + t.Fatalf("read durable issue AS OF HEAD: %v", err) + } + if workingTitle != "durable working-only" || headTitle != "perm "+durableID { + t.Errorf("durable issue titles = working:%q HEAD:%q", workingTitle, headTitle) + } + + var headLabelCount int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM labels AS OF 'HEAD' WHERE issue_id = ? AND label = ?", + durableID, workingLabel, + ).Scan(&headLabelCount); err != nil { + t.Fatalf("read durable label AS OF HEAD: %v", err) + } + if headLabelCount != 0 { + t.Errorf("durable working-only label count AS OF HEAD = %d, want 0", headLabelCount) + } + + // events is dolt_ignored since migration 0062 (bd-red8u): it has no HEAD + // state, so the working-only audit edit can only be read from the working + // set. "Nothing was published" is already carried by the HEAD-unchanged + // assertion above; what remains to check is that the wisp mutation left the + // unrelated audit edit intact. + var workingEventCount int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?", + durableID, string(types.EventCreated), "durable working-only", + ).Scan(&workingEventCount); err != nil { + t.Fatalf("read durable event in working set: %v", err) + } + if workingEventCount != 1 { + t.Errorf("durable working-only event count = %d, want 1", workingEventCount) + } +} + +func assertDirectSameStatusUnrelatedChangesWorkingOnly(t *testing.T, ctx context.Context, store *DoltStore, dirtyID string) { + t.Helper() + var workingTitle, headTitle string + if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues WHERE id = ?", dirtyID).Scan(&workingTitle); err != nil { + t.Fatalf("read working unrelated issue: %v", err) + } + if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", dirtyID).Scan(&headTitle); err != nil { + t.Fatalf("read unrelated issue AS OF HEAD: %v", err) + } + if workingTitle != "working-only title" || headTitle != "perm "+dirtyID { + t.Errorf("unrelated issue titles = working:%q HEAD:%q", workingTitle, headTitle) + } + // events is dolt_ignored since migration 0062 (bd-red8u): there is no HEAD + // state to compare against. Every caller of this helper asserts that HEAD + // did not move, which is the stronger form of "nothing was published"; the + // remaining events-specific claim is that the same-status update left the + // unrelated working-set audit edit alone. + var workingEvent int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?", + dirtyID, string(types.EventCreated), "working-only event", + ).Scan(&workingEvent); err != nil { + t.Fatalf("read working unrelated event: %v", err) + } + if workingEvent != 1 { + t.Errorf("unrelated working-set event edit count = %d, want 1", workingEvent) + } +} + +func newTransactionWispLifecycleStore(t *testing.T) (context.Context, *DoltStore) { + t.Helper() + store, cleanup := setupTestStore(t) + t.Cleanup(cleanup) + ctx, cancel := testContext(t) + t.Cleanup(cancel) + return ctx, store +} + +func seedTransactionWispBlocker(t *testing.T, ctx context.Context, store *DoltStore, dependerID, wispID string) { + t.Helper() + createPerm(t, ctx, store, dependerID) + createWisp(t, ctx, store, wispID) + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks, + }, "tester"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + if err := store.Commit(ctx, "test: seed wisp blocker"); err != nil { + t.Fatalf("Commit seed: %v", err) + } + var blocked bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", dependerID).Scan(&blocked); err != nil { + t.Fatalf("read seed durable depender: %v", err) + } + if !blocked { + t.Fatalf("seed durable depender %s is not blocked", dependerID) + } + var committed bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", dependerID).Scan(&committed); err != nil { + t.Fatalf("read committed seed durable depender: %v", err) + } + if !committed { + t.Fatalf("committed seed durable depender %s is not blocked", dependerID) + } +} + +func transactionWispLifecycleHead(t *testing.T, ctx context.Context, store *DoltStore) string { + t.Helper() + head, err := store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit: %v", err) + } + return head +} + +func assertTransactionWispLifecyclePostState(t *testing.T, ctx context.Context, store *DoltStore, dependerID, before string, wantBlocked bool) { + t.Helper() + after := transactionWispLifecycleHead(t, ctx, store) + if after == before { + t.Errorf("transactional wisp lifecycle did not publish durable dependent; HEAD remained %s", before) + } + + var working bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", dependerID).Scan(&working); err != nil { + t.Fatalf("read working durable depender: %v", err) + } + if working != wantBlocked { + t.Errorf("working durable depender is_blocked = %t, want %t", working, wantBlocked) + } + + var committed bool + if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", dependerID).Scan(&committed); err != nil { + t.Fatalf("read durable depender AS OF HEAD: %v", err) + } + if committed != wantBlocked { + t.Errorf("committed durable depender is_blocked = %t, want %t", committed, wantBlocked) + } +} + +func assertStandaloneWispLifecycleState(t *testing.T, ctx context.Context, store *DoltStore, wispID, before string, wantStatus types.Status) { + t.Helper() + if after := transactionWispLifecycleHead(t, ctx, store); after != before { + t.Fatalf("standalone wisp lifecycle changed HEAD from %s to %s", before, after) + } + issue, err := store.GetIssue(ctx, wispID) + if err != nil { + t.Fatalf("GetIssue(%s): %v", wispID, err) + } + if issue.Status != wantStatus { + t.Errorf("wisp status = %q, want %q", issue.Status, wantStatus) + } +} diff --git a/internal/storage/dolt/update_same_status_test.go b/internal/storage/dolt/update_same_status_test.go new file mode 100644 index 000000000..6f9fc3d26 --- /dev/null +++ b/internal/storage/dolt/update_same_status_test.go @@ -0,0 +1,149 @@ +package dolt + +import ( + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +func TestUpdateIssueSameStatusDoesNotCreateLifecycleMutation(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + const id = "same-status-no-lifecycle-mutation" + createPerm(t, ctx, store, id) + before, err := store.GetIssue(ctx, id) + if err != nil { + t.Fatal(err) + } + beforeEvents, err := store.GetEvents(ctx, id, 0) + if err != nil { + t.Fatal(err) + } + + if err := store.UpdateIssue(ctx, id, map[string]interface{}{"status": types.StatusOpen}, "tester"); err != nil { + t.Fatalf("same-status UpdateIssue: %v", err) + } + afterSameStatus, err := store.GetIssue(ctx, id) + if err != nil { + t.Fatal(err) + } + afterSameStatusEvents, err := store.GetEvents(ctx, id, 0) + if err != nil { + t.Fatal(err) + } + if afterSameStatus.RowVersion != before.RowVersion { + t.Errorf("same-status update changed RowVersion from %d to %d", before.RowVersion, afterSameStatus.RowVersion) + } + if len(afterSameStatusEvents) != len(beforeEvents) { + t.Errorf("same-status update recorded %d events, want %d", len(afterSameStatusEvents), len(beforeEvents)) + } + + if err := store.UpdateIssue(ctx, id, map[string]interface{}{"status": types.StatusOpen, "title": "renamed"}, "tester"); err != nil { + t.Fatalf("same-status scalar UpdateIssue: %v", err) + } + afterScalar, err := store.GetIssue(ctx, id) + if err != nil { + t.Fatal(err) + } + if afterScalar.Title != "renamed" { + t.Errorf("mixed scalar update title = %q, want renamed", afterScalar.Title) + } + events, err := store.GetEvents(ctx, id, 0) + if err != nil { + t.Fatal(err) + } + var updated, statusChanged int + for _, event := range events { + switch event.EventType { + case types.EventUpdated: + updated++ + case types.EventStatusChanged: + statusChanged++ + } + } + if len(events) != len(beforeEvents)+1 || updated != 1 || statusChanged != 0 { + t.Errorf("mixed scalar same-status events = updated:%d status_changed:%d total:%d", updated, statusChanged, len(events)) + } +} + +func TestDoltStoreSameStatusUpdatesDoNotPublishUnrelatedDurableChanges(t *testing.T) { + for _, test := range []struct { + name string + checked bool + }{ + {name: "UpdateIssue"}, + {name: "UpdateIssueChecked", checked: true}, + } { + t.Run(test.name, func(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + targetID := "store-same-status-target-" + test.name + dirtyID := "store-same-status-dirty-" + test.name + createPerm(t, ctx, store, targetID) + createPerm(t, ctx, store, dirtyID) + targetBefore, err := store.GetIssue(ctx, targetID) + if err != nil { + t.Fatalf("GetIssue target before: %v", err) + } + before := transactionWispLifecycleHead(t, ctx, store) + + if _, err := store.db.ExecContext(ctx, "UPDATE issues SET title = ? WHERE id = ?", "working-only title", dirtyID); err != nil { + t.Fatalf("stage unrelated issue edit: %v", err) + } + if _, err := store.db.ExecContext(ctx, + "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?", + "working-only event", dirtyID, string(types.EventCreated), + ); err != nil { + t.Fatalf("stage unrelated event edit: %v", err) + } + + updates := map[string]interface{}{"status": types.StatusOpen} + if test.checked { + version := targetBefore.RowVersion + err = store.UpdateIssueChecked(ctx, targetID, updates, "tester", storage.UpdateIssueOptions{ExpectedVersion: &version}) + } else { + err = store.UpdateIssue(ctx, targetID, updates, "tester") + } + if err != nil { + t.Fatalf("%s: %v", test.name, err) + } + if after := transactionWispLifecycleHead(t, ctx, store); after != before { + t.Errorf("%s same-status update changed HEAD from %s to %s", test.name, before, after) + } + targetAfter, err := store.GetIssue(ctx, targetID) + if err != nil { + t.Fatalf("GetIssue target after: %v", err) + } + if targetAfter.RowVersion != targetBefore.RowVersion { + t.Errorf("%s same-status update changed RowVersion from %d to %d", + test.name, targetBefore.RowVersion, targetAfter.RowVersion) + } + assertDirectSameStatusUnrelatedChangesWorkingOnly(t, ctx, store, dirtyID) + }) + } +} + +func TestUpdateIssuePreservesCallerUpdatesAfterSameStatusNormalization(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + + const id = "same-status-preserves-caller-map" + createPerm(t, ctx, store, id) + updates := map[string]interface{}{"status": types.StatusOpen} + + if err := store.UpdateIssue(ctx, id, updates, "tester"); err != nil { + t.Fatalf("UpdateIssue: %v", err) + } + if got, ok := updates["status"]; !ok || got != types.StatusOpen { + t.Fatalf("caller updates after same-status update = %#v, want status=open", updates) + } +} diff --git a/internal/storage/dolt/wisps.go b/internal/storage/dolt/wisps.go index 433d37718..15efef603 100644 --- a/internal/storage/dolt/wisps.go +++ b/internal/storage/dolt/wisps.go @@ -279,7 +279,7 @@ func (s *DoltStore) closeWispChecked(ctx context.Context, id string, actor strin if err := wrapTransactionError("commit close wisp", tx.Commit()); err != nil { return storage.CloseIssueResult{}, err } - return storage.CloseIssueResult{Unchanged: res.AlreadyClosed}, nil + return storage.CloseIssueResult{Unchanged: res.AlreadyClosed, OpenChildren: res.OpenChildren}, nil } // deleteWisp permanently removes a wisp and its related data. diff --git a/internal/storage/domain/comment.go b/internal/storage/domain/comment.go index dda2a861a..1fce57579 100644 --- a/internal/storage/domain/comment.go +++ b/internal/storage/domain/comment.go @@ -17,6 +17,7 @@ type CommentSQLRepository interface { ListByIssueIDs(ctx context.Context, issueIDs []string, opts CommentOpts) (map[string][]*types.Comment, error) IterByIssueID(ctx context.Context, issueID string, opts CommentOpts) (storage.Iter[types.Comment], error) Insert(ctx context.Context, issueID, author, text string, opts CommentOpts) (*types.Comment, error) + InsertRecord(ctx context.Context, comment *types.Comment, opts CommentOpts) (*types.Comment, error) } type CommentUseCase interface { diff --git a/internal/storage/domain/config.go b/internal/storage/domain/config.go index a27e06b0f..347d83ecc 100644 --- a/internal/storage/domain/config.go +++ b/internal/storage/domain/config.go @@ -63,6 +63,10 @@ type CreateContext struct { AllowedPrefixes string CustomTypes []string CustomStatuses []types.CustomStatus + // InfraTypes is the resolved infrastructure-type set. A create whose type + // is in this set is routed to the wisp tables, the same routing the + // embedded and direct stores apply from IsInfraTypeCtx. + InfraTypes map[string]bool } type Issue struct{} @@ -297,10 +301,15 @@ func (u *configUseCaseImpl) LoadCreateContext(ctx context.Context) (CreateContex if err != nil { return CreateContext{}, fmt.Errorf("LoadCreateContext: read custom statuses: %w", err) } + infraTypes, err := u.GetInfraTypes(ctx) + if err != nil { + return CreateContext{}, fmt.Errorf("LoadCreateContext: read infra types: %w", err) + } return CreateContext{ IssuePrefix: prefix, AllowedPrefixes: allowed, CustomTypes: customTypes, CustomStatuses: customStatuses, + InfraTypes: infraTypes, }, nil } diff --git a/internal/storage/domain/db/close_checked_usecase_test.go b/internal/storage/domain/db/close_checked_usecase_test.go index 87974d065..f223d851a 100644 --- a/internal/storage/domain/db/close_checked_usecase_test.go +++ b/internal/storage/domain/db/close_checked_usecase_test.go @@ -17,6 +17,56 @@ func (s *testSuite) TestIssueUseCase_CloseIssueChecked() { s.Run("UnblockedClosesAndReturnsIssue", s.uccCloseCheckedUnblockedCloses) s.Run("WispDirectBlockerRefuses", s.uccCloseWispCheckedDirectBlockerRefuses) s.Run("WispForceClosesDespiteDirectBlocker", s.uccCloseWispCheckedForceCloses) + s.Run("OpenChildrenRefuseAndForceReportsCount", s.uccCloseCheckedOpenChildren) +} + +func (s *testSuite) uccCloseCheckedOpenChildren() { + parent := "bd-ucc-clc-parent" + permanentChild := "bd-ucc-clc-child" + wispChild := "bd-ucc-clc-wisp-child" + s.seedIssueRow(parent) + s.seedIssueRow(permanentChild) + s.seedWispRow(wispChild) + for _, child := range []struct { + id string + wisp bool + }{{permanentChild, false}, {wispChild, true}} { + s.Require().NoError(s.depRepo().Insert(s.Ctx(), + newDep(child.id, parent, types.DepParentChild), "tester", domain.DepInsertOpts{UseWispsTable: child.wisp})) + } + + res, err := s.issueUseCase().CloseIssueChecked(s.Ctx(), parent, + domain.CloseIssueParams{Reason: "done"}, "tester", false) + s.Require().Error(err) + s.True(errors.Is(err, storage.ErrCloseOpenChildren)) + var childErr *storage.CloseOpenChildrenError + s.True(errors.As(err, &childErr)) + s.Equal(parent, childErr.IssueID) + s.Equal(2, childErr.OpenChildren) + s.False(res.Closed) + s.Equal(0, res.OpenChildren) + + res, err = s.issueUseCase().CloseIssueChecked(s.Ctx(), parent, + domain.CloseIssueParams{Reason: "override"}, "tester", true) + s.Require().NoError(err) + s.True(res.Closed) + s.Equal(2, res.OpenChildren) + + wispParent := "bd-ucc-clc-wisp-parent" + childOfWispParent := "bd-ucc-clc-wisp-parent-child" + s.seedWispRow(wispParent) + s.seedIssueRow(childOfWispParent) + s.Require().NoError(s.depRepo().Insert(s.Ctx(), + newDep(childOfWispParent, wispParent, types.DepParentChild), "tester", domain.DepInsertOpts{})) + res, err = s.issueUseCase().CloseWispChecked(s.Ctx(), wispParent, + domain.CloseIssueParams{Reason: "done"}, "tester", false) + s.Require().Error(err) + s.True(errors.Is(err, storage.ErrCloseOpenChildren)) + res, err = s.issueUseCase().CloseWispChecked(s.Ctx(), wispParent, + domain.CloseIssueParams{Reason: "override"}, "tester", true) + s.Require().NoError(err) + s.True(res.Closed) + s.Equal(1, res.OpenChildren) } func (s *testSuite) uccCloseCheckedDirectBlockerRefuses() { diff --git a/internal/storage/domain/db/comment.go b/internal/storage/domain/db/comment.go index 1b95d1540..27b7a3ab4 100644 --- a/internal/storage/domain/db/comment.go +++ b/internal/storage/domain/db/comment.go @@ -114,43 +114,64 @@ func (r *commentSQLRepositoryImpl) IterByIssueID(ctx context.Context, issueID st } func (r *commentSQLRepositoryImpl) Insert(ctx context.Context, issueID, author, text string, opts domain.CommentOpts) (*types.Comment, error) { - if issueID == "" { - return nil, fmt.Errorf("db: CommentSQLRepository.Insert: issueID must not be empty") + // Live add: advance past the issue's newest comment so a burst inside one + // second still reads back in write order (issueops.NextLiveCommentTime). + // InsertRecord honors a supplied CreatedAt verbatim, which is what keeps + // imported comments on their original timestamps. + stamp, err := issueops.NextLiveCommentTime(ctx, r.runner, pickCommentTable(opts.UseWispsTable), issueID, time.Now()) + if err != nil { + return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err) + } + return r.InsertRecord(ctx, &types.Comment{IssueID: issueID, Author: author, Text: text, CreatedAt: stamp}, opts) +} + +func (r *commentSQLRepositoryImpl) InsertRecord(ctx context.Context, comment *types.Comment, opts domain.CommentOpts) (*types.Comment, error) { + if comment == nil { + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: comment must not be nil") + } + copy := *comment + if copy.IssueID == "" { + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: issueID must not be empty") } issueTable := pickIssueTable(opts.UseWispsTable) var exists bool //nolint:gosec // G201: issueTable is one of two hardcoded constants if err := r.runner.QueryRowContext(ctx, - fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM %s WHERE id = ?)", issueTable), issueID).Scan(&exists); err != nil { - return nil, fmt.Errorf("db: CommentSQLRepository.Insert: check issue existence: %w", err) + fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM %s WHERE id = ?)", issueTable), copy.IssueID).Scan(&exists); err != nil { + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: check issue existence: %w", err) } if !exists { - return nil, fmt.Errorf("db: CommentSQLRepository.Insert: issue %s not found", issueID) + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: issue %s not found", copy.IssueID) } - commentTable := pickCommentTable(opts.UseWispsTable) - // Live add: advance past the issue's newest comment so a burst inside one - // second still reads back in write order (issueops.NextLiveCommentTime). - stamp, err := issueops.NextLiveCommentTime(ctx, r.runner, commentTable, issueID, time.Now()) - if err != nil { - return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err) + if copy.CreatedAt.IsZero() { + copy.CreatedAt = time.Now().UTC() + } else { + copy.CreatedAt = copy.CreatedAt.UTC() } - createdAtText := issueops.FormatAuxTime(stamp) - id, _, err := issueops.InsertDerivedComment(ctx, r.runner, commentTable, issueID, author, text, createdAtText) - if err != nil { - return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err) + createdAtText := issueops.FormatAuxTime(copy.CreatedAt) + commentTable := pickCommentTable(opts.UseWispsTable) + if copy.ID == "" { + id, _, err := issueops.InsertDerivedComment(ctx, r.runner, commentTable, copy.IssueID, copy.Author, copy.Text, createdAtText) + if err != nil { + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: %w", err) + } + copy.ID = id + } else { + //nolint:gosec // G201: commentTable is one of two hardcoded constants + if _, err := r.runner.ExecContext(ctx, fmt.Sprintf(` + INSERT INTO %s (id, issue_id, author, text, created_at) + VALUES (?, ?, ?, ?, ?) + `, commentTable), copy.ID, copy.IssueID, copy.Author, copy.Text, createdAtText); err != nil { + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: %w", err) + } } createdAt, err := issueops.ParseAuxTime(createdAtText) if err != nil { - return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err) + return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: %w", err) } + copy.CreatedAt = createdAt - return &types.Comment{ - ID: id, - IssueID: issueID, - Author: author, - Text: text, - CreatedAt: createdAt, - }, nil + return ©, nil } diff --git a/internal/storage/domain/db/comment_test.go b/internal/storage/domain/db/comment_test.go index fdec9ad45..44f2ebb87 100644 --- a/internal/storage/domain/db/comment_test.go +++ b/internal/storage/domain/db/comment_test.go @@ -6,6 +6,7 @@ import ( "github.com/google/uuid" "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" ) func (s *testSuite) TestCommentSQLRepository() { @@ -33,9 +34,32 @@ func (s *testSuite) TestCommentSQLRepository() { s.Run("PopulatesReturnedComment", s.commentInsertPopulatesReturn) s.Run("RoundTripsThroughList", s.commentInsertRoundTrip) s.Run("RoutesToWispComments", s.commentInsertWispRouting) + s.Run("InsertRecordPreservesImportedValues", s.commentInsertRecordPreservesImportedValues) }) } +func (s *testSuite) commentInsertRecordPreservesImportedValues() { + s.seedIssueRow("bd-cmt-ins-record") + createdAt := time.Date(2025, time.January, 2, 3, 4, 5, 987_654_321, time.UTC) + + inserted, err := s.commentRepo().InsertRecord(s.Ctx(), &types.Comment{ + ID: "imported-comment-id", + IssueID: "bd-cmt-ins-record", + Author: "importer", + Text: "preserved", + CreatedAt: createdAt, + }, domain.CommentOpts{}) + s.Require().NoError(err) + s.Equal("imported-comment-id", inserted.ID) + s.Equal(createdAt.Truncate(time.Second), inserted.CreatedAt) + + comments, err := s.commentRepo().ListByIssueIDs(s.Ctx(), []string{"bd-cmt-ins-record"}, domain.CommentOpts{}) + s.Require().NoError(err) + s.Require().Len(comments["bd-cmt-ins-record"], 1) + s.Equal("imported-comment-id", comments["bd-cmt-ins-record"][0].ID) + s.Equal(createdAt.Truncate(time.Second), comments["bd-cmt-ins-record"][0].CreatedAt) +} + func (s *testSuite) commentRepo() domain.CommentSQLRepository { return NewCommentSQLRepository(s.Runner()) } diff --git a/internal/storage/domain/db/dependency.go b/internal/storage/domain/db/dependency.go index 63d3db778..13eb03cac 100644 --- a/internal/storage/domain/db/dependency.go +++ b/internal/storage/domain/db/dependency.go @@ -145,6 +145,11 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep ); err != nil { return fmt.Errorf("db: DependencySQLRepository.Insert: %w", err) } + if dep.Type == types.DepParentChild { + if err := issueops.TouchDependencyCoordinationTableInTx(ctx, r.runner, dep.DependsOnID, table); err != nil { + return fmt.Errorf("db: DependencySQLRepository.Insert: %w", err) + } + } // Record the dependency_added event on the source's event table, matching the // embedded/issueops AddDependencyInTx path so the bd CLI and library callers diff --git a/internal/storage/domain/db/dependency_test.go b/internal/storage/domain/db/dependency_test.go index bd9b6809c..c659602ea 100644 --- a/internal/storage/domain/db/dependency_test.go +++ b/internal/storage/domain/db/dependency_test.go @@ -13,6 +13,7 @@ func (s *testSuite) TestDependencySQLRepository() { s.Run("RejectsEmptyIDs", s.depInsertEmptyIDs) s.Run("SameTypeIsIdempotentMetadataRefresh", s.depInsertIdempotentSameType) s.Run("UsesDeterministicID", s.depInsertUsesDeterministicID) + s.Run("ParentChildTouchesCoordinationOnlyForNewEdge", s.depInsertParentChildTouchesCoordinationOnlyForNewEdge) s.Run("DifferentTypeIsRejected", s.depInsertConflictingType) s.Run("MissingTargetIssueFailsFK", s.depInsertFKViolation) s.Run("ThreadIDPersists", s.depInsertThreadID) @@ -94,6 +95,39 @@ func (s *testSuite) depInsertUsesDeterministicID() { s.Equal(depid.New("bd-dep-det-a", "bd-dep-det-b"), gotID) } +func (s *testSuite) depInsertParentChildTouchesCoordinationOnlyForNewEdge() { + const keyPattern = "dependency-coordination/v1/dependencies/%" + parent, child, blocker, blocked := "bd-dep-coord-parent", "bd-dep-coord-child", "bd-dep-coord-blocker", "bd-dep-coord-blocked" + _, err := s.Runner().ExecContext(s.Ctx(), "DELETE FROM local_metadata WHERE `key` LIKE ?", keyPattern) + s.Require().NoError(err) + for _, id := range []string{parent, child, blocker, blocked} { + s.seedIssueRow(id) + } + s.Require().NoError(s.depRepo().Insert(s.Ctx(), newDep(child, parent, types.DepParentChild), "tester", domain.DepInsertOpts{})) + + var value string + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT value FROM local_metadata WHERE `key` LIKE ?", keyPattern).Scan(&value)) + s.NotEmpty(value, "new parent-child edge must touch its coordination row") + _, err = s.Runner().ExecContext(s.Ctx(), + "UPDATE local_metadata SET value = 'sentinel' WHERE `key` LIKE ?", keyPattern) + s.Require().NoError(err) + + // Same-type re-add refreshes metadata only, so it must not rewrite the + // coordination token. + s.Require().NoError(s.depRepo().Insert(s.Ctx(), newDep(child, parent, types.DepParentChild), "tester", domain.DepInsertOpts{})) + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT value FROM local_metadata WHERE `key` LIKE ?", keyPattern).Scan(&value)) + s.Equal("sentinel", value) + + // A non-parent-child edge must not create a second coordination row. + s.Require().NoError(s.depRepo().Insert(s.Ctx(), newDep(blocker, blocked, types.DepBlocks), "tester", domain.DepInsertOpts{})) + var count int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM local_metadata WHERE `key` LIKE ?", keyPattern).Scan(&count)) + s.Equal(1, count) +} + func (s *testSuite) depInsertRoundTrip() { s.seedIssueRow("bd-dep-a") s.seedIssueRow("bd-dep-b") diff --git a/internal/storage/domain/db/is_blocked_test.go b/internal/storage/domain/db/is_blocked_test.go index e79e9c583..61ba27f02 100644 --- a/internal/storage/domain/db/is_blocked_test.go +++ b/internal/storage/domain/db/is_blocked_test.go @@ -62,8 +62,8 @@ func (s *testSuite) ibUpdateCloseUnblocks() { s.Require().True(s.isBlocked("bd-ib-up-src")) issueRepo := NewIssueSQLRepository(s.Runner()) - s.Require().NoError(issueRepo.Update(s.Ctx(), "bd-ib-up-tgt", - map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + _, err := issueRepo.Close(s.Ctx(), "bd-ib-up-tgt", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) s.False(s.isBlocked("bd-ib-up-src"), "closing the blocker must unblock its dependent") } @@ -75,12 +75,12 @@ func (s *testSuite) ibUpdateReopenReblocks() { newDep("bd-ib-re-src", "bd-ib-re-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) issueRepo := NewIssueSQLRepository(s.Runner()) - s.Require().NoError(issueRepo.Update(s.Ctx(), "bd-ib-re-tgt", - map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + _, err := issueRepo.Close(s.Ctx(), "bd-ib-re-tgt", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) s.Require().False(s.isBlocked("bd-ib-re-src")) - s.Require().NoError(issueRepo.Update(s.Ctx(), "bd-ib-re-tgt", - map[string]any{"status": string(types.StatusOpen)}, "tester", domain.IssueTableOpts{})) + _, err = issueRepo.Reopen(s.Ctx(), "bd-ib-re-tgt", domain.ReopenRowParams{}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) s.True(s.isBlocked("bd-ib-re-src"), "reopening the blocker must re-block its dependent") } diff --git a/internal/storage/domain/db/issue.go b/internal/storage/domain/db/issue.go index 38f6c261c..ff21cbaab 100644 --- a/internal/storage/domain/db/issue.go +++ b/internal/storage/domain/db/issue.go @@ -37,7 +37,7 @@ var _ domain.IssueSQLRepository = (*issueSQLRepositoryImpl)(nil) const issueSelectColumns = sqlbuild.IssueSelectColumns var allowedUpdateFields = map[string]struct{}{ - "status": {}, "priority": {}, "title": {}, "assignee": {}, + "status": {}, "priority": {}, "title": {}, "assignee": {}, "owner": {}, "description": {}, "design": {}, "acceptance_criteria": {}, "notes": {}, "issue_type": {}, "estimated_minutes": {}, "external_ref": {}, "spec_id": {}, "started_at": {}, "closed_at": {}, "close_reason": {}, "closed_by_session": {}, @@ -66,6 +66,19 @@ func (r *issueSQLRepositoryImpl) Insert(ctx context.Context, issue *types.Issue, } table := pickIssueTable(opts.UseWispsTable) + if opts.CreateOnly { + if err := issueops.EnsureIssueIDAvailableInTx(ctx, r.runner, issue.ID); err != nil { + return err + } + if err := issueops.InsertIssueStrictInTx(ctx, r.runner, table, issue); err != nil { + return err + } + return r.events.Record(ctx, domain.Event{ + IssueID: issue.ID, + Type: types.EventCreated, + Actor: actor, + }, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}) + } if err := insertIssueRow(ctx, r.runner, table, issue); err != nil { return err } @@ -85,6 +98,18 @@ func (r *issueSQLRepositoryImpl) InsertBatch(ctx context.Context, issues []*type return nil } +func (r *issueSQLRepositoryImpl) MovePersistence(ctx context.Context, id string, mode types.PersistenceMode) (bool, error) { + issue, err := issueops.GetIssueInTx(ctx, r.runner, id) + if err != nil { + return false, fmt.Errorf("db: MovePersistence %s: get issue: %w", id, err) + } + result, err := issueops.MoveIssuePersistenceInTx(ctx, r.runner, issue, mode) + if err != nil { + return false, fmt.Errorf("db: MovePersistence %s: %w", id, err) + } + return result.Changed, nil +} + func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates map[string]any, actor string, opts domain.IssueTableOpts) error { if id == "" { return errors.New("db: Update: id must not be empty") @@ -92,6 +117,7 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates if len(updates) == 0 { return nil } + updates = cloneUpdateFields(updates) // Bound the VARCHAR(255) assignment columns before touching SQL, mirroring // issueops.updateIssueInTx: an over-length assignee/owner aborts with a typed @@ -108,27 +134,17 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates table := pickIssueTable(opts.UseWispsTable) - _, statusChanging := updates["status"] mergeOps := issueops.HasMergeOps(updates) - // When the status changes we need the prior row to reproduce the embedded - // lifecycle side effects (issueops.updateIssueInTx): closed_at is set on - // close and cleared on reopen, started_at is set on the in_progress - // transition, the audit event type is derived from the transition, and - // is_blocked is recomputed for neighbors. Read the full old issue once so - // all four use the same snapshot; the ErrNoRows contract is preserved. - // Merge operations (metadata edits, note appends) need the same read: they - // are resolved against the row as seen by THIS unit-of-work transaction. - var oldIssue *types.Issue - if statusChanging || mergeOps { - var err error - oldIssue, err = r.Get(ctx, id, opts) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows) - } - return fmt.Errorf("db: Update %s: read old issue: %w", id, err) + // Read the prior row once. Status and merge updates need it for their + // transaction-local resolution, and every update uses it to suppress true + // no-ops before changing row_lock or recording an event. + oldIssue, err := r.Get(ctx, id, opts) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows) } + return fmt.Errorf("db: Update %s: read old issue: %w", id, err) } // Resolve read-merge-write operation keys (issueops.OpMergeMetadata, @@ -149,6 +165,18 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates updates = resolved } + filteredUpdates, err := issueops.DiscardNoopIssueUpdates(oldIssue, updates) + if err != nil { + return fmt.Errorf("db: Update %s: compare updates: %w", id, err) + } + updates = filteredUpdates + if len(updates) == 0 { + return nil + } + // A status that matched the row was already dropped as a no-op, so the + // lifecycle side effects below only fire on a real transition. + _, statusChanging := updates["status"] + setClauses := make([]string, 0, len(updates)+3) args := make([]any, 0, len(updates)+4) for key, value := range updates { @@ -167,11 +195,12 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates // Lifecycle parity with issueops.updateIssueInTx: auto-manage closed_at and // started_at from the status transition unless the caller set them - // explicitly. Both helpers no-op when the status is unchanged. + // explicitly. if statusChanging { setClauses, args = issueops.ManageClosedAt(oldIssue, updates, setClauses, args) setClauses, args = issueops.ManageStartedAt(oldIssue, updates, setClauses, args) } + clearLease := issueops.ManageLeaseOnUpdate(oldIssue, updates) // Rewrite row_lock on every generic update, mirroring the classic // issueops.updateIssueInTx invariant (update.go): a concurrent @@ -198,6 +227,11 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates if rows == 0 { return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows) } + if clearLease && !opts.UseWispsTable { + if err := issueops.DeleteLeaseInTx(ctx, r.runner, id); err != nil { + return fmt.Errorf("db: Update %s: clear lease: %w", id, err) + } + } // Event-type parity: embedded records EventClosed / EventReopened / // EventStatusChanged for status transitions (issueops.DetermineEventType), @@ -239,6 +273,14 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates return nil } +func cloneUpdateFields(updates map[string]any) map[string]any { + cloned := make(map[string]any, len(updates)) + for key, value := range updates { + cloned[key] = value + } + return cloned +} + func coerceStatus(v any) types.Status { switch s := v.(type) { case string: @@ -896,13 +938,26 @@ func (r *issueSQLRepositoryImpl) Close(ctx context.Context, id string, params do }, nil } +func (r *issueSQLRepositoryImpl) CloseChecked(ctx context.Context, id string, params domain.CloseRowParams, actor string, force bool) (domain.CloseRowResult, error) { + res, err := issueops.CloseIssueCheckedInTx(ctx, r.runner, id, params.Reason, actor, params.Session, force, nil) + if err != nil { + return domain.CloseRowResult{}, fmt.Errorf("db: IssueSQLRepository.CloseChecked %s: %w", id, err) + } + return domain.CloseRowResult{ + Updated: !res.AlreadyClosed, + AlreadyClosed: res.AlreadyClosed, + IsWisp: res.IsWisp, + OpenChildren: res.OpenChildren, + }, nil +} + func (r *issueSQLRepositoryImpl) Reopen(ctx context.Context, id string, params domain.ReopenRowParams, actor string, opts domain.IssueTableOpts) (domain.ReopenRowResult, error) { res, err := issueops.ReopenIssueInTx(ctx, r.runner, id, params.Reason, actor) if err != nil { return domain.ReopenRowResult{}, fmt.Errorf("db: IssueSQLRepository.Reopen %s: %w", id, err) } return domain.ReopenRowResult{ - Updated: !res.AlreadyOpen, + Updated: res.Changed, AlreadyOpen: res.AlreadyOpen, IsWisp: res.IsWisp, }, nil diff --git a/internal/storage/domain/db/issue_cross_tier_test.go b/internal/storage/domain/db/issue_cross_tier_test.go new file mode 100644 index 000000000..7acb27c0e --- /dev/null +++ b/internal/storage/domain/db/issue_cross_tier_test.go @@ -0,0 +1,97 @@ +package db + +import ( + "strings" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func (s *testSuite) TestParentTierControlsInheritedLabels() { + s.Run("durable parent to wisp child", func() { + s.resetMintConfig("tier-durable-parent", "") + uc := s.issueUseCase() + parent, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "durable parent", IssueType: types.TypeEpic, Priority: 2}, + Labels: []string{"durable-parent-label"}, + }, "tester") + s.Require().NoError(err) + + child, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "wisp child", IssueType: types.TypeTask, Priority: 2, Ephemeral: true}, + ParentID: parent.Issue.ID, + InheritLabelsFromParent: true, + }, "tester") + s.Require().NoError(err) + s.True(strings.HasPrefix(child.Issue.ID, parent.Issue.ID+"."), "child ID %q must use canonical parent child minting", child.Issue.ID) + s.Equal([]string{"durable-parent-label"}, child.InheritedLabels) + labels, err := s.labelUseCase().GetWispLabels(s.Ctx(), child.Issue.ID) + s.Require().NoError(err) + s.Equal([]string{"durable-parent-label"}, labels) + }) + + s.Run("wisp parent to durable child", func() { + s.resetMintConfig("tier-wisp-parent", "") + uc := s.issueUseCase() + parent, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "wisp parent", IssueType: types.TypeEpic, Priority: 2, Ephemeral: true}, + Labels: []string{"wisp-parent-label"}, + }, "tester") + s.Require().NoError(err) + + child, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "durable child", IssueType: types.TypeTask, Priority: 2}, + ParentID: parent.Issue.ID, + InheritLabelsFromParent: true, + }, "tester") + s.Require().NoError(err) + s.True(strings.HasPrefix(child.Issue.ID, parent.Issue.ID+"."), "child ID %q must use canonical parent child minting", child.Issue.ID) + s.Equal([]string{"wisp-parent-label"}, child.InheritedLabels) + labels, err := s.labelUseCase().GetLabels(s.Ctx(), child.Issue.ID) + s.Require().NoError(err) + s.Equal([]string{"wisp-parent-label"}, labels) + }) +} + +func (s *testSuite) TestReverseCreateDependencyUsesActualSourceTier() { + s.resetMintConfig("tier-reverse-dependency", "") + uc := s.issueUseCase() + + wispSource, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "wisp source", IssueType: types.TypeTask, Priority: 2, Ephemeral: true}, + }, "tester") + s.Require().NoError(err) + durableTarget, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "durable target", IssueType: types.TypeTask, Priority: 2}, + Dependencies: []domain.DependencySpec{{ + Type: types.DepRelated, TargetID: wispSource.Issue.ID, SwapDirection: true, + Metadata: `{"from":"wisp"}`, ThreadID: "wisp-thread", + }}, + }, "tester") + s.Require().NoError(err) + wispRecords, err := s.depUseCase().GetWispDependencyRecords(s.Ctx(), []string{wispSource.Issue.ID}) + s.Require().NoError(err) + s.Require().Len(wispRecords[wispSource.Issue.ID], 1) + s.Equal(durableTarget.Issue.ID, wispRecords[wispSource.Issue.ID][0].DependsOnID) + s.Equal(`{"from":"wisp"}`, wispRecords[wispSource.Issue.ID][0].Metadata) + s.Equal("wisp-thread", wispRecords[wispSource.Issue.ID][0].ThreadID) + + durableSource, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "durable source", IssueType: types.TypeTask, Priority: 2}, + }, "tester") + s.Require().NoError(err) + wispTarget, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "wisp target", IssueType: types.TypeTask, Priority: 2, Ephemeral: true}, + Dependencies: []domain.DependencySpec{{ + Type: types.DepRelated, TargetID: durableSource.Issue.ID, SwapDirection: true, + Metadata: `{"from":"durable"}`, ThreadID: "durable-thread", + }}, + }, "tester") + s.Require().NoError(err) + durableRecords, err := s.depUseCase().GetIssueDependencyRecords(s.Ctx(), []string{durableSource.Issue.ID}) + s.Require().NoError(err) + s.Require().Len(durableRecords[durableSource.Issue.ID], 1) + s.Equal(wispTarget.Issue.ID, durableRecords[durableSource.Issue.ID][0].DependsOnID) + s.Equal(`{"from":"durable"}`, durableRecords[durableSource.Issue.ID][0].Metadata) + s.Equal("durable-thread", durableRecords[durableSource.Issue.ID][0].ThreadID) +} diff --git a/internal/storage/domain/db/issue_scan_parity_test.go b/internal/storage/domain/db/issue_scan_parity_test.go index d5250f696..04699aa30 100644 --- a/internal/storage/domain/db/issue_scan_parity_test.go +++ b/internal/storage/domain/db/issue_scan_parity_test.go @@ -42,13 +42,13 @@ func TestScanIssue_StringTimestamps(t *testing.T) { for i := range cols { cols[i] = strings.TrimSpace(cols[i]) } - require.Len(t, cols, 51) + require.Len(t, cols, 52) row := []driver.Value{ "bd-test.1", nil, "title", "desc", "", "", "", // id..notes "open", 1, "task", nil, nil, // status..estimated_minutes "2026-06-12 10:00:00", nil, nil, "2026-06-12T10:00:01Z", nil, nil, nil, nil, // created_at..spec_id - 0, nil, nil, nil, nil, nil, // compaction_level..close_reason + 0, nil, nil, nil, nil, nil, nil, // compaction_level..closed_by_session nil, nil, nil, nil, nil, nil, // sender..is_template nil, nil, nil, nil, // await_type..waiters nil, // mol_type @@ -59,7 +59,7 @@ func TestScanIssue_StringTimestamps(t *testing.T) { nil, // storage_class nil, nil, nil, // lease_expires_at, heartbeat_at, granted_node } - require.Len(t, row, 51) + require.Len(t, row, 52) mock.ExpectQuery("SELECT").WillReturnRows(sqlmock.NewRows(cols).AddRow(row...)) diff --git a/internal/storage/domain/db/issue_test.go b/internal/storage/domain/db/issue_test.go index 10c229e15..a294e7a44 100644 --- a/internal/storage/domain/db/issue_test.go +++ b/internal/storage/domain/db/issue_test.go @@ -31,6 +31,8 @@ func (s *testSuite) TestIssueSQLRepository() { s.Run("NormalizesStatusType", s.issueUpdateStatusType) s.Run("NormalizesTimestampToUTC", s.issueUpdateNormalizesTimestamp) s.Run("MissingIDWithStatusChangeReturnsErrNoRows", s.issueUpdateMissingIDWithStatus) + s.Run("SameStatusInUnitOfWork", s.issueUpdateSameStatusInUnitOfWork) + s.Run("PreservesCallerMap", s.issueUpdatePreservesCallerMap) }) s.Run("RowVersion", func() { s.Run("NonZeroAfterCreate", s.issueRowVersionNonZeroOnCreate) @@ -696,8 +698,8 @@ func (s *testSuite) issueClaimConflict() { func (s *testSuite) issueClaimClosed() { r := s.issueRepo() s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-claim-closed", "x"), "tester", domain.InsertIssueOpts{})) - s.Require().NoError(r.Update(s.Ctx(), "bd-claim-closed", - map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + _, err := r.Close(s.Ctx(), "bd-claim-closed", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) res, err := r.Claim(s.Ctx(), "bd-claim-closed", "alice", domain.IssueTableOpts{}) s.Require().NoError(err) diff --git a/internal/storage/domain/db/issue_update_validation_test.go b/internal/storage/domain/db/issue_update_validation_test.go new file mode 100644 index 000000000..3bfa192d1 --- /dev/null +++ b/internal/storage/domain/db/issue_update_validation_test.go @@ -0,0 +1,236 @@ +package db + +import ( + "errors" + "strings" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func (s *testSuite) TestIssueUpdateRejectsInvalidCanonicalFields() { + created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: "bd-domain-invalid-update", + Title: "valid incumbent", + IssueType: types.TypeTask, + Priority: 2, + }, + }, "tester") + s.Require().NoError(err) + + incumbent, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(err) + + var eventCount int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&eventCount)) + + checks := []struct { + name string + updates map[string]any + }{ + {"empty title", map[string]any{"title": ""}}, + {"overlong title", map[string]any{"title": strings.Repeat("x", 501)}}, + {"negative priority", map[string]any{"priority": -1}}, + {"priority above maximum", map[string]any{"priority": 5}}, + {"negative estimated minutes", map[string]any{"estimated_minutes": -1}}, + } + for _, check := range checks { + s.Run(check.name, func() { + err := s.issueUseCase().UpdateIssue(s.Ctx(), created.Issue.ID, check.updates, "tester") + s.ErrorIs(err, storage.ErrValidation) + + stored, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(getErr) + s.Equal("valid incumbent", stored.Title) + s.Equal(2, stored.Priority) + s.Nil(stored.EstimatedMinutes) + s.Equal(incumbent.RowVersion, stored.RowVersion) + + var afterEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&afterEvents)) + s.True(errors.Is(err, storage.ErrValidation)) + s.Equal(eventCount, afterEvents) + }) + } +} + +func (s *testSuite) TestIssueUpdateRejectsUnsupportedCanonicalFieldTypes() { + checks := []struct { + name string + id string + updates map[string]any + }{ + {"non-string title", "bd-domain-title-type", map[string]any{"title": 7}}, + {"int64 priority", "bd-domain-priority-type", map[string]any{"priority": int64(-1)}}, + {"int64 estimated minutes", "bd-domain-estimate-type", map[string]any{"estimated_minutes": int64(-1)}}, + } + for _, check := range checks { + s.Run(check.name, func() { + created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: check.id, + Title: "valid incumbent", + IssueType: types.TypeTask, + Priority: 2, + }, + }, "tester") + s.Require().NoError(err) + + before, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(err) + var beforeEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&beforeEvents)) + + err = s.issueUseCase().UpdateIssue(s.Ctx(), created.Issue.ID, check.updates, "tester") + s.ErrorIs(err, storage.ErrValidation) + + after, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(getErr) + s.Equal(before.Title, after.Title) + s.Equal(before.Priority, after.Priority) + s.Equal(before.EstimatedMinutes, after.EstimatedMinutes) + s.Equal(before.Status, after.Status) + s.Equal(before.Assignee, after.Assignee) + s.Equal(before.RowVersion, after.RowVersion) + var afterEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&afterEvents)) + s.Equal(beforeEvents, afterEvents) + }) + } +} + +func (s *testSuite) TestApplyUpdateValidatesFieldsBeforeClaim() { + created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: "bd-domain-validate-before-claim", + Title: "valid incumbent", + IssueType: types.TypeTask, + Priority: 2, + }, + }, "tester") + s.Require().NoError(err) + + before, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(err) + var beforeEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&beforeEvents)) + + _, err = s.issueUseCase().ApplyUpdate(s.Ctx(), created.Issue.ID, domain.UpdateSpec{ + Claim: true, + Fields: map[string]any{"title": ""}, + }, "claimant") + s.ErrorIs(err, storage.ErrValidation) + + after, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(getErr) + s.Equal(before.Title, after.Title) + s.Equal(before.Priority, after.Priority) + s.Equal(before.EstimatedMinutes, after.EstimatedMinutes) + s.Equal(before.Status, after.Status) + s.Equal(before.Assignee, after.Assignee) + s.Equal(before.RowVersion, after.RowVersion) + var afterEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&afterEvents)) + s.Equal(beforeEvents, afterEvents) +} + +func (s *testSuite) TestApplyUpdateValidatesIssueTypeBeforeClaim() { + created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: "bd-domain-validate-type-before-claim", + Title: "valid incumbent", + IssueType: types.TypeTask, + Priority: 2, + }, + }, "tester") + s.Require().NoError(err) + + before, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(err) + var beforeEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&beforeEvents)) + + _, err = s.issueUseCase().ApplyUpdate(s.Ctx(), created.Issue.ID, domain.UpdateSpec{ + Claim: true, + Fields: map[string]any{"issue_type": "bogus"}, + }, "claimant") + s.ErrorIs(err, storage.ErrValidation) + + after, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(getErr) + s.Equal(before.IssueType, after.IssueType) + s.Equal(before.Status, after.Status) + s.Equal(before.Assignee, after.Assignee) + s.Equal(before.RowVersion, after.RowVersion) + var afterEvents int + s.Require().NoError(s.Runner().QueryRowContext( + s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + created.Issue.ID, + ).Scan(&afterEvents)) + s.Equal(beforeEvents, afterEvents) +} + +func (s *testSuite) TestIssueUpdateAcceptsLegacyIssueTypeRepresentations() { + checks := []struct { + name string + id string + issueType any + want types.IssueType + }{ + {"string", "bd-domain-type-string", "bug", types.TypeBug}, + {"typed", "bd-domain-type-typed", types.TypeFeature, types.TypeFeature}, + } + for _, check := range checks { + s.Run(check.name, func() { + created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: check.id, + Title: "legacy type representation", + IssueType: types.TypeTask, + Priority: 2, + }, + }, "tester") + s.Require().NoError(err) + + err = s.issueUseCase().UpdateIssue(s.Ctx(), created.Issue.ID, map[string]any{ + "issue_type": check.issueType, + }, "tester") + s.Require().NoError(err) + + updated, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID) + s.Require().NoError(err) + s.Equal(check.want, updated.IssueType) + }) + } +} diff --git a/internal/storage/domain/db/issue_usecase_apply_update_test.go b/internal/storage/domain/db/issue_usecase_apply_update_test.go index 749f143cd..6aefab621 100644 --- a/internal/storage/domain/db/issue_usecase_apply_update_test.go +++ b/internal/storage/domain/db/issue_usecase_apply_update_test.go @@ -1,6 +1,8 @@ package db import ( + "database/sql" + "encoding/json" "errors" "github.com/steveyegge/beads/internal/storage" @@ -25,12 +27,15 @@ func (s *testSuite) TestIssueUseCase_ApplyUpdate() { s.Run("ClaimAndFieldsRunTogether", s.iucApplyUpdateClaimPlusFields) s.Run("AddRemoveLabelPaths", s.iucApplyUpdateAddRemoveLabels) s.Run("SetLabelsDiffsAgainstCurrent", s.iucApplyUpdateSetLabels) - s.Run("SetLabelsTakesPrecedenceOverAddRemove", s.iucApplyUpdateSetLabelsBeatsAddRemove) + s.Run("SetLabelsThenAddsThenRemoves", s.iucApplyUpdateSetLabelsThenAddRemove) + s.Run("SameScalarAndMetadataAreNoops", s.iucApplyUpdateSameScalarAndMetadataAreNoops) s.Run("ReparentReplacesParent", s.iucApplyUpdateReparent) s.Run("ReparentEmptyUnparents", s.iucApplyUpdateUnparent) s.Run("NoSpecBitsIsHarmless", s.iucApplyUpdateEmptySpec) s.Run("WispIDDispatchesToWispTables", s.iucApplyUpdateDispatchesToWisp) s.Run("ClaimAgainstWispDispatches", s.iucClaimDispatchesToWisp) + s.Run("ExpectedVersionRefusesStaleWrite", s.iucApplyUpdateExpectedVersion) + s.Run("PersistenceMovesNoOpsAndRollsBack", s.iucApplyUpdatePersistence) } func (s *testSuite) seedOpenIssue(id string) { @@ -91,11 +96,10 @@ func (s *testSuite) iucClaimOpenAssignedCopy() { func (s *testSuite) iucClaimClosed() { s.seedOpenIssue("bd-iuc-cl-closed") - r := s.issueRepo() - s.Require().NoError(r.Update(s.Ctx(), "bd-iuc-cl-closed", - map[string]any{"status": string(types.StatusClosed)}, "seeder", domain.IssueTableOpts{})) + _, err := s.issueUseCase().CloseIssue(s.Ctx(), "bd-iuc-cl-closed", domain.CloseIssueParams{}, "seeder") + s.Require().NoError(err) - _, err := s.issueUseCase().ClaimIssue(s.Ctx(), "bd-iuc-cl-closed", "alice") + _, err = s.issueUseCase().ClaimIssue(s.Ctx(), "bd-iuc-cl-closed", "alice") s.Require().Error(err) s.True(errors.Is(err, storage.ErrNotClaimable), "expected ErrNotClaimable, got %v", err) } @@ -175,21 +179,37 @@ func (s *testSuite) iucApplyUpdateSetLabels() { s.Equal([]string{"y", "z"}, labels) } -func (s *testSuite) iucApplyUpdateSetLabelsBeatsAddRemove() { - s.seedOpenIssue("bd-iuc-au-sl-prec") - uc := s.issueUseCase() - - desired := []string{"only-this"} - _, err := uc.ApplyUpdate(s.Ctx(), "bd-iuc-au-sl-prec", domain.UpdateSpec{ - AddLabels: []string{"add-me"}, - RemoveLabels: []string{"remove-me"}, +func (s *testSuite) iucApplyUpdateSetLabelsThenAddRemove() { + s.seedOpenIssue("bd-iuc-au-sl-order") + desired := []string{"replace", "remove"} + _, err := s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-sl-order", domain.UpdateSpec{ SetLabels: &desired, + AddLabels: []string{"add", "remove"}, + RemoveLabels: []string{"remove"}, }, "tester") s.Require().NoError(err) - - labels, err := s.labelUseCase().GetLabels(s.Ctx(), "bd-iuc-au-sl-prec") + labels, err := s.labelUseCase().GetLabels(s.Ctx(), "bd-iuc-au-sl-order") s.Require().NoError(err) - s.Equal([]string{"only-this"}, labels) + s.Equal([]string{"add", "replace"}, labels) +} + +func (s *testSuite) iucApplyUpdateSameScalarAndMetadataAreNoops() { + s.seedOpenIssue("bd-iuc-au-noop") + uc := s.issueUseCase() + before, err := uc.GetIssue(s.Ctx(), "bd-iuc-au-noop") + s.Require().NoError(err) + var beforeEvents int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), "SELECT COUNT(*) FROM events WHERE issue_id = ?", before.ID).Scan(&beforeEvents)) + + updated, err := uc.ApplyUpdate(s.Ctx(), before.ID, domain.UpdateSpec{Fields: map[string]any{ + "priority": before.Priority, + "metadata": json.RawMessage(`{}`), + }}, "tester") + s.Require().NoError(err) + s.Equal(before.RowVersion, updated.RowVersion) + var afterEvents int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), "SELECT COUNT(*) FROM events WHERE issue_id = ?", before.ID).Scan(&afterEvents)) + s.Equal(beforeEvents, afterEvents) } func (s *testSuite) iucApplyUpdateReparent() { @@ -232,6 +252,53 @@ func (s *testSuite) iucApplyUpdateEmptySpec() { s.Equal("bd-iuc-au-empty", updated.ID) } +func (s *testSuite) iucApplyUpdateExpectedVersion() { + s.seedOpenIssue("bd-iuc-au-version") + current, err := s.issueUseCase().GetIssue(s.Ctx(), "bd-iuc-au-version") + s.Require().NoError(err) + staleVersion := current.RowVersion + 1 + + _, err = s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-version", domain.UpdateSpec{ + ExpectedVersion: &staleVersion, + Fields: map[string]any{"title": "must not persist"}, + }, "tester") + s.Require().Error(err) + s.True(errors.Is(err, storage.ErrVersionMismatch), "want ErrVersionMismatch, got %v", err) + + stored, err := s.issueUseCase().GetIssue(s.Ctx(), "bd-iuc-au-version") + s.Require().NoError(err) + s.Equal("seed", stored.Title) +} + +func (s *testSuite) iucApplyUpdatePersistence() { + s.seedOpenIssue("bd-iuc-au-persist") + mode := types.PersistenceModeEphemeral + moved, err := s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-persist", domain.UpdateSpec{Persistence: &mode}, "tester") + s.Require().NoError(err) + s.True(moved.Ephemeral) + + _, err = s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist", domain.IssueTableOpts{}) + s.True(errors.Is(err, sql.ErrNoRows), "durable source must be removed, got %v", err) + stored, err := s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist", domain.IssueTableOpts{UseWispsTable: true}) + s.Require().NoError(err) + version := stored.RowVersion + + unchanged, err := s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-persist", domain.UpdateSpec{Persistence: &mode}, "tester") + s.Require().NoError(err) + s.Equal(version, unchanged.RowVersion, "same persistence mode must not rewrite the row") + + s.seedOpenIssue("bd-iuc-au-persist-rollback") + _, err = s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-persist-rollback", domain.UpdateSpec{ + Fields: map[string]any{"not_a_column": "bad"}, + Persistence: &mode, + }, "tester") + s.Require().Error(err) + _, err = s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist-rollback", domain.IssueTableOpts{}) + s.Require().NoError(err) + _, err = s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist-rollback", domain.IssueTableOpts{UseWispsTable: true}) + s.True(errors.Is(err, sql.ErrNoRows), "failed update must not move persistence plane, got %v", err) +} + func (s *testSuite) seedOpenWisp(id string) { r := s.issueRepo() w := newTestIssue(id, "seed wisp") diff --git a/internal/storage/domain/db/issue_usecase_test.go b/internal/storage/domain/db/issue_usecase_test.go index 212501862..a9d25a0dc 100644 --- a/internal/storage/domain/db/issue_usecase_test.go +++ b/internal/storage/domain/db/issue_usecase_test.go @@ -2,8 +2,11 @@ package db import ( "database/sql" + "errors" "strings" + "time" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" ) @@ -16,6 +19,9 @@ func (s *testSuite) TestIssueUseCase_MintTopLevelID() { s.Run("IDPrefixSubprefixHonored", s.useCaseMintRespectsIDPrefix) s.Run("WispUsesWispPrefix", s.useCaseMintWispPrefix) s.Run("MissingConfigPrefixErrors", s.useCaseMintMissingPrefix) + s.Run("ExplicitIDRequiresConfiguredPrefixUnlessForced", s.useCaseExplicitIDPrefixGuard) + s.Run("CreateOnlyRefusesOccupiedID", s.useCaseCreateOnlyRefusesOccupiedID) + s.Run("CreateAttachesNormalizedComments", s.useCaseCreateAttachesNormalizedComments) } func (s *testSuite) issueUseCase() domain.IssueUseCase { @@ -152,6 +158,91 @@ func (s *testSuite) useCaseMintMissingPrefix() { s.Contains(err.Error(), "issue_prefix") } +func (s *testSuite) useCaseExplicitIDPrefixGuard() { + s.resetMintConfig("prefixguard", "") + uc := s.issueUseCase() + + upsert, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "foreign upsert", IssueType: types.TypeTask, Priority: 2}, + ExplicitID: "foreign-upsert-1", + }, "tester") + s.Require().NoError(err) + s.Equal("foreign-upsert-1", upsert.Issue.ID) + + _, err = uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "foreign", IssueType: types.TypeTask, Priority: 2}, + ExplicitID: "foreign-1", + CreateOnly: true, + }, "tester") + s.Require().Error(err) + s.True(errors.Is(err, storage.ErrPrefixMismatch), "want ErrPrefixMismatch, got %v", err) + s.Require().NoError(NewConfigSQLRepository(s.Runner()).SetConfig(s.Ctx(), "allowed_prefixes", "allowed")) + + allowed, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "allowed", IssueType: types.TypeTask, Priority: 2}, + ExplicitID: "allowed-1", + CreateOnly: true, + }, "tester") + s.Require().NoError(err) + s.Equal("allowed-1", allowed.Issue.ID) + + created, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "forced", IssueType: types.TypeTask, Priority: 2}, + ExplicitID: "foreign-1", + ForcePrefix: true, + CreateOnly: true, + }, "tester") + s.Require().NoError(err) + s.Equal("foreign-1", created.Issue.ID) +} + +func (s *testSuite) useCaseCreateOnlyRefusesOccupiedID() { + s.resetMintConfig("createonly", "") + uc := s.issueUseCase() + params := domain.CreateIssueParams{ + Issue: &types.Issue{Title: "first", IssueType: types.TypeTask, Priority: 2}, + ExplicitID: "createonly-1", + CreateOnly: true, + } + _, err := uc.CreateIssue(s.Ctx(), params, "tester") + s.Require().NoError(err) + + params.Issue = &types.Issue{Title: "replacement", IssueType: types.TypeTask, Priority: 2} + _, err = uc.CreateIssue(s.Ctx(), params, "tester") + s.Require().Error(err) + s.True(errors.Is(err, storage.ErrAlreadyExists), "want ErrAlreadyExists, got %v", err) + + stored, err := uc.GetIssue(s.Ctx(), "createonly-1") + s.Require().NoError(err) + s.Equal("first", stored.Title) +} + +func (s *testSuite) useCaseCreateAttachesNormalizedComments() { + s.resetMintConfig("comments", "") + createdAt := time.Date(2025, time.February, 3, 4, 5, 6, 0, time.UTC) + params := domain.CreateIssueParams{ + Issue: &types.Issue{Title: "with comments", IssueType: types.TypeTask, Priority: 2}, + ExplicitID: "comments-1", + Comments: []*types.Comment{ + {Text: "defaulted"}, + {ID: "imported-comment", Author: "importer", Text: "preserved", CreatedAt: createdAt}, + }, + } + + created, err := s.issueUseCase().CreateIssue(s.Ctx(), params, "actor") + s.Require().NoError(err) + s.Require().Len(created.Issue.Comments, 2) + s.Equal("comments-1", created.Issue.Comments[0].IssueID) + s.Equal("actor", created.Issue.Comments[0].Author) + s.NotEmpty(created.Issue.Comments[0].ID) + s.False(created.Issue.Comments[0].CreatedAt.IsZero()) + s.Equal("imported-comment", created.Issue.Comments[1].ID) + s.Equal("importer", created.Issue.Comments[1].Author) + s.Equal(createdAt, created.Issue.Comments[1].CreatedAt) + + s.Equal("", params.Comments[0].IssueID, "create must not mutate caller comments") +} + func (s *testSuite) TestIssueUseCase_ApplyGraph() { s.Run("ChildrenBeforeParentsSucceed", s.applyGraphChildrenBeforeParents) s.Run("ExplicitParentChildEdgeIsDeduped", s.applyGraphParentChildEdgeDedup) @@ -171,6 +262,33 @@ func (s *testSuite) TestIssueUseCase_ApplyGraph() { func (s *testSuite) TestIssueUseCase_MixedParentChildRouting() { s.Run("WispChildOfRegularParent", s.mixedWispChildOfRegularParent) s.Run("DepTargetClassification", s.mixedDepTargetClassification) + s.Run("ReverseDependencyUsesResultingSourceTierAndPreservesThread", s.mixedReverseDependencySourceTier) +} + +func (s *testSuite) mixedReverseDependencySourceTier() { + s.resetMintConfig("reverse", "") + uc := s.issueUseCase() + regular, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "regular source", IssueType: types.TypeTask, Priority: 2}, + }, "tester") + s.Require().NoError(err) + + wisp, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{ + Issue: &types.Issue{Title: "wisp target", IssueType: types.TypeTask, Priority: 2, Ephemeral: true}, + Dependencies: []domain.DependencySpec{{ + Type: types.DepRelated, + TargetID: regular.Issue.ID, + SwapDirection: true, + ThreadID: "thread-1", + }}, + }, "tester") + s.Require().NoError(err) + + records, err := s.depUseCase().GetIssueDependencyRecords(s.Ctx(), []string{regular.Issue.ID}) + s.Require().NoError(err) + s.Require().Len(records[regular.Issue.ID], 1) + s.Equal(wisp.Issue.ID, records[regular.Issue.ID][0].DependsOnID) + s.Equal("thread-1", records[regular.Issue.ID][0].ThreadID) } func (s *testSuite) mixedWispChildOfRegularParent() { diff --git a/internal/storage/domain/db/label.go b/internal/storage/domain/db/label.go index 56f9e4ca8..00d67d008 100644 --- a/internal/storage/domain/db/label.go +++ b/internal/storage/domain/db/label.go @@ -48,12 +48,32 @@ func (r *labelSQLRepositoryImpl) Insert(ctx context.Context, issueID, label, act } table := pickLabelTable(opts.UseWispsTable) //nolint:gosec // G201: table is one of two hardcoded constants - if _, err := r.runner.ExecContext(ctx, + result, err := r.runner.ExecContext(ctx, fmt.Sprintf("INSERT IGNORE INTO %s (issue_id, label) VALUES (?, ?)", table), issueID, label, - ); err != nil { + ) + if err != nil { return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: %w", issueID, label, err) } + rows, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: rows affected: %w", issueID, label, err) + } + if rows == 0 { + issueTable := "issues" + if opts.UseWispsTable { + issueTable = "wisps" + } + var count int + //nolint:gosec // G201: issueTable is one of two hardcoded constants. + if err := r.runner.QueryRowContext(ctx, fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id = ?", issueTable), issueID).Scan(&count); err != nil { + return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: verify issue: %w", issueID, label, err) + } + if count == 0 { + return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: issue does not exist", issueID, label) + } + return nil + } return r.events.Record(ctx, domain.Event{ IssueID: issueID, Type: types.EventLabelAdded, @@ -71,12 +91,20 @@ func (r *labelSQLRepositoryImpl) Delete(ctx context.Context, issueID, label, act } table := pickLabelTable(opts.UseWispsTable) //nolint:gosec // G201: table is one of two hardcoded constants - if _, err := r.runner.ExecContext(ctx, + result, err := r.runner.ExecContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE issue_id = ? AND label = ?", table), issueID, label, - ); err != nil { + ) + if err != nil { return fmt.Errorf("db: LabelSQLRepository.Delete %s/%s: %w", issueID, label, err) } + rows, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("db: LabelSQLRepository.Delete %s/%s: rows affected: %w", issueID, label, err) + } + if rows == 0 { + return nil + } return r.events.Record(ctx, domain.Event{ IssueID: issueID, Type: types.EventLabelRemoved, diff --git a/internal/storage/domain/db/label_test.go b/internal/storage/domain/db/label_test.go index 6e6f63716..eec46e6ad 100644 --- a/internal/storage/domain/db/label_test.go +++ b/internal/storage/domain/db/label_test.go @@ -69,7 +69,7 @@ func (s *testSuite) labelInsertIdempotent() { "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-lbl-dup", string(types.EventLabelAdded), ).Scan(&count)) - s.Equal(2, count) + s.Equal(1, count) } func (s *testSuite) labelInsertRecordsEvent() { @@ -259,6 +259,12 @@ func (s *testSuite) labelDeleteMissingNoop() { out, err := r.List(s.Ctx(), "bd-lbl-del-miss", domain.LabelOpts{}) s.Require().NoError(err) s.Empty(out) + var count int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", + "bd-lbl-del-miss", string(types.EventLabelRemoved), + ).Scan(&count)) + s.Equal(0, count) } func (s *testSuite) labelDeleteSpecificLabel() { diff --git a/internal/storage/domain/db/ready_helpers_test.go b/internal/storage/domain/db/ready_helpers_test.go index 630f52f25..936905b51 100644 --- a/internal/storage/domain/db/ready_helpers_test.go +++ b/internal/storage/domain/db/ready_helpers_test.go @@ -210,8 +210,8 @@ func (s *testSuite) blockedExcludesClosed() { s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) s.Require().NoError(dr.Insert(s.Ctx(), newDep("bd-blc-src", "bd-blc-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) - s.Require().NoError(r.Update(s.Ctx(), "bd-blc-src", - map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + _, err := r.Close(s.Ctx(), "bd-blc-src", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) s.Require().NoError(err) @@ -230,8 +230,8 @@ func (s *testSuite) blockedUnblocksOnClose() { s.Require().NoError(dr.Insert(s.Ctx(), newDep("bd-bluc-src", "bd-bluc-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) - s.Require().NoError(r.Update(s.Ctx(), "bd-bluc-tgt", - map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + _, err := r.Close(s.Ctx(), "bd-bluc-tgt", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) s.Require().NoError(err) diff --git a/internal/storage/domain/db/reopen_test.go b/internal/storage/domain/db/reopen_test.go index 30b49853d..947a27b2b 100644 --- a/internal/storage/domain/db/reopen_test.go +++ b/internal/storage/domain/db/reopen_test.go @@ -1,6 +1,9 @@ package db import ( + "database/sql" + + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" ) @@ -13,6 +16,10 @@ func (s *testSuite) TestIssueSQLRepositoryReopen() { s.Run("RoutesWisp", s.reopenRoutesWisp) s.Run("AppendsCommentOnReason", s.reopenAppendsComment) s.Run("NoCommentOnEmptyReason", s.reopenNoCommentEmptyReason) + s.Run("ReopensCustomDonePermanentAndClearsLifecycleFields", s.reopenCustomDonePermanent) + s.Run("ReopensCustomDoneWisp", s.reopenCustomDoneWisp) + s.Run("LeavesCustomNonDoneAndUnspecifiedStatusesUntouched", s.reopenLeavesIneligibleStatusesUntouched) + s.Run("ConfigurationFailureRollsBack", s.reopenConfigurationFailureRollsBack) } func (s *testSuite) reopenMutatesRow() { @@ -21,6 +28,11 @@ func (s *testSuite) reopenMutatesRow() { _, err := r.Close(s.Ctx(), "bd-ro-row", domain.CloseRowParams{Reason: "done", Session: "sess-1"}, "tester", domain.IssueTableOpts{}) s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), ` + INSERT INTO leases (issue_id, holder, granted_at, lease_expires_at, heartbeat_at) + VALUES (?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL 5 MINUTE), UTC_TIMESTAMP()) + `, "bd-ro-row", "stale-worker") + s.Require().NoError(err) res, err := r.Reopen(s.Ctx(), "bd-ro-row", domain.ReopenRowParams{Reason: "not really done"}, "tester", domain.IssueTableOpts{}) @@ -44,6 +56,11 @@ func (s *testSuite) reopenMutatesRow() { "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-row", string(types.EventReopened)).Scan(&evtCount)) s.Equal(1, evtCount) + + var leaseCount int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM leases WHERE issue_id = ?", "bd-ro-row").Scan(&leaseCount)) + s.Equal(0, leaseCount, "reopen must remove a seeded lease") } func (s *testSuite) reopenIdempotent() { @@ -86,6 +103,7 @@ func (s *testSuite) reopenMissingID() { _, err := r.Reopen(s.Ctx(), "bd-ro-missing", domain.ReopenRowParams{}, "tester", domain.IssueTableOpts{}) s.Require().Error(err) + s.ErrorIs(err, storage.ErrNotFound) } func (s *testSuite) reopenRoutesWisp() { @@ -148,3 +166,158 @@ func (s *testSuite) reopenNoCommentEmptyReason() { "bd-ro-nocmt", string(types.EventCommented)).Scan(&cmtCount)) s.Equal(0, cmtCount) } + +func (s *testSuite) reopenCustomDonePermanent() { + const customStatus = "archived-permanent" + + s.seedIssueRow("bd-ro-custom-done") + _, err := s.Runner().ExecContext(s.Ctx(), + "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", customStatus, string(types.CategoryDone)) + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), ` + UPDATE issues + SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?, + defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY) + WHERE id = ? + `, customStatus, "completed", "session-1", "bd-ro-custom-done") + s.Require().NoError(err) + + res, err := NewIssueSQLRepository(s.Runner()).Reopen(s.Ctx(), "bd-ro-custom-done", + domain.ReopenRowParams{Reason: "needs another pass"}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.True(res.Updated) + + var status, closeReason, closedBySession string + var closedAt, deferUntil sql.NullTime + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), ` + SELECT status, closed_at, close_reason, closed_by_session, defer_until + FROM issues WHERE id = ? + `, "bd-ro-custom-done").Scan(&status, &closedAt, &closeReason, &closedBySession, &deferUntil)) + s.Equal(string(types.StatusOpen), status) + s.False(closedAt.Valid, "closed_at must be cleared") + s.Equal("", closeReason) + s.Equal("", closedBySession) + s.False(deferUntil.Valid, "defer_until must be cleared") + + var reopened, comments int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-custom-done", string(types.EventReopened)).Scan(&reopened)) + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-custom-done", string(types.EventCommented)).Scan(&comments)) + s.Equal(1, reopened) + s.Equal(1, comments) +} + +func (s *testSuite) reopenCustomDoneWisp() { + const customStatus = "archived-wisp" + + s.seedWispRow("bd-ro-custom-done-wisp") + _, err := s.Runner().ExecContext(s.Ctx(), + "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", customStatus, string(types.CategoryDone)) + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), ` + UPDATE wisps + SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?, + defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY) + WHERE id = ? + `, customStatus, "completed", "session-1", "bd-ro-custom-done-wisp") + s.Require().NoError(err) + + res, err := NewIssueSQLRepository(s.Runner()).Reopen(s.Ctx(), "bd-ro-custom-done-wisp", + domain.ReopenRowParams{}, "tester", domain.IssueTableOpts{UseWispsTable: true}) + s.Require().NoError(err) + s.True(res.Updated) + s.True(res.IsWisp) + + var status, closeReason, closedBySession string + var closedAt, deferUntil sql.NullTime + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), ` + SELECT status, closed_at, close_reason, closed_by_session, defer_until + FROM wisps WHERE id = ? + `, "bd-ro-custom-done-wisp").Scan(&status, &closedAt, &closeReason, &closedBySession, &deferUntil)) + s.Equal(string(types.StatusOpen), status) + s.False(closedAt.Valid, "closed_at must be cleared") + s.Equal("", closeReason) + s.Equal("", closedBySession) + s.False(deferUntil.Valid, "defer_until must be cleared") +} + +func (s *testSuite) reopenLeavesIneligibleStatusesUntouched() { + r := NewIssueSQLRepository(s.Runner()) + statuses := []struct { + id string + status string + category types.StatusCategory + }{ + {id: "bd-ro-custom-active", status: "triaged", category: types.CategoryActive}, + {id: "bd-ro-custom-wip", status: "testing", category: types.CategoryWIP}, + {id: "bd-ro-custom-frozen", status: "on-ice", category: types.CategoryFrozen}, + {id: "bd-ro-custom-unknown", status: "queued", category: types.CategoryUnspecified}, + } + var err error + for _, status := range statuses[:3] { + s.seedIssueRow(status.id) + _, err = s.Runner().ExecContext(s.Ctx(), + "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", status.status, string(status.category)) + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), + "UPDATE issues SET status = ?, close_reason = ? WHERE id = ?", status.status, "keep", status.id) + s.Require().NoError(err) + } + s.seedIssueRow(statuses[3].id) + _, err = s.Runner().ExecContext(s.Ctx(), + "INSERT INTO config (`key`, value) VALUES (?, ?)", "status.custom", "queued") + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), + "UPDATE issues SET status = ?, close_reason = ? WHERE id = ?", "queued", "keep", statuses[3].id) + s.Require().NoError(err) + + for _, want := range statuses { + res, err := r.Reopen(s.Ctx(), want.id, domain.ReopenRowParams{Reason: "ignored"}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.False(res.Updated, "%s should not reopen", want.id) + s.False(res.AlreadyOpen, "%s is not literally open", want.id) + + var status, closeReason string + var events int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT status, close_reason FROM issues WHERE id = ?", want.id).Scan(&status, &closeReason)) + s.Equal(want.status, status) + s.Equal("keep", closeReason) + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ?", want.id).Scan(&events)) + s.Equal(0, events, "%s must not emit reopen or comment events", want.id) + } +} + +func (s *testSuite) reopenConfigurationFailureRollsBack() { + const customStatus = "missing-config-status" + + s.seedIssueRow("bd-ro-config-failure") + _, err := NewIssueSQLRepository(s.Runner()).Close(s.Ctx(), "bd-ro-config-failure", + domain.CloseRowParams{Reason: "done"}, "tester", domain.IssueTableOpts{}) + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), + "UPDATE issues SET status = ? WHERE id = ?", customStatus, "bd-ro-config-failure") + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), "DELETE FROM custom_statuses") + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), "DROP TABLE config") + s.Require().NoError(err) + + _, err = NewIssueSQLRepository(s.Runner()).Reopen(s.Ctx(), "bd-ro-config-failure", + domain.ReopenRowParams{Reason: "must roll back"}, "tester", domain.IssueTableOpts{}) + s.Require().Error(err) + + var status string + var reopened, comments int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT status FROM issues WHERE id = ?", "bd-ro-config-failure").Scan(&status)) + s.Equal(customStatus, status) + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-config-failure", string(types.EventReopened)).Scan(&reopened)) + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-config-failure", string(types.EventCommented)).Scan(&comments)) + s.Equal(0, reopened) + s.Equal(0, comments) +} diff --git a/internal/storage/domain/db/reopen_usecase_test.go b/internal/storage/domain/db/reopen_usecase_test.go index 9b42541f0..547ecc806 100644 --- a/internal/storage/domain/db/reopen_usecase_test.go +++ b/internal/storage/domain/db/reopen_usecase_test.go @@ -1,6 +1,7 @@ package db import ( + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" ) @@ -13,6 +14,7 @@ func (s *testSuite) TestIssueUseCase_ReopenIssue() { s.Run("MissingIDErrors", s.uccReopenMissingID) s.Run("WispVariantRoutesToWispsTable", s.uccReopenWispRoutes) s.Run("ReasonRecordedAsComment", s.uccReopenReasonComment) + s.Run("CustomNonDoneReportsNotReopened", s.uccReopenCustomNonDoneReportsNotReopened) } func (s *testSuite) uccReopenReturnsIssue() { @@ -60,6 +62,7 @@ func (s *testSuite) uccReopenMissingID() { _, err := s.issueUseCase().ReopenIssue(s.Ctx(), "bd-ucc-ro-missing", domain.ReopenIssueParams{}, "tester") s.Require().Error(err) + s.ErrorIs(err, storage.ErrNotFound) } func (s *testSuite) uccReopenWispRoutes() { @@ -99,3 +102,20 @@ func (s *testSuite) uccReopenReasonComment() { "bd-ucc-ro-cmt", string(types.EventCommented)).Scan(&comment)) s.Equal("qa found a regression", comment) } + +func (s *testSuite) uccReopenCustomNonDoneReportsNotReopened() { + const id = "bd-ucc-ro-custom-active" + s.seedIssueRow(id) + _, err := s.Runner().ExecContext(s.Ctx(), + "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", "triaged", string(types.CategoryActive)) + s.Require().NoError(err) + _, err = s.Runner().ExecContext(s.Ctx(), "UPDATE issues SET status = ? WHERE id = ?", "triaged", id) + s.Require().NoError(err) + + res, err := s.issueUseCase().ReopenIssue(s.Ctx(), id, + domain.ReopenIssueParams{}, "tester") + s.Require().NoError(err) + s.False(res.Reopened) + s.Require().NotNil(res.Issue) + s.Equal(types.Status("triaged"), res.Issue.Status) +} diff --git a/internal/storage/domain/db/update_same_status_test.go b/internal/storage/domain/db/update_same_status_test.go new file mode 100644 index 000000000..bbbe929fe --- /dev/null +++ b/internal/storage/domain/db/update_same_status_test.go @@ -0,0 +1,51 @@ +package db + +import ( + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func (s *testSuite) issueUpdateSameStatusInUnitOfWork() { + ctx := s.Ctx() + issue := newTestIssue("same-status-uow", "before") + s.Require().NoError(s.issueRepo().Insert(ctx, issue, "tester", domain.InsertIssueOpts{})) + var eventsBefore int + s.Require().NoError(s.Runner().QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ?", issue.ID).Scan(&eventsBefore)) + + tx, err := s.db.BeginTx(ctx, nil) + s.Require().NoError(err) + repo := NewIssueSQLRepository(tx) + before, err := repo.Get(ctx, issue.ID, domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Require().NoError(repo.Update(ctx, issue.ID, map[string]any{"status": types.StatusOpen}, "tester", domain.IssueTableOpts{})) + afterNoop, err := repo.Get(ctx, issue.ID, domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Equal(before.RowVersion, afterNoop.RowVersion) + var eventsAfterNoop, statusChangedAfterNoop int + s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ?", issue.ID).Scan(&eventsAfterNoop)) + s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", issue.ID, string(types.EventStatusChanged)).Scan(&statusChangedAfterNoop)) + s.Equal(eventsBefore, eventsAfterNoop) + s.Zero(statusChangedAfterNoop) + + s.Require().NoError(repo.Update(ctx, issue.ID, map[string]any{"status": types.StatusOpen, "title": "after"}, "tester", domain.IssueTableOpts{})) + afterScalar, err := repo.Get(ctx, issue.ID, domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Equal("after", afterScalar.Title) + s.NotEqual(afterNoop.RowVersion, afterScalar.RowVersion) + var updated, statusChanged int + s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", issue.ID, string(types.EventUpdated)).Scan(&updated)) + s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", issue.ID, string(types.EventStatusChanged)).Scan(&statusChanged)) + s.Equal(1, updated) + s.Zero(statusChanged) + s.Require().NoError(tx.Commit()) +} + +func (s *testSuite) issueUpdatePreservesCallerMap() { + ctx := s.Ctx() + issue := newTestIssue("preserve-caller-map", "before") + s.Require().NoError(s.issueRepo().Insert(ctx, issue, "tester", domain.InsertIssueOpts{})) + updates := map[string]any{"status": types.StatusOpen} + + s.Require().NoError(s.issueRepo().Update(ctx, issue.ID, updates, "tester", domain.IssueTableOpts{})) + s.Equal(map[string]any{"status": types.StatusOpen}, updates) +} diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index d638f1f15..2f79b4368 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -8,20 +8,17 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dberrors" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" ) -// ErrSelfDependency is returned when a dependency edge would point an issue at -// itself. It is the static prefix of the formatted message, wrapped so callers -// can errors.Is it while the human-readable text is preserved byte-for-byte. -var ErrSelfDependency = errors.New("cannot add self-dependency") - -// ErrDependencyCycle is returned when adding a dependency edge would introduce a -// scheduling cycle. It is scoped to the dependency-add family — the single and -// bulk add paths (add/addBulk) and the dolt cross-tier check — so callers can -// errors.Is any dependency-add cycle rejection. The whole-graph construction -// paths (ApplyIssueGraph/ApplyWispGraph) are a separate family and deliberately -// do not carry this sentinel yet. -var ErrDependencyCycle = errors.New("adding dependency would create a cycle") +// The dependency-edge refusals are declared and documented by the public +// contract package, github.com/steveyegge/beads/issueops. These are the same +// values, so every domain.ErrX reference and every errors.Is site keeps +// matching the identical error. +var ( + ErrSelfDependency = issueops.ErrSelfDependency + ErrDependencyCycle = issueops.ErrDependencyCycle +) // cycleError carries a fully-formatted cycle-rejection message while unwrapping // to ErrDependencyCycle. The bulk dependency-add path surfaces this text @@ -52,41 +49,14 @@ func NewCycleError(format string, args ...any) error { return cycleErrorf(format, args...) } -// DependencyTypeConflictError is returned when an edge already exists between -// the same pair with a DIFFERENT type. Its message is byte-identical to the -// embedded issueops path (issueops/dependencies.go) so `bd dep add` surfaces -// the same user-facing retype error on the domain/db seam as on the embedded -// store. It is a typed error so the use-case can pass it through -// unwrapped instead of burying it under an "add dep: insert:" prefix. -type DependencyTypeConflictError struct { - IssueID string - DependsOnID string - ExistingType string - RequestedType string -} +// DependencyTypeConflictError reports a duplicate dependency pair with a +// conflicting requested type. See issueops.DependencyTypeConflictError. +type DependencyTypeConflictError = issueops.DependencyTypeConflictError -// DependencyHierarchyConflictError is returned when a blocking dependency -// would gate an issue on one of its own ancestors or descendants. Either shape -// can never clear under the parent-child close/blocking semantics. -type DependencyHierarchyConflictError struct { - IssueID string - BlockerID string - BlockerIsAncestor bool -} - -func (e *DependencyHierarchyConflictError) Error() string { - if e.BlockerIsAncestor { - return fmt.Sprintf("%s cannot be blocked by its ancestor %s: %s cannot close until its descendants finish, so the gate would never clear", - e.IssueID, e.BlockerID, e.BlockerID) - } - return fmt.Sprintf("%s cannot be blocked by its descendant %s: blocked status cascades to descendants, so %s would inherit the block and never close", - e.IssueID, e.BlockerID, e.BlockerID) -} - -func (e *DependencyTypeConflictError) Error() string { - return fmt.Sprintf("dependency %s -> %s already exists with type %q (requested %q); remove it first with 'bd dep remove' then re-add", - e.IssueID, e.DependsOnID, e.ExistingType, e.RequestedType) -} +// DependencyHierarchyConflictError reports a dependency that would make a +// blocking hierarchy impossible to complete. See +// issueops.DependencyHierarchyConflictError. +type DependencyHierarchyConflictError = issueops.DependencyHierarchyConflictError type DepDirection int diff --git a/internal/storage/domain/issue.go b/internal/storage/domain/issue.go index 6ba55dc31..fd842e239 100644 --- a/internal/storage/domain/issue.go +++ b/internal/storage/domain/issue.go @@ -14,6 +14,7 @@ import ( type InsertIssueOpts struct { UseWispsTable bool + CreateOnly bool } type IssueTableOpts struct { @@ -36,6 +37,7 @@ type ClaimRowResult struct { type IssueSQLRepository interface { Insert(ctx context.Context, issue *types.Issue, actor string, opts InsertIssueOpts) error InsertBatch(ctx context.Context, issues []*types.Issue, actor string, opts InsertIssueOpts) error + MovePersistence(ctx context.Context, id string, mode types.PersistenceMode) (changed bool, err error) Update(ctx context.Context, id string, updates map[string]any, actor string, opts IssueTableOpts) error Claim(ctx context.Context, id, actor string, opts IssueTableOpts) (ClaimRowResult, error) Get(ctx context.Context, id string, opts IssueTableOpts) (*types.Issue, error) @@ -58,6 +60,7 @@ type IssueSQLRepository interface { AffectedByDeletion(ctx context.Context, issueIDs, wispIDs []string) (affectedIssues, affectedWisps []string, err error) RecomputeIsBlocked(ctx context.Context, issueIDs, wispIDs []string) error Close(ctx context.Context, id string, params CloseRowParams, actor string, opts IssueTableOpts) (CloseRowResult, error) + CloseChecked(ctx context.Context, id string, params CloseRowParams, actor string, force bool) (CloseRowResult, error) Reopen(ctx context.Context, id string, params ReopenRowParams, actor string, opts IssueTableOpts) (ReopenRowResult, error) GetNewlyUnblockedByClose(ctx context.Context, closedID string) ([]*types.Issue, error) ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) @@ -83,6 +86,7 @@ type CloseRowResult struct { Updated bool AlreadyClosed bool IsWisp bool + OpenChildren int } type ReopenRowParams struct { @@ -152,6 +156,8 @@ type CreateIssueParams struct { WaitsFor *WaitsForSpec DiscoveredFromParent string ForcePrefix bool + CreateOnly bool + Comments []*types.Comment } type DependencySpec struct { @@ -159,6 +165,7 @@ type DependencySpec struct { TargetID string SwapDirection bool Metadata string + ThreadID string } type WaitsForSpec struct { @@ -230,12 +237,16 @@ type ClaimReadyResult struct { } type UpdateSpec struct { - Fields map[string]any - Claim bool - AddLabels []string - RemoveLabels []string - SetLabels *[]string - Reparent *string + Fields map[string]any + Claim bool + // ExpectedVersion requires the current row version to match before any + // claim or field writes. + ExpectedVersion *int64 + Persistence *types.PersistenceMode + AddLabels []string + RemoveLabels []string + SetLabels *[]string + Reparent *string // ExpectedAssignee and ExpectedStatus are the bd-wsqvw compare-and-set // guards (`bd update --if-assignee/--if-status`): when non-nil, the whole @@ -314,8 +325,9 @@ type CloseIssueParams struct { } type CloseIssueResult struct { - Issue *types.Issue - Closed bool + Issue *types.Issue + Closed bool + OpenChildren int } type ReopenIssueParams struct { @@ -433,20 +445,88 @@ func (u *issueUseCaseImpl) update(ctx context.Context, id string, updates map[st if len(updates) == 0 { return nil } - if rawType, ok := updates["issue_type"]; ok { - if issueType, ok := rawType.(string); ok && issueType != "" { - customTypes, err := u.cfgRepo.GetCustomTypes(ctx) - if err != nil { - return fmt.Errorf("update: read custom types: %w", err) - } - if !types.IssueType(issueType).IsValidWithCustom(customTypes) { - return fmt.Errorf("invalid issue type: %s", issueType) - } - } + if err := validateCanonicalIssueUpdates(updates); err != nil { + return err + } + if err := u.validateIssueTypeUpdate(ctx, updates); err != nil { + return err } return u.issueRepo.Update(ctx, id, updates, actor, IssueTableOpts{UseWispsTable: useWisp}) } +// validateIssueTypeUpdate rejects an issue_type the configuration does not +// define. It reads the configured custom types, so unlike +// validateCanonicalIssueUpdates it needs the use case and a context. +func (u *issueUseCaseImpl) validateIssueTypeUpdate(ctx context.Context, updates map[string]any) error { + rawType, ok := updates["issue_type"] + if !ok { + return nil + } + issueType, ok := rawType.(string) + if !ok { + return nil + } + customTypes, err := u.cfgRepo.GetCustomTypes(ctx) + if err != nil { + return fmt.Errorf("update: read custom types: %w", err) + } + if !types.IssueType(issueType).IsValidWithCustom(customTypes) { + return fmt.Errorf("%w: invalid issue type: %s", storage.ErrValidation, issueType) + } + return nil +} + +// validateCanonicalIssueUpdates rejects out-of-range values for the canonical +// scalar columns, and rejects values whose Go type the column cannot carry. An +// unsupported type used to fall through unvalidated and reach the SQL layer, +// which coerced it silently -- a title of 7 was stored as "7", and an int64 +// priority or estimate skipped its range check entirely. +func validateCanonicalIssueUpdates(updates map[string]any) error { + if value, ok := updates["title"]; ok { + title, isString := value.(string) + if !isString { + return canonicalIssueUpdateTypeError("title", value, "string") + } + if err := types.ValidateIssueTitle(title); err != nil { + return canonicalIssueUpdateValidationError("title", err) + } + } + if value, ok := updates["priority"]; ok { + priority, isInt := value.(int) + if !isInt { + return canonicalIssueUpdateTypeError("priority", value, "int") + } + if err := types.ValidateIssuePriority(priority); err != nil { + return canonicalIssueUpdateValidationError("priority", err) + } + } + if value, ok := updates["estimated_minutes"]; ok { + var estimatedMinutes *int + switch value := value.(type) { + case int: + estimatedMinutes = &value + case *int: + estimatedMinutes = value + case nil: + // Clearing the estimate; a nil estimate validates. + default: + return canonicalIssueUpdateTypeError("estimated_minutes", value, "int or *int") + } + if err := types.ValidateIssueEstimatedMinutes(estimatedMinutes); err != nil { + return canonicalIssueUpdateValidationError("estimated_minutes", err) + } + } + return nil +} + +func canonicalIssueUpdateValidationError(field string, err error) error { + return fmt.Errorf("%w: update field %q: %w", storage.ErrValidation, field, err) +} + +func canonicalIssueUpdateTypeError(field string, value any, want string) error { + return fmt.Errorf("%w: update field %q: expected %s, got %T", storage.ErrValidation, field, want, value) +} + func (u *issueUseCaseImpl) ClaimIssue(ctx context.Context, id, actor string) (ClaimResult, error) { return u.claim(ctx, id, actor, false) } @@ -501,13 +581,7 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda return nil, fmt.Errorf("ApplyUpdate %s: %w", id, err) } - // bd-wsqvw field guards: refuse the whole spec atomically on a stale - // assignee/status. The read shares this unit of work's transaction, and - // every field update rewrites row_lock, so a writer that commits during - // the attempt collides at commit time and the caller's whole-attempt - // retry re-checks here on the redo — same CAS invariant as the store-level - // UpdateIssueChecked path. - if spec.ExpectedAssignee != nil || spec.ExpectedStatus != nil { + if spec.ExpectedVersion != nil || spec.ExpectedAssignee != nil || spec.ExpectedStatus != nil { var current *types.Issue if useWisp { current, err = u.GetWisp(ctx, id) @@ -520,6 +594,9 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda if current == nil { return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) } + if spec.ExpectedVersion != nil && current.RowVersion != *spec.ExpectedVersion { + return nil, fmt.Errorf("%w: expected %d, got %d", storage.ErrVersionMismatch, *spec.ExpectedVersion, current.RowVersion) + } if spec.ExpectedAssignee != nil && current.Assignee != *spec.ExpectedAssignee { return nil, fmt.Errorf("%w: %s is held by %q, expected %q", storage.ErrAssigneeMismatch, id, current.Assignee, *spec.ExpectedAssignee) @@ -530,6 +607,17 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda } } + // Validate the requested field values before anything mutates. The claim + // below writes assignee and status, so a spec that pairs Claim with an + // invalid field used to leave the issue claimed by an update that never + // applied. + if err := validateCanonicalIssueUpdates(spec.Fields); err != nil { + return nil, err + } + if err := u.validateIssueTypeUpdate(ctx, spec.Fields); err != nil { + return nil, err + } + if spec.Claim { if useWisp { if _, err := u.ClaimWisp(ctx, id, actor); err != nil { @@ -564,27 +652,26 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda return nil, err } } - } else { - if len(spec.AddLabels) > 0 { - if useWisp { - if err := u.labelUC.AddWispLabels(ctx, id, spec.AddLabels, actor); err != nil { - return nil, err - } - } else { - if err := u.labelUC.AddLabels(ctx, id, spec.AddLabels, actor); err != nil { - return nil, err - } + } + if len(spec.AddLabels) > 0 { + if useWisp { + if err := u.labelUC.AddWispLabels(ctx, id, spec.AddLabels, actor); err != nil { + return nil, err + } + } else { + if err := u.labelUC.AddLabels(ctx, id, spec.AddLabels, actor); err != nil { + return nil, err } } - if len(spec.RemoveLabels) > 0 { - if useWisp { - if err := u.labelUC.RemoveWispLabels(ctx, id, spec.RemoveLabels, actor); err != nil { - return nil, err - } - } else { - if err := u.labelUC.RemoveLabels(ctx, id, spec.RemoveLabels, actor); err != nil { - return nil, err - } + } + if len(spec.RemoveLabels) > 0 { + if useWisp { + if err := u.labelUC.RemoveWispLabels(ctx, id, spec.RemoveLabels, actor); err != nil { + return nil, err + } + } else { + if err := u.labelUC.RemoveLabels(ctx, id, spec.RemoveLabels, actor); err != nil { + return nil, err } } } @@ -601,6 +688,16 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda } } + if spec.Persistence != nil { + if _, err := u.issueRepo.MovePersistence(ctx, id, *spec.Persistence); err != nil { + return nil, fmt.Errorf("ApplyUpdate: move persistence for %s: %w", id, err) + } + useWisp, err = u.isWispID(ctx, id) + if err != nil { + return nil, fmt.Errorf("ApplyUpdate: re-locate %s after persistence move: %w", id, err) + } + } + var issue *types.Issue if useWisp { issue, err = u.GetWisp(ctx, id) @@ -718,17 +815,50 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams, issue.ID = minted } + if params.CreateOnly && params.ExplicitID != "" && !params.ForcePrefix { + configuredPrefix, err := u.cfgRepo.GetConfig(ctx, "issue_prefix") + if err != nil { + return CreateIssueResult{}, fmt.Errorf("create: read issue prefix: %w", err) + } + allowedPrefixes, err := u.cfgRepo.GetConfig(ctx, "allowed_prefixes") + if err != nil { + return CreateIssueResult{}, fmt.Errorf("create: read allowed prefixes: %w", err) + } + if err := validateExplicitIDPrefix(issue.ID, strings.TrimSuffix(configuredPrefix, "-"), allowedPrefixes); err != nil { + return CreateIssueResult{}, fmt.Errorf("create: explicit ID prefix: %w", err) + } + } + if params.DiscoveredFromParent != "" { if parent, err := u.GetIssue(ctx, params.DiscoveredFromParent); err == nil && parent.SourceRepo != "" { issue.SourceRepo = parent.SourceRepo } } - insertOpts := InsertIssueOpts{UseWispsTable: useWisp} + insertOpts := InsertIssueOpts{UseWispsTable: useWisp, CreateOnly: params.CreateOnly} if err := u.issueRepo.Insert(ctx, issue, actor, insertOpts); err != nil { return CreateIssueResult{}, fmt.Errorf("create: insert: %w", err) } + if len(params.Comments) > 0 { + issue.Comments = make([]*types.Comment, 0, len(params.Comments)) + for _, comment := range params.Comments { + if comment == nil { + return CreateIssueResult{}, fmt.Errorf("create: comment must not be nil") + } + copy := *comment + copy.IssueID = issue.ID + if copy.Author == "" { + copy.Author = actor + } + inserted, err := u.commentRepo.InsertRecord(ctx, ©, CommentOpts{UseWispsTable: useWisp}) + if err != nil { + return CreateIssueResult{}, fmt.Errorf("create: insert comment: %w", err) + } + issue.Comments = append(issue.Comments, inserted) + } + } + result := CreateIssueResult{Issue: issue} if params.ParentID != "" { @@ -744,7 +874,11 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams, } if params.InheritLabelsFromParent && params.ParentID != "" { - parentLabels, err := u.labelRepo.List(ctx, params.ParentID, LabelOpts{UseWispsTable: useWisp}) + parentIsWisp, err := u.isWispID(ctx, params.ParentID) + if err != nil { + return result, fmt.Errorf("create: determine parent tier for label inheritance from %s: %w", params.ParentID, err) + } + parentLabels, err := u.labelRepo.List(ctx, params.ParentID, LabelOpts{UseWispsTable: parentIsWisp}) switch { case dberrors.IsTableNotExist(err): // Older schemas may lack the wisp label table; nothing to inherit. @@ -785,11 +919,16 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams, DependsOnID: spec.TargetID, Type: spec.Type, Metadata: spec.Metadata, + ThreadID: spec.ThreadID, } if spec.SwapDirection { dep.IssueID, dep.DependsOnID = dep.DependsOnID, dep.IssueID } - if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{UseWispsTable: useWisp}); err != nil { + depSourceIsWisp, err := u.isWispID(ctx, dep.IssueID) + if err != nil { + return result, fmt.Errorf("create: determine dep source tier for %s: %w", dep.IssueID, err) + } + if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{UseWispsTable: depSourceIsWisp}); err != nil { return result, fmt.Errorf("create: add dep %s -> %s: %w", dep.IssueID, dep.DependsOnID, err) } result.PostCreateWrites = true @@ -810,6 +949,19 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams, return result, nil } +func validateExplicitIDPrefix(id, prefix, allowedPrefixes string) error { + if strings.HasPrefix(id, prefix+"-") { + return nil + } + for _, allowed := range strings.Split(allowedPrefixes, ",") { + allowed = strings.TrimSpace(allowed) + if allowed != "" && strings.HasPrefix(id, allowed+"-") { + return nil + } + } + return fmt.Errorf("%w: issue ID %s does not match configured prefix %s", storage.ErrPrefixMismatch, id, prefix) +} + func (u *issueUseCaseImpl) CreateIssues(ctx context.Context, params []CreateIssueParams, actor string) (CreateIssuesResult, error) { return u.createMany(ctx, params, actor, false) } @@ -1388,82 +1540,32 @@ func (u *issueUseCaseImpl) CloseWisp(ctx context.Context, id string, params Clos return u.close(ctx, id, params, actor, true) } -// CloseIssueChecked closes an issue, refusing with storage.ErrCloseBlocked when -// the issue has a live, open direct blocker unless force is set. The blocker -// check (IsBlocked) and the close (CloseIssue) run through the same unit-of-work -// transaction, so this is a single enforcement point rather than a re-check of -// separate reads. When force is set or the guard passes it delegates to the -// unchecked CloseIssue, preserving its CloseIssueResult semantics exactly. +// CloseIssueChecked closes an issue through the shared guarded close path. func (u *issueUseCaseImpl) CloseIssueChecked(ctx context.Context, id string, params CloseIssueParams, actor string, force bool) (CloseIssueResult, error) { return u.closeChecked(ctx, id, params, actor, force, false) } -// CloseWispChecked is the wisp twin of CloseIssueChecked: it applies the same -// live-direct-blocker guard (via IsWispBlocked) before delegating to the -// unchecked CloseWisp. +// CloseWispChecked is the wisp twin of CloseIssueChecked. func (u *issueUseCaseImpl) CloseWispChecked(ctx context.Context, id string, params CloseIssueParams, actor string, force bool) (CloseIssueResult, error) { return u.closeChecked(ctx, id, params, actor, force, true) } -// isClosed reports whether the issue (or wisp) identified by id is already in -// the closed status, read in the same unit of work as the close so the check -// and the close cannot straddle a concurrent state change. A missing row (or, -// for a wisp source, a missing optional wisps table) reports not-closed so -// closeChecked falls through to u.close, whose repo Close surfaces the not-found -// result — mirroring issueops.isClosedInTx on the embedded checked-close path. -func (u *issueUseCaseImpl) isClosed(ctx context.Context, id string, useWisp bool) (bool, error) { - issue, err := u.issueRepo.Get(ctx, id, IssueTableOpts{UseWispsTable: useWisp}) - if err != nil { - if dberrors.IsNoRows(err) || dberrors.IsTableNotExist(err) { - return false, nil - } - return false, err - } - if issue == nil { - return false, nil - } - return issue.Status == types.StatusClosed, nil -} - func (u *issueUseCaseImpl) closeChecked(ctx context.Context, id string, params CloseIssueParams, actor string, force, useWisp bool) (CloseIssueResult, error) { - if !force { - // The blocked guard only has meaning for an open→closed transition. An - // already-closed row is an idempotent no-op (Closed=false per the - // Storage.CloseIssueChecked contract), so detect that first: a closed row - // can still carry a stale is_blocked=1 (e.g. after a cross-clone Dolt - // merge, a state GetStatistics filters as `is_blocked = 1 AND status <> - // 'closed'`) whose live direct blocker would otherwise refuse the - // idempotent re-close with ErrCloseBlocked. This mirrors - // issueops.CloseIssueCheckedInTx, which runs isClosedInTx before the - // is_blocked guard; u.close below is the sole detector of the - // already-closed no-op (matching the Force path, which reaches - // Closed=false by skipping the guard). - closed, err := u.isClosed(ctx, id, useWisp) - if err != nil { - return CloseIssueResult{}, err - } - if !closed { - var ( - blocked bool - blockers []string - ) - if useWisp { - blocked, blockers, err = u.depUC.IsWispBlocked(ctx, id) - } else { - blocked, blockers, err = u.depUC.IsBlocked(ctx, id) - } - if err != nil { - return CloseIssueResult{}, err - } - // Refuse only on a live, open direct blocker. A bare is_blocked=1 with no - // live direct blocker (a purely transitive block) closes — matching the - // historical `bd close` predicate and the embedded checked-close path. - if blocked && len(blockers) > 0 { - return CloseIssueResult{}, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, id, blockers) - } - } + if id == "" { + return CloseIssueResult{}, fmt.Errorf("close: id must not be empty") } - return u.close(ctx, id, params, actor, useWisp) + if actor == "" { + return CloseIssueResult{}, fmt.Errorf("close: actor must not be empty") + } + row, err := u.issueRepo.CloseChecked(ctx, id, CloseRowParams{Reason: params.Reason, Session: params.Session}, actor, force) + if err != nil { + return CloseIssueResult{}, fmt.Errorf("close %s: %w", id, err) + } + issue, err := u.issueRepo.Get(ctx, id, IssueTableOpts{UseWispsTable: row.IsWisp || useWisp}) + if err != nil { + return CloseIssueResult{}, fmt.Errorf("close %s: reload: %w", id, err) + } + return CloseIssueResult{Issue: issue, Closed: !row.AlreadyClosed, OpenChildren: row.OpenChildren}, nil } func (u *issueUseCaseImpl) close(ctx context.Context, id string, params CloseIssueParams, actor string, useWisp bool) (CloseIssueResult, error) { @@ -1512,7 +1614,7 @@ func (u *issueUseCaseImpl) reopen(ctx context.Context, id string, params ReopenI } return ReopenIssueResult{ Issue: issue, - Reopened: !row.AlreadyOpen, + Reopened: row.Updated, }, nil } diff --git a/internal/storage/embeddeddolt/close_issue_checked_test.go b/internal/storage/embeddeddolt/close_issue_checked_test.go index 32c736c85..7b9b07906 100644 --- a/internal/storage/embeddeddolt/close_issue_checked_test.go +++ b/internal/storage/embeddeddolt/close_issue_checked_test.go @@ -77,6 +77,28 @@ func TestEmbeddedCloseIssueChecked(t *testing.T) { if iss.Status != types.StatusClosed { t.Fatalf("cic-target status = %q after force, want closed", iss.Status) } + + parent := &types.Issue{ID: "cicoc-parent", Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + child := &types.Issue{ID: "cicoc-child", Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + for _, issue := range []*types.Issue{parent, child} { + if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatalf("CreateIssue(%s): %v", issue.ID, err) + } + } + if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "tester"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + res, err = te.store.CloseIssueChecked(ctx, parent.ID, "tester", storage.CloseIssueOptions{Reason: "done"}) + if !errors.Is(err, storage.ErrCloseOpenChildren) { + t.Fatalf("close error = %v, want errors.Is(_, ErrCloseOpenChildren)", err) + } + if iss, getErr := te.store.GetIssue(ctx, parent.ID); getErr != nil || iss.Status != types.StatusOpen { + t.Fatalf("GetIssue after refusal = (%+v, %v), want open parent", iss, getErr) + } + res, err = te.store.CloseIssueChecked(ctx, parent.ID, "tester", storage.CloseIssueOptions{Reason: "override", Force: true}) + if err != nil || res.Unchanged || res.OpenChildren != 1 { + t.Fatalf("force result = %+v, err = %v; want changed close with 1 child", res, err) + } } // TestEmbeddedCloseIssueCheckedTransitiveBlockedCloses proves the guard refuses diff --git a/internal/storage/embeddeddolt/issue_lifecycle_test.go b/internal/storage/embeddeddolt/issue_lifecycle_test.go new file mode 100644 index 000000000..44a9d74d1 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_lifecycle_test.go @@ -0,0 +1,31 @@ +//go:build cgo + +package embeddeddolt + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" +) + +func TestEmbeddedDoltStoreIssueLifecycleBuildsOperations(t *testing.T) { + lifecycle, err := (&EmbeddedDoltStore{}).IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle() error = %v", err) + } + if lifecycle == nil { + t.Fatal("IssueLifecycle() returned nil operations") + } +} + +func TestEmbeddedDoltStoreIssueLifecycleRejectsNilStore(t *testing.T) { + lifecycle, err := (*EmbeddedDoltStore)(nil).IssueLifecycle() + if lifecycle != nil { + t.Fatalf("IssueLifecycle() lifecycle = %T, want nil", lifecycle) + } + var unsupported *storage.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("IssueLifecycle() error = %v, want *storage.ErrUnsupported", err) + } +} diff --git a/internal/storage/embeddeddolt/issue_operations.go b/internal/storage/embeddeddolt/issue_operations.go new file mode 100644 index 000000000..3050892cc --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations.go @@ -0,0 +1,87 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// IssueLifecycle returns the guarded issue-lifecycle surface for this store. +func (s *EmbeddedDoltStore) IssueLifecycle() (issueops.Lifecycle, error) { + return NewIssueOperations(s) +} + +// NewIssueOperations returns guarded issue operations backed by store. +func NewIssueOperations(store *EmbeddedDoltStore) (issueops.Lifecycle, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewIssueOperations", Backend: "nil"} + } + return &issueOperations{store: store}, nil +} + +type issueOperations struct{ store *EmbeddedDoltStore } + +// updateCommitMessage names the updated issue in the Dolt commit message. +func updateCommitMessage(issueID string) string { + if issueID == "" { + return "bd: update issue" + } + return "bd: update " + issueID +} + +func (o *issueOperations) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) { + snapshot := storageissueops.CloneCreateRequest(request) + var result issueops.CreateResult + err := o.store.runIssueOperationTx(ctx, "bd: create issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteCreate(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +func (o *issueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) { + snapshot := storageissueops.CloneUpdateRequest(request) + var result issueops.UpdateResult + // Same ID-bearing commit message as the server-backed store, so `bd dolt + // log` reads the same on both backends. + err := o.store.runIssueOperationTx(ctx, updateCommitMessage(snapshot.IssueID), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteUpdate(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +func (o *issueOperations) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) { + snapshot := storageissueops.CloneCloseRequest(request) + var result issueops.CloseResult + err := o.store.runIssueOperationTx(ctx, "bd: close issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteClose(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +func (o *issueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) { + snapshot := storageissueops.CloneReopenRequest(request) + var result issueops.ReopenResult + err := o.store.runIssueOperationTx(ctx, "bd: reopen issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteReopen(ctx, tx, snapshot) + return tables, err + }) + return result, err +} + +var _ issueops.Lifecycle = (*issueOperations)(nil) diff --git a/internal/storage/embeddeddolt/issue_operations_behavior_test.go b/internal/storage/embeddeddolt/issue_operations_behavior_test.go new file mode 100644 index 000000000..904a26b55 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations_behavior_test.go @@ -0,0 +1,589 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestEmbeddedIssueOperationsGuardedVerbs gives the embedded adapter the same +// public guarded-operation coverage as the direct implementation. +func TestEmbeddedIssueOperationsGuardedVerbs(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + create := func(t *testing.T, id string) *types.Issue { + t.Helper() + issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + return issue + } + + t.Run("create rejects occupied ID", func(t *testing.T) { + create(t, "ops-duplicate") + _, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-duplicate", Title: "replacement", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}}) + if !errors.Is(err, publicops.ErrAlreadyExists) { + t.Fatalf("Create error = %v, want ErrAlreadyExists", err) + } + got, getErr := te.store.GetIssue(ctx, "ops-duplicate") + if getErr != nil || got.Title != "ops-duplicate" { + t.Fatalf("stored duplicate = %#v, %v; want original title", got, getErr) + } + }) + + t.Run("create validates prefix and aggregates relations", func(t *testing.T) { + parent := create(t, "ops-parent") + spawner := create(t, "ops-spawner") + if err := te.store.AddLabel(ctx, parent.ID, "parent-label", "seed"); err != nil { + t.Fatal(err) + } + target := create(t, "ops-target") + request := publicops.CreateRequest{Actor: "writer", Issue: &types.Issue{ID: "foreign-aggregate", Title: "aggregate", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, ParentID: parent.ID, InheritLabelsFromParent: true, Dependencies: []publicops.CreateDependency{{TargetID: target.ID, Type: types.DepRelated, ThreadID: "thread"}, {TargetID: target.ID, Type: types.DepRelatesTo, Reverse: true, ThreadID: "reverse-thread"}}, WaitsFor: &publicops.WaitsFor{SpawnerID: spawner.ID}} + _, err := operations.Create(ctx, request) + if !errors.Is(err, publicops.ErrPrefixMismatch) { + t.Fatalf("unforced foreign prefix error = %v, want ErrPrefixMismatch", err) + } + request.ForceIDPrefix = true + result, err := operations.Create(ctx, request) + if err != nil { + t.Fatalf("forced Create: %v", err) + } + if len(result.Issue.Labels) != 1 || result.Issue.Labels[0] != "parent-label" || len(result.Issue.Dependencies) != 3 { + t.Fatalf("Create result aggregate = %#v", result.Issue) + } + inbound, err := te.store.GetDependentRecords(ctx, result.Issue.ID, "", 10, "") + if err != nil || len(inbound) != 1 || inbound[0].IssueID != target.ID || inbound[0].ThreadID != "reverse-thread" { + t.Fatalf("reverse dependency = %#v, %v", inbound, err) + } + }) + + t.Run("update enforces version and claim", func(t *testing.T) { + issue := create(t, "ops-update") + stale := issue.RowVersion + 1 + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must not persist"}}}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("stale Update error = %v, want ErrVersionMismatch", err) + } + result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Claim: true}) + if err != nil || !result.Changed || result.Issue.Assignee != "writer" || result.Issue.Status != publicops.StatusInProgress { + t.Fatalf("claim result = %#v, %v", result, err) + } + }) + + t.Run("close and reopen enforce versions and children", func(t *testing.T) { + parent := create(t, "ops-close-parent") + child := create(t, "ops-close-child") + if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatal(err) + } + stale := parent.RowVersion + 1 + _, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("stale Close error = %v, want ErrVersionMismatch", err) + } + _, err = operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID}) + if !errors.Is(err, publicops.ErrCloseOpenChildren) { + t.Fatalf("unforced close error = %v, want ErrCloseOpenChildren", err) + } + closed, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true}) + if err != nil || !closed.Changed || closed.OpenChildren != 1 { + t.Fatalf("forced close = %#v, %v", closed, err) + } + stale = closed.Issue.RowVersion + 1 + _, err = operations.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("stale Reopen error = %v, want ErrVersionMismatch", err) + } + }) +} + +func TestEmbeddedIssueOperationsUpdateMetadataPatchOrderingAndReplacementGuard(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_metadata_order") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + issue := &types.Issue{ID: "ops-metadata-order", Title: "metadata", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"old","remove":"old"}`)} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{ + Merge: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"keep":"merged","merge":true}`)}, + Set: map[string]json.RawMessage{"after": json.RawMessage(`"set"`), "keep": json.RawMessage(`"set"`)}, + Unset: []string{"keep", "remove"}, + }}}) + if err != nil || !updated.Changed || !sameEmbeddedMetadataJSON(updated.Issue.Metadata, json.RawMessage(`{"after":"set","merge":true}`)) { + t.Fatalf("ordered metadata update = %#v, %v", updated, err) + } + replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)}}}}) + if err != nil || !replaced.Changed || !sameEmbeddedMetadataJSON(replaced.Issue.Metadata, json.RawMessage(`{"replacement":true}`)) { + t.Fatalf("metadata replacement = %#v, %v", replaced, err) + } + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{ + Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)}, + Set: map[string]json.RawMessage{"must_not_persist": json.RawMessage(`true`)}, + }}}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("combined replacement error = %v, want ErrValidation", err) + } + stored, err := te.store.GetIssue(ctx, issue.ID) + if err != nil || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"replacement":true}`)) { + t.Fatalf("replacement guard persisted metadata = %#v, %v", stored, err) + } +} + +func TestEmbeddedIssueOperationsUpdateLabelPatchOrderingAndNoop(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_label_order") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + issue := &types.Issue{ID: "ops-label-order", Title: "labels", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"old", "shared"}} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + patch := publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "shared"}}, Add: []string{"add", "shared"}, Remove: []string{"old", "shared"}} + updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: patch}}) + if err != nil || !updated.Changed || strings.Join(updated.Issue.Labels, ",") != "add,replace" { + t.Fatalf("ordered labels update = %#v, %v", updated, err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "add"}}, Add: []string{"add"}, Remove: []string{"missing"}}}}) + if err != nil || noOp.Changed || strings.Join(noOp.Issue.Labels, ",") != "add,replace" { + t.Fatalf("same labels update = %#v, %v", noOp, err) + } +} + +func TestEmbeddedIssueOperationsUpdateParentReplacementClearAndNoop(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_parent_order") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + create := func(id string) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + parentA, parentB, parentC := create("ops-parent-a"), create("ops-parent-b"), create("ops-parent-c") + child := create("ops-parent-child") + for _, parent := range []*types.Issue{parentA, parentB} { + if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatal(err) + } + } + replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}}) + if err != nil || !replaced.Changed || embeddedIssueParentIDs(replaced.Issue) != parentC.ID { + t.Fatalf("parent replacement = %#v, %v", replaced, err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}}) + if err != nil || noOp.Changed || embeddedIssueParentIDs(noOp.Issue) != parentC.ID { + t.Fatalf("same parent replacement = %#v, %v", noOp, err) + } + cleared, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}}) + if err != nil || !cleared.Changed || embeddedIssueParentIDs(cleared.Issue) != "" { + t.Fatalf("parent clear = %#v, %v", cleared, err) + } + noOp, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}}) + if err != nil || noOp.Changed || embeddedIssueParentIDs(noOp.Issue) != "" { + t.Fatalf("same parent clear = %#v, %v", noOp, err) + } +} + +func TestEmbeddedIssueOperationsUpdateClaimCASAndTransferMatrix(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_claim_matrix") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + create := func(id, assignee string, status types.Status, wisp bool) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Assignee: assignee, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + t.Run("version and field CAS refuse before mutation", func(t *testing.T) { + issue := create("ops-cas", "owner", types.StatusOpen, false) + stale := issue.RowVersion + 1 + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("version error = %v", err) + } + expectedAssignee, expectedStatus := "other", publicops.StatusOpen + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, ExpectedStatus: &expectedStatus, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrAssigneeMismatch) { + t.Fatalf("assignee error = %v", err) + } + expectedAssignee = "owner" + wrongStatus := publicops.StatusInProgress + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, ExpectedStatus: &wrongStatus, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}}) + if !errors.Is(err, publicops.ErrStatusMismatch) { + t.Fatalf("status error = %v", err) + } + expectedStatus = publicops.StatusOpen + matched, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, ExpectedStatus: &expectedStatus, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "matched"}}}) + if err != nil || !matched.Changed || matched.Issue.Title != "matched" { + t.Fatalf("matching CAS = %#v, %v", matched, err) + } + got, getErr := te.store.GetIssue(ctx, issue.ID) + if getErr != nil || got.Title != "matched" { + t.Fatalf("CAS mutation = %#v, %v", got, getErr) + } + }) + t.Run("claim eligibility and overrides", func(t *testing.T) { + claimable := create("ops-claim", "", types.StatusOpen, false) + claimed, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true}) + if err != nil || !claimed.Changed || claimed.Issue.Assignee != "worker" || claimed.Issue.Status != publicops.StatusInProgress { + t.Fatalf("claim = %#v, %v", claimed, err) + } + noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true}) + if err != nil || noOp.Changed { + t.Fatalf("same actor claim = %#v, %v", noOp, err) + } + foreign := create("ops-foreign", "owner", types.StatusOpen, false) + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: foreign.ID, Claim: true}) + if !errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Fatalf("foreign claim = %v", err) + } + if err := te.store.SetConfig(ctx, "claim.pools", "crew"); err != nil { + t.Fatal(err) + } + pool := create("ops-pool", "crew", types.StatusOpen, false) + pooled, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: pool.ID, Claim: true}) + if err != nil || !pooled.Changed || pooled.Issue.Assignee != "worker" { + t.Fatalf("pool claim = %#v, %v", pooled, err) + } + poolTransfer := create("ops-pool-transfer", "crew", types.StatusInProgress, false) + transferred, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: poolTransfer.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if err != nil || !transferred.Changed || transferred.Issue.Assignee != "next" { + t.Fatalf("pool transfer = %#v, %v", transferred, err) + } + override := create("ops-override", "", types.StatusOpen, false) + result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: override.ID, Claim: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "reviewer"}, Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen}}}) + if err != nil || !result.Changed || result.Issue.Assignee != "reviewer" || result.Issue.Status != publicops.StatusOpen { + t.Fatalf("claim override = %#v, %v", result, err) + } + }) + t.Run("transfer fence, force, expected assignee, and wisp routing", func(t *testing.T) { + foreign := create("ops-transfer", "owner", types.StatusInProgress, false) + _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if !errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Fatalf("unforced transfer = %v", err) + } + forced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, ForceAssigneeTransfer: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if err != nil || !forced.Changed || forced.Issue.Assignee != "next" { + t.Fatalf("forced transfer = %#v, %v", forced, err) + } + expected := "owner" + authorized := create("ops-authorized", "owner", types.StatusInProgress, false) + result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: authorized.ID, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}) + if err != nil || !result.Changed || result.Issue.Assignee != "next" { + t.Fatalf("authorized transfer = %#v, %v", result, err) + } + wisp := create("ops-wisp", "", types.StatusOpen, true) + wispResult, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: wisp.ID, Claim: true}) + if err != nil || !wispResult.Changed || wispResult.Issue.Assignee != "worker" { + t.Fatalf("wisp claim = %#v, %v", wispResult, err) + } + }) + t.Run("invalid claim combinations fail without mutation", func(t *testing.T) { + issue := create("ops-invalid", "", types.StatusOpen, false) + expected := "" + status := publicops.StatusOpen + for _, request := range []publicops.UpdateRequest{ + {Actor: "worker", IssueID: issue.ID, Claim: true, ExpectedAssignee: &expected}, + {Actor: "worker", IssueID: issue.ID, Claim: true, ExpectedStatus: &status}, + {Actor: "worker", IssueID: issue.ID, Claim: true, ForceAssigneeTransfer: true}, + {Actor: "worker", IssueID: issue.ID, ForceAssigneeTransfer: true}, + {Actor: "worker", IssueID: issue.ID, ForceAssigneeTransfer: true, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}, + } { + _, err := operations.Update(ctx, request) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("invalid request error = %v", err) + } + } + got, err := te.store.GetIssue(ctx, issue.ID) + if err != nil || got.Assignee != "" || got.Status != types.StatusOpen { + t.Fatalf("invalid request mutated = %#v, %v", got, err) + } + }) +} + +func TestEmbeddedIssueOperationsLifecycleContractMatrix(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_lifecycle") + ctx := t.Context() + ops, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + makeIssue := func(id string, status types.Status, wisp bool) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + t.Run("close session and reclose", func(t *testing.T) { + issue := makeIssue("ops-life", types.StatusOpen, false) + result, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID, Reason: "because", Session: "session-1"}) + if err != nil || !result.Changed || result.Issue.ClosedBySession != "session-1" || result.Issue.CloseReason != "because" { + t.Fatalf("first close session=%q reason=%q changed=%t error=%v", result.Issue.ClosedBySession, result.Issue.CloseReason, result.Changed, err) + } + reclose, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID}) + if err != nil || reclose.Changed { + t.Fatalf("idempotent reclose = %#v, %v; want unchanged", reclose, err) + } + }) + t.Run("force reopen wisp", func(t *testing.T) { + parent, child := makeIssue("ops-parent", types.StatusOpen, false), makeIssue("ops-child", types.StatusOpen, false) + if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatal(err) + } + _, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID}) + if !errors.Is(err, publicops.ErrCloseOpenChildren) { + t.Fatalf("children=%v", err) + } + forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true}) + if err != nil || forced.OpenChildren != 1 { + t.Fatalf("force=%#v,%v", forced, err) + } + opened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID}) + if err != nil || !opened.Changed { + t.Fatalf("reopen=%#v,%v", opened, err) + } + wisp := makeIssue("ops-wisp", types.StatusOpen, true) + if _, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID}); err != nil { + t.Fatal(err) + } + }) +} + +func TestEmbeddedIssueOperationsLifecycleRemainingCausalCases(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_life_remaining") + ctx := t.Context() + ops, _ := embeddeddolt.NewIssueOperations(te.store) + makeIssue := func(id string, status types.Status) *types.Issue { + issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + return issue + } + t.Run("blocker refusal and force leave no partial mutation", func(t *testing.T) { + blocker, target := makeIssue("ops-blocker", types.StatusOpen), makeIssue("ops-blocked", types.StatusOpen) + if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: target.ID, DependsOnID: blocker.ID, Type: types.DepBlocks}, "seed"); err != nil { + t.Fatal(err) + } + _, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID}) + if !errors.Is(err, publicops.ErrCloseBlocked) { + t.Fatalf("blocker=%v", err) + } + got, _ := te.store.GetIssue(ctx, target.ID) + if got.Status != types.StatusOpen { + t.Fatalf("refusal mutated=%#v", got) + } + forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID, Force: true}) + if err != nil || !forced.Changed { + t.Fatalf("force=%#v,%v", forced, err) + } + }) + t.Run("reopen version before non-done noop and custom done", func(t *testing.T) { + open := makeIssue("ops-open", types.StatusOpen) + stale := open.RowVersion + 1 + _, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: open.ID, ExpectedVersion: &stale}) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("reopen version=%v", err) + } + if err := te.store.SetConfig(ctx, "status.custom", "archived:done"); err != nil { + t.Fatal(err) + } + custom := makeIssue("ops-custom", types.Status("archived")) + reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: custom.ID}) + if err != nil || !reopened.Changed || reopened.Issue.Status != types.StatusOpen { + t.Fatalf("custom=%#v,%v", reopened, err) + } + }) +} + +func embeddedIssueParentIDs(issue *types.Issue) string { + parents := make([]string, 0) + for _, dependency := range issue.Dependencies { + if dependency.Type == types.DepParentChild { + parents = append(parents, dependency.DependsOnID) + } + } + return strings.Join(parents, ",") +} + +func sameEmbeddedMetadataJSON(left, right json.RawMessage) bool { + var leftValue, rightValue any + return json.Unmarshal(left, &leftValue) == nil && json.Unmarshal(right, &rightValue) == nil && reflect.DeepEqual(leftValue, rightValue) +} + +func TestEmbeddedIssueOperationsUpdateAllScalarAndPointerFieldsReportChanged(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_scalar_changed") + ctx := t.Context() + ops, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + when := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC) + minutes, external := 15, "external" + base := func(id string) *types.Issue { + return &types.Issue{ID: id, Title: "title", Description: "description", Design: "design", AcceptanceCriteria: "criteria", Notes: "notes", SpecID: "spec", AwaitID: "await", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Assignee: "worker", Owner: "owner", ClosedBySession: "session", EstimatedMinutes: &minutes, ExternalRef: &external, DueAt: &when, DeferUntil: &when} + } + cases := []struct { + name string + patch publicops.IssuePatch + check func(*types.Issue) bool + }{ + {"title", publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "changed"}}, func(i *types.Issue) bool { return i.Title == "changed" }}, + {"description clear", publicops.IssuePatch{Description: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Description == "" }}, + {"design clear", publicops.IssuePatch{Design: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Design == "" }}, + {"acceptance criteria clear", publicops.IssuePatch{AcceptanceCriteria: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AcceptanceCriteria == "" }}, + {"notes clear", publicops.IssuePatch{Notes: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Notes == "" }}, + {"append notes", publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "later"}}, func(i *types.Issue) bool { return i.Notes == "notes\nlater" }}, + {"spec ID clear", publicops.IssuePatch{SpecID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.SpecID == "" }}, + {"await ID clear", publicops.IssuePatch{AwaitID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AwaitID == "" }}, + {"status", publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusInProgress}}, func(i *types.Issue) bool { return i.Status == publicops.StatusInProgress }}, + {"priority zero", publicops.IssuePatch{Priority: publicops.Field[int]{Set: true}}, func(i *types.Issue) bool { return i.Priority == 0 }}, + {"issue type", publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: types.TypeBug}}, func(i *types.Issue) bool { return i.IssueType == types.TypeBug }}, + {"assignee clear", publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Assignee == "" }}, + {"owner clear", publicops.IssuePatch{Owner: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Owner == "" }}, + {"closed by session clear", publicops.IssuePatch{ClosedBySession: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.ClosedBySession == "" }}, + {"estimated minutes clear", publicops.IssuePatch{EstimatedMinutes: publicops.Field[*int]{Set: true}}, func(i *types.Issue) bool { return i.EstimatedMinutes == nil }}, + {"external ref clear", publicops.IssuePatch{ExternalRef: publicops.Field[*string]{Set: true}}, func(i *types.Issue) bool { return i.ExternalRef == nil }}, + {"due at clear", publicops.IssuePatch{DueAt: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DueAt == nil }}, + {"defer until clear", publicops.IssuePatch{DeferUntil: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DeferUntil == nil }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + issue := base("ops-scalars-" + strings.ReplaceAll(tc.name, " ", "-")) + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch}) + if err != nil || !result.Changed || !tc.check(result.Issue) { + t.Fatalf("Update(%s) = %#v, %v", tc.name, result, err) + } + stored, err := te.store.GetIssue(ctx, issue.ID) + if err != nil || !tc.check(stored) { + t.Fatalf("stored %s = %#v, %v", tc.name, stored, err) + } + if tc.name != "append notes" { + noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch}) + if err != nil || noOp.Changed { + t.Fatalf("same-value %s = %#v, %v", tc.name, noOp, err) + } + after, err := te.store.GetIssue(ctx, issue.ID) + if err != nil || after.RowVersion != stored.RowVersion { + t.Fatalf("same-value %s wrote row version %d -> %d, %v", tc.name, stored.RowVersion, after.RowVersion, err) + } + } + }) + } + issue := base("ops-notes-conflict") + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + _, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Notes: publicops.Field[string]{Set: true, Value: "replace"}, AppendNotes: publicops.Field[string]{Set: true, Value: "append"}}}) + if err == nil { + t.Fatal("Notes plus AppendNotes succeeded") + } + stored, err := te.store.GetIssue(ctx, issue.ID) + if err != nil || stored.Title != "title" || stored.Notes != "notes" { + t.Fatalf("notes conflict persisted %#v, %v", stored, err) + } +} + +func TestEmbeddedIssueOperationsPersistenceRollbackWispAndDetachedResults(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_persistence_aggregate") + ctx := t.Context() + ops, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + for _, transition := range []struct{ from, to publicops.PersistenceMode }{{publicops.PersistenceModePersistent, publicops.PersistenceModeEphemeral}, {publicops.PersistenceModeEphemeral, publicops.PersistenceModeNoHistory}, {publicops.PersistenceModeNoHistory, publicops.PersistenceModePersistent}} { + id := "ops-persistence-" + string(transition.from) + "-" + string(transition.to) + if err := te.store.CreateIssue(ctx, &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: transition.from == publicops.PersistenceModeEphemeral, NoHistory: transition.from == publicops.PersistenceModeNoHistory}, "seed"); err != nil { + t.Fatal(err) + } + result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}}) + if err != nil || !result.Changed || result.Issue.Ephemeral != (transition.to == publicops.PersistenceModeEphemeral) || result.Issue.NoHistory != (transition.to == publicops.PersistenceModeNoHistory) { + t.Fatalf("transition %s->%s = %#v, %v", transition.from, transition.to, result, err) + } + noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}}) + if err != nil || noOp.Changed { + t.Fatalf("same persistence %s = %#v, %v", transition.to, noOp, err) + } + } + unversioned := &types.Issue{ID: "ops-persistence-rollback", Title: "original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`)} + if err := te.store.CreateIssue(ctx, unversioned, "seed"); err != nil { + t.Fatal(err) + } + _, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: unversioned.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Labels: publicops.LabelPatch{Add: []string{"must-rollback"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"must_rollback": json.RawMessage(`true`)}}, Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}}}) + if err == nil { + t.Fatal("unversioned demotion succeeded") + } + stored, err := te.store.GetIssue(ctx, unversioned.ID) + if err != nil || stored.Title != "original" || strings.Join(stored.Labels, ",") != "keep" || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"keep":true}`)) || stored.Ephemeral || stored.NoHistory { + t.Fatalf("failed demotion left state %#v, %v", stored, err) + } + external := "external" + wisp := &types.Issue{ID: "ops-wisp-detached", Title: "wisp", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`), ExternalRef: &external} + if err := te.store.CreateIssue(ctx, wisp, "seed"); err != nil { + t.Fatal(err) + } + updated, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: wisp.ID, Patch: publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "after"}, Labels: publicops.LabelPatch{Add: []string{"added"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"added": json.RawMessage(`true`)}}}}) + if err != nil || !updated.Changed || updated.Issue.Notes != "before\nafter" || strings.Join(updated.Issue.Labels, ",") != "added,keep" { + t.Fatalf("wisp update = %#v, %v", updated, err) + } + updated.Issue.Labels[0], updated.Issue.Metadata[2], *updated.Issue.ExternalRef = "corrupt", 'X', "corrupt" + stored, err = te.store.GetIssue(ctx, wisp.ID) + if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) || stored.ExternalRef == nil || *stored.ExternalRef != "external" { + t.Fatalf("update result aliases store %#v, %v", stored, err) + } + closed, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID}) + if err != nil || !closed.Changed || closed.Issue.Status != publicops.StatusClosed { + t.Fatalf("wisp close = %#v, %v", closed, err) + } + closed.Issue.Metadata[2] = 'X' + reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: wisp.ID}) + if err != nil || !reopened.Changed || reopened.Issue.Status != publicops.StatusOpen { + t.Fatalf("wisp reopen = %#v, %v", reopened, err) + } + reopened.Issue.Labels[0] = "corrupt" + stored, err = te.store.GetIssue(ctx, wisp.ID) + if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) { + t.Fatalf("lifecycle result aliases store %#v, %v", stored, err) + } +} diff --git a/internal/storage/embeddeddolt/issue_operations_contract_test.go b/internal/storage/embeddeddolt/issue_operations_contract_test.go new file mode 100644 index 000000000..f218a4d95 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations_contract_test.go @@ -0,0 +1,50 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/storage/conformance" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" +) + +func TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "infra") + ctx := t.Context() + conformance.RunIssueOperationsCreateRoutesInfraTypesToWisps(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "infra")) +} + +func TestEmbeddedIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "skipdep") + ctx := t.Context() + conformance.RunIssueOperationsCreateRejectsMissingDependencyTargets(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "skipdep")) +} + +func TestEmbeddedIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "metaevent") + ctx := t.Context() + conformance.RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "metaevent")) +} + +func newEmbeddedIssueOperationsFixture(t *testing.T, ctx context.Context, te *testEnv, prefix string) conformance.IssueOperationsStagingFixture { + t.Helper() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + return conformance.IssueOperationsStagingFixture{ + IssuePrefix: prefix, + Operations: operations, + CreateIssue: te.store.CreateIssue, + SetConfig: te.store.SetConfig, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + te.queryScalar(t, ctx, query, args, dest...) + return nil + }, + } +} diff --git a/internal/storage/embeddeddolt/issue_operations_persistence_test.go b/internal/storage/embeddeddolt/issue_operations_persistence_test.go new file mode 100644 index 000000000..e74792812 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations_persistence_test.go @@ -0,0 +1,45 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "path/filepath" + "testing" + + "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" +) + +func TestEmbeddedMoveIssuePersistenceEphemeralNoHistorySmoke(t *testing.T) { + ctx := context.Background() + store, err := Open(ctx, filepath.Join(t.TempDir(), ".beads"), "persist", "main") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + if err := store.SetConfig(ctx, "issue_prefix", "persist"); err != nil { + t.Fatal(err) + } + issue := &types.Issue{ID: "persist-embedded", Title: "embedded", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + if err := store.runTransaction(ctx, "persistence", func(tx *embeddedTransaction) error { + current, err := issueops.GetIssueInTx(ctx, tx.tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx.tx, current, types.PersistenceModeNoHistory) + return err + }); err != nil { + t.Fatal(err) + } + got, err := store.GetIssue(ctx, issue.ID) + if err != nil { + t.Fatal(err) + } + if got.Ephemeral || !got.NoHistory { + t.Fatalf("persistence = (%t,%t), want (false,true)", got.Ephemeral, got.NoHistory) + } +} diff --git a/internal/storage/embeddeddolt/issue_operations_staging_test.go b/internal/storage/embeddeddolt/issue_operations_staging_test.go new file mode 100644 index 000000000..c1c1f0850 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations_staging_test.go @@ -0,0 +1,287 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "encoding/json" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage/conformance" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +func TestEmbeddedIssueOperationsUpdateClaimPatchAppliesAfterClaim(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_staging_claim_patch") + ctx := t.Context() + issue := &types.Issue{ID: "ops-staging-claim-patch", Title: "claim patch", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + + result, err := operations.Update(ctx, publicops.UpdateRequest{ + Actor: "worker", + IssueID: issue.ID, + Claim: true, + Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen}, + Assignee: publicops.Field[string]{Set: true}, + }, + }) + if err != nil { + t.Fatal(err) + } + if !result.Changed || result.Issue.Status != publicops.StatusOpen || result.Issue.Assignee != "" { + t.Fatalf("claim then patch = %#v, want open and unassigned", result) + } +} + +func TestEmbeddedIssueOperationsCreateEmptyIDPreservesParentAndReverseDependencies(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_staging_create_reverse") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + parent := &types.Issue{ID: "ops-staging-embedded-parent", Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic} + durableSource := &types.Issue{ID: "test-staging-embedded-durable", Title: "durable source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + wispSource := &types.Issue{ID: "test-staging-embedded-wisp", Title: "wisp source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true} + for _, issue := range []*types.Issue{parent, durableSource, wispSource} { + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + } + + child, err := operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + ParentID: parent.ID, + }) + if err != nil { + t.Fatal(err) + } + if child.Issue.ID != parent.ID+".1" || len(child.Issue.Dependencies) != 1 || child.Issue.Dependencies[0].IssueID != child.Issue.ID || child.Issue.Dependencies[0].DependsOnID != parent.ID || child.Issue.Dependencies[0].Type != types.DepParentChild || child.Issue.Dependencies[0].Metadata != "{}" { + t.Fatalf("child aggregate = %#v", child.Issue) + } + + generatedWisp, err := operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: "generated wisp", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, + Dependencies: []publicops.CreateDependency{{TargetID: durableSource.ID, Type: types.DepRelatesTo, Reverse: true, Metadata: `{"direction":"durable"}`, ThreadID: "durable-thread"}}, + }) + if err != nil { + t.Fatal(err) + } + durableDependencies, err := te.store.GetDependencyRecords(ctx, durableSource.ID) + if err != nil || len(durableDependencies) != 1 { + t.Fatalf("durable reverse dependency = %#v, %v", durableDependencies, err) + } + durableDependency := durableDependencies[0] + if durableDependency.IssueID != durableSource.ID || durableDependency.DependsOnID != generatedWisp.Issue.ID || durableDependency.Type != types.DepRelatesTo || !sameEmbeddedMetadataJSON(json.RawMessage(durableDependency.Metadata), json.RawMessage(`{"direction":"durable"}`)) || durableDependency.ThreadID != "durable-thread" { + t.Fatalf("durable reverse dependency = %+v", durableDependency) + } + + generatedDurable, err := operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: "generated durable", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + Dependencies: []publicops.CreateDependency{{TargetID: wispSource.ID, Type: types.DepRelatesTo, Reverse: true, Metadata: `{"direction":"wisp"}`, ThreadID: "wisp-thread"}}, + }) + if err != nil { + t.Fatal(err) + } + wispDependencies, err := te.store.GetDependencyRecords(ctx, wispSource.ID) + if err != nil || len(wispDependencies) != 1 { + t.Fatalf("wisp reverse dependency = %#v, %v", wispDependencies, err) + } + wispDependency := wispDependencies[0] + if wispDependency.IssueID != wispSource.ID || wispDependency.DependsOnID != generatedDurable.Issue.ID || wispDependency.Type != types.DepRelatesTo || !sameEmbeddedMetadataJSON(json.RawMessage(wispDependency.Metadata), json.RawMessage(`{"direction":"wisp"}`)) || wispDependency.ThreadID != "wisp-thread" { + t.Fatalf("wisp reverse dependency = %+v", wispDependency) + } +} + +func TestEmbeddedIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + + conformance.RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t, ctx, conformance.IssueOperationsStagingFixture{ + IssuePrefix: "ops", + Operations: operations, + CreateIssue: te.store.CreateIssue, + Commit: te.store.Commit, + Exec: func(ctx context.Context, query string, args ...any) error { + te.exec(t, ctx, query, args...) + return nil + }, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + te.queryScalar(t, ctx, query, args, dest...) + return nil + }, + }) +} + +func TestEmbeddedIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops") + ctx := t.Context() + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + + conformance.RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t, ctx, conformance.IssueOperationsStagingFixture{ + IssuePrefix: "ops", + Operations: operations, + CreateIssue: te.store.CreateIssue, + AddDependency: te.store.AddDependency, + GetReadyWork: te.store.GetReadyWork, + Commit: te.store.Commit, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + te.queryScalar(t, ctx, query, args, dest...) + return nil + }, + }) +} + +func TestEmbeddedIssueOperationsUpdateInvalidIssueTypePreservesValidationSentinel(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_staging_invalid_type") + ctx := t.Context() + issue := &types.Issue{ID: "ops-staging-invalid-type", Title: "invalid type", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: "not-a-type"}}}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("invalid issue type error = %v, want ErrValidation", err) + } +} + +func TestEmbeddedIssueOperationsUpdateNotesConflictPreservesValidationSentinel(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_staging_notes_conflict") + ctx := t.Context() + issue := &types.Issue{ID: "ops-staging-notes-conflict", Title: "notes conflict", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", + IssueID: issue.ID, + Patch: publicops.IssuePatch{ + Notes: publicops.Field[string]{Set: true, Value: "replacement"}, + AppendNotes: publicops.Field[string]{Set: true, Value: "append"}, + }, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("notes conflict error = %v, want ErrValidation", err) + } + stored, err := te.store.GetIssue(ctx, issue.ID) + if err != nil || stored.Notes != "before" { + t.Fatalf("notes conflict persisted notes = %q, %v; want before", stored.Notes, err) + } +} + +func TestEmbeddedIssueOperationsUpdateParentStagesBlockedStateAndRollsBackFailure(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_staging_parent_state") + ctx := t.Context() + issues := []*types.Issue{ + {ID: "ops-staging-parent-blocker", Title: "blocker", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + {ID: "ops-staging-parent-clean", Title: "clean parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic}, + {ID: "ops-staging-parent-blocked", Title: "blocked parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic}, + {ID: "ops-staging-parent-child", Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + {ID: "ops-staging-parent-rollback", Title: "rollback child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + } + for _, issue := range issues { + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatal(err) + } + } + for _, dependency := range []*types.Dependency{ + {IssueID: "ops-staging-parent-blocked", DependsOnID: "ops-staging-parent-blocker", Type: types.DepBlocks}, + {IssueID: "ops-staging-parent-child", DependsOnID: "ops-staging-parent-clean", Type: types.DepParentChild}, + {IssueID: "ops-staging-parent-rollback", DependsOnID: "ops-staging-parent-blocked", Type: types.DepParentChild}, + } { + if err := te.store.AddDependency(ctx, dependency, "seed"); err != nil { + t.Fatal(err) + } + } + if err := te.store.Commit(ctx, "seed blocked parent state"); err != nil { + t.Fatal(err) + } + operations, err := embeddeddolt.NewIssueOperations(te.store) + if err != nil { + t.Fatal(err) + } + + result, err := operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", + IssueID: "ops-staging-parent-child", + Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-blocked"}}, + }) + if err != nil || !result.Changed || embeddedIssueParentIDs(result.Issue) != "ops-staging-parent-blocked" { + t.Fatalf("blocked parent replacement = %#v, %v", result, err) + } + var workingBlocked, headBlocked bool + te.queryScalar(t, ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{"ops-staging-parent-child"}, &workingBlocked) + te.queryScalar(t, ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{"ops-staging-parent-child"}, &headBlocked) + if !workingBlocked || !headBlocked { + t.Fatalf("blocked child state = working %t, HEAD %t; want both true", workingBlocked, headBlocked) + } + + _, err = operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", + IssueID: "ops-staging-parent-rollback", + Patch: publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "must rollback"}, + ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-missing"}, + }, + }) + if err == nil { + t.Fatal("missing parent replacement succeeded") + } + rolledBack, err := te.store.GetIssue(ctx, "ops-staging-parent-rollback") + if err != nil { + t.Fatal(err) + } + dependencies, err := te.store.GetDependencyRecords(ctx, rolledBack.ID) + if err != nil { + t.Fatal(err) + } + if rolledBack.Title != "rollback child" || len(dependencies) != 1 || dependencies[0].IssueID != rolledBack.ID || dependencies[0].DependsOnID != "ops-staging-parent-blocked" || dependencies[0].Type != types.DepParentChild { + t.Fatalf("failed parent replacement persisted issue = %#v, dependencies %#v", rolledBack, dependencies) + } + var rollbackWorkingTitle, rollbackHeadTitle string + te.queryScalar(t, ctx, "SELECT title, is_blocked FROM issues WHERE id = ?", []any{rolledBack.ID}, &rollbackWorkingTitle, &workingBlocked) + te.queryScalar(t, ctx, "SELECT title, is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{rolledBack.ID}, &rollbackHeadTitle, &headBlocked) + if rollbackWorkingTitle != "rollback child" || rollbackHeadTitle != "rollback child" || !workingBlocked || !headBlocked { + t.Fatalf("failed parent replacement state = working (%q, %t), HEAD (%q, %t)", rollbackWorkingTitle, workingBlocked, rollbackHeadTitle, headBlocked) + } +} diff --git a/internal/storage/embeddeddolt/issue_operations_tx.go b/internal/storage/embeddeddolt/issue_operations_tx.go new file mode 100644 index 000000000..9134d46a6 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations_tx.go @@ -0,0 +1,29 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" +) + +func (s *EmbeddedDoltStore) runIssueOperationTx(ctx context.Context, commitMsg string, fn func(*sql.Tx) (storageissueops.ChangedTables, error)) error { + // An empty message is runTransaction's existing "write, but do not version + // commit" signal — the same one CLI batch mode already uses for its + // RunInTransaction writes. + if storageissueops.VersionCommitDeferred(ctx) { + commitMsg = "" + } + return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error { + tables, err := fn(tx.tx) + if err != nil { + return err + } + for table := range tables { + tx.dirty.MarkDirty(table) + } + return nil + }) +} diff --git a/internal/storage/embeddeddolt/issue_operations_validation_test.go b/internal/storage/embeddeddolt/issue_operations_validation_test.go new file mode 100644 index 000000000..33e6caadb --- /dev/null +++ b/internal/storage/embeddeddolt/issue_operations_validation_test.go @@ -0,0 +1,61 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "encoding/json" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestEmbeddedIssueOperationsRejectsInvalidUpdatesWithoutMutation pins the +// shared update validation on this backend's own lifecycle, so a request the +// unit-of-work backend refuses is refused here too — and refused before any +// field in the same patch reaches the row. +func TestEmbeddedIssueOperationsRejectsInvalidUpdatesWithoutMutation(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "ops_validation") + ctx := t.Context() + operations, err := te.store.IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle: %v", err) + } + issue := &types.Issue{ID: "ops_validation-1", Title: "original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"yes"}`)} + if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed: %v", err) + } + + mutation := publicops.Field[string]{Set: true, Value: "mutated"} + for _, tc := range []struct { + name string + patch publicops.IssuePatch + }{ + {"priority above range", publicops.IssuePatch{Title: mutation, Priority: publicops.Field[int]{Set: true, Value: 9}}}, + {"metadata set key with unsafe characters", publicops.IssuePatch{Title: mutation, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"bad-key": json.RawMessage(`"value"`)}}}}, + } { + t.Run(tc.name, func(t *testing.T) { + if _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch}); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("Update error = %v, want ErrValidation", err) + } + stored, err := te.store.GetIssue(ctx, issue.ID) + if err != nil { + t.Fatalf("GetIssue: %v", err) + } + if stored.Title != "original" || stored.Priority != 2 { + t.Fatalf("rejected update mutated the row: title %q, priority %d", stored.Title, stored.Priority) + } + metadata := map[string]json.RawMessage{} + if len(stored.Metadata) > 0 { + if err := json.Unmarshal(stored.Metadata, &metadata); err != nil { + t.Fatalf("unmarshal stored metadata %s: %v", stored.Metadata, err) + } + } + if _, ok := metadata["bad-key"]; ok { + t.Fatalf("rejected update wrote metadata: %s", stored.Metadata) + } + }) + } +} diff --git a/internal/storage/embeddeddolt/issues.go b/internal/storage/embeddeddolt/issues.go index 30bb2b8ef..7e1140204 100644 --- a/internal/storage/embeddeddolt/issues.go +++ b/internal/storage/embeddeddolt/issues.go @@ -137,23 +137,13 @@ func (s *EmbeddedDoltStore) ReclaimExpiredLeases(ctx context.Context, olderThan return reclaimed, err } -// ReopenIssue reopens a closed issue, setting status to open and clearing -// closed_at and defer_until. If reason is non-empty, it is recorded as a comment. -// Wraps UpdateIssue; EmbeddedDolt auto-commits the transaction. +// ReopenIssue reopens a done-category issue atomically. EmbeddedDolt commits +// the issue, event, comment, lease, and dependency changes together. func (s *EmbeddedDoltStore) ReopenIssue(ctx context.Context, id string, reason string, actor string) error { - updates := map[string]interface{}{ - "status": string(types.StatusOpen), - "defer_until": nil, - } - if err := s.UpdateIssue(ctx, id, updates, actor); err != nil { + return s.withConn(ctx, true, func(tx *sql.Tx) error { + _, err := issueops.ReopenIssueInTx(ctx, tx, id, reason, actor) return err - } - if reason != "" { - if err := s.AddComment(ctx, id, actor, reason); err != nil { - return fmt.Errorf("reopen comment: %w", err) - } - } - return nil + }) } // UpdateIssueType changes the issue_type field of an issue. @@ -185,7 +175,7 @@ func (s *EmbeddedDoltStore) CloseIssueChecked(ctx context.Context, id string, ac if err != nil { return err } - result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed} + result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed, OpenChildren: res.OpenChildren} return nil }) if err != nil { diff --git a/internal/storage/embeddeddolt/reopen_category_test.go b/internal/storage/embeddeddolt/reopen_category_test.go new file mode 100644 index 000000000..8b5de9a56 --- /dev/null +++ b/internal/storage/embeddeddolt/reopen_category_test.go @@ -0,0 +1,164 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +func TestEmbeddedReopenIssueCategorySemantics(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "rct") + ctx := t.Context() + + create := func(id string, ephemeral bool) { + t.Helper() + if err := te.store.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral, + }, "tester"); err != nil { + t.Fatalf("CreateIssue(%s): %v", id, err) + } + } + setStatus := func(table, id, status string) { + t.Helper() + te.exec(t, ctx, ` + UPDATE `+table+` + SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?, + defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY) + WHERE id = ? + `, status, "completed", "session-1", id) + } + assertReopened := func(id string) { + t.Helper() + issue, err := te.store.GetIssue(ctx, id) + if err != nil { + t.Fatalf("GetIssue(%s): %v", id, err) + } + if issue.Status != types.StatusOpen || issue.ClosedAt != nil || issue.CloseReason != "" || issue.ClosedBySession != "" || issue.DeferUntil != nil { + t.Fatalf("reopened issue = %+v", issue) + } + } + assertReopenEvents := func(id string) { + t.Helper() + events, err := te.store.GetEvents(ctx, id, 0) + if err != nil { + t.Fatalf("GetEvents(%s): %v", id, err) + } + var reopened, commented, statusChanged int + for _, event := range events { + switch event.EventType { + case types.EventReopened: + reopened++ + case types.EventCommented: + commented++ + case types.EventStatusChanged: + statusChanged++ + } + } + if reopened != 1 || commented != 1 || statusChanged != 0 { + t.Fatalf( + "reopen events for %s = reopened:%d commented:%d status_changed:%d, want 1, 1, 0", + id, reopened, commented, statusChanged, + ) + } + } + + te.exec(t, ctx, "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", "archived", string(types.CategoryDone)) + create("rct-permanent", false) + create("rct-wisp", true) + setStatus("issues", "rct-permanent", "archived") + setStatus("wisps", "rct-wisp", "archived") + + for _, id := range []string{"rct-permanent", "rct-wisp"} { + if err := te.store.ReopenIssue(ctx, id, "needs work", "tester"); err != nil { + t.Fatalf("ReopenIssue(%s): %v", id, err) + } + assertReopened(id) + assertReopenEvents(id) + } + + for _, status := range []struct { + id string + name string + category types.StatusCategory + }{ + {id: "rct-active", name: "triaged", category: types.CategoryActive}, + {id: "rct-wip", name: "testing", category: types.CategoryWIP}, + {id: "rct-frozen", name: "on-ice", category: types.CategoryFrozen}, + {id: "rct-unknown", name: "unknown-status", category: types.CategoryUnspecified}, + } { + if status.category != types.CategoryUnspecified { + te.exec(t, ctx, "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", status.name, string(status.category)) + } + create(status.id, false) + setStatus("issues", status.id, status.name) + if err := te.store.ReopenIssue(ctx, status.id, "ignored", "tester"); err != nil { + t.Fatalf("ReopenIssue(%s): %v", status.name, err) + } + issue, err := te.store.GetIssue(ctx, status.id) + if err != nil { + t.Fatalf("GetIssue(%s): %v", status.name, err) + } + if issue.Status != types.Status(status.name) || issue.CloseReason != "completed" { + t.Fatalf("non-done issue %s changed: %+v", status.name, issue) + } + } + + create("rct-open", false) + beforeEvents, err := te.store.GetEvents(ctx, "rct-open", 0) + if err != nil { + t.Fatalf("GetEvents(open) before reopen: %v", err) + } + if err := te.store.ReopenIssue(ctx, "rct-open", "ignored", "tester"); err != nil { + t.Fatalf("ReopenIssue(open): %v", err) + } + afterEvents, err := te.store.GetEvents(ctx, "rct-open", 0) + if err != nil { + t.Fatalf("GetEvents(open) after reopen: %v", err) + } + if len(afterEvents) != len(beforeEvents) { + t.Fatalf("literal-open no-op events = %+v, want no new events", afterEvents) + } + + err = te.store.ReopenIssue(ctx, "rct-missing", "", "tester") + if !errors.Is(err, storage.ErrNotFound) { + t.Fatalf("missing reopen err = %v, want ErrNotFound", err) + } +} + +func TestEmbeddedReopenCustomDoneFallsBackWhenNormalizedTableMissing(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "rcf") + ctx := t.Context() + const id = "rcf-legacy-done" + + if err := te.store.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "tester"); err != nil { + t.Fatalf("CreateIssue: %v", err) + } + if err := te.store.SetConfig(ctx, "status.custom", "archived:done"); err != nil { + t.Fatalf("SetConfig(status.custom): %v", err) + } + te.exec(t, ctx, ` + UPDATE issues + SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ? + WHERE id = ? + `, "archived", "completed", id) + te.exec(t, ctx, "DROP TABLE custom_statuses") + + if err := te.store.ReopenIssue(ctx, id, "", "tester"); err != nil { + t.Fatalf("ReopenIssue: %v", err) + } + issue, err := te.store.GetIssue(ctx, id) + if err != nil { + t.Fatalf("GetIssue: %v", err) + } + if issue.Status != types.StatusOpen || issue.ClosedAt != nil || issue.CloseReason != "" { + t.Fatalf("reopened issue = %+v", issue) + } +} diff --git a/internal/storage/embeddeddolt/transaction.go b/internal/storage/embeddeddolt/transaction.go index f3e7b1016..70fdf0fb2 100644 --- a/internal/storage/embeddeddolt/transaction.go +++ b/internal/storage/embeddeddolt/transaction.go @@ -18,6 +18,16 @@ import ( // After the SQL transaction commits, dirty tables are selectively staged // and a Dolt version commit is created with the given message. func (s *EmbeddedDoltStore) RunInTransaction(ctx context.Context, commitMsg string, fn func(tx storage.Transaction) error) error { + return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error { return fn(tx) }) +} + +// RunInIssueLifecycleTransaction keeps lifecycle work on the embedded store's +// one transaction and stages only durable rows changed by that work. +func (s *EmbeddedDoltStore) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx storage.IssueLifecycleTransaction) error) error { + return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error { return fn(tx) }) +} + +func (s *EmbeddedDoltStore) runTransaction(ctx context.Context, commitMsg string, fn func(tx *embeddedTransaction) error) error { var tracker versioncontrolops.DirtyTableTracker if err := s.withConn(ctx, true, func(tx *sql.Tx) error { @@ -70,17 +80,49 @@ func (t *embeddedTransaction) CreateIssues(ctx context.Context, issues []*types. } func (t *embeddedTransaction) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error { - t.dirty.MarkDirty("issues") - t.dirty.MarkDirty("events") - _, err := issueops.UpdateIssueInTx(ctx, t.tx, id, updates, actor) - return err + issueTable, _, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, id)) + result, err := issueops.UpdateIssueInTx(ctx, t.tx, id, updates, actor) + if err != nil { + return err + } + if !result.Changed { + return nil + } + t.dirty.MarkDirty(issueTable) + t.dirty.MarkDirty(eventTable) + return nil } func (t *embeddedTransaction) CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error { - t.dirty.MarkDirty("issues") - t.dirty.MarkDirty("events") - _, err := issueops.CloseIssueInTx(ctx, t.tx, id, reason, actor, session) - return err + issueTable, _, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, id)) + result, err := issueops.CloseIssueInTx(ctx, t.tx, id, reason, actor, session) + if err != nil || result.AlreadyClosed { + return err + } + t.dirty.MarkDirty(issueTable) + t.dirty.MarkDirty(eventTable) + if result.IssueRowsChanged { + t.dirty.MarkDirty("issues") + } + return nil +} + +// ReopenIssueWithResult lets transaction-scoped callers preserve lifecycle +// semantics when an update crosses the done boundary. +func (t *embeddedTransaction) ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) { + issueTable, _, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, id)) + result, err := issueops.ReopenIssueInTx(ctx, t.tx, id, reason, actor) + if err != nil { + return false, err + } + if result.Changed { + t.dirty.MarkDirty(issueTable) + t.dirty.MarkDirty(eventTable) + if result.IssueRowsChanged { + t.dirty.MarkDirty("issues") + } + } + return result.Changed, nil } func (t *embeddedTransaction) DeleteIssue(ctx context.Context, id string) error { @@ -173,13 +215,23 @@ func (t *embeddedTransaction) GetDependencyRecords(ctx context.Context, issueID } func (t *embeddedTransaction) AddLabel(ctx context.Context, issueID, label, actor string) error { - t.dirty.MarkDirty("labels") - return issueops.AddLabelInTx(ctx, t.tx, "", "", issueID, label, actor) + _, labelTable, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, issueID)) + if err := issueops.AddLabelInTx(ctx, t.tx, labelTable, eventTable, issueID, label, actor); err != nil { + return err + } + t.dirty.MarkDirty(labelTable) + t.dirty.MarkDirty(eventTable) + return nil } func (t *embeddedTransaction) RemoveLabel(ctx context.Context, issueID, label, actor string) error { - t.dirty.MarkDirty("labels") - return issueops.RemoveLabelInTx(ctx, t.tx, "", "", issueID, label, actor) + _, labelTable, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, issueID)) + if err := issueops.RemoveLabelInTx(ctx, t.tx, labelTable, eventTable, issueID, label, actor); err != nil { + return err + } + t.dirty.MarkDirty(labelTable) + t.dirty.MarkDirty(eventTable) + return nil } func (t *embeddedTransaction) GetLabels(ctx context.Context, issueID string) ([]string, error) { diff --git a/internal/storage/embeddeddolt/transaction_wisp_lifecycle_persistence_test.go b/internal/storage/embeddeddolt/transaction_wisp_lifecycle_persistence_test.go new file mode 100644 index 000000000..1d3b37f0a --- /dev/null +++ b/internal/storage/embeddeddolt/transaction_wisp_lifecycle_persistence_test.go @@ -0,0 +1,387 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" +) + +// TestEmbeddedTransactionWispLifecyclePersistsDurableDependent verifies that +// a transactional wisp lifecycle transition publishes the durable dependent's +// recomputed blocked state into the versioned history. +func TestEmbeddedTransactionWispLifecyclePersistsDurableDependent(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + + for _, test := range []struct { + name string + wispID string + dependerID string + wantBlocked bool + run func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error + }{ + { + name: "close", + wispID: "embedded-tx-wisp-close", + dependerID: "embedded-tx-close-depender", + run: func(_ *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error { + return store.RunInIssueLifecycleTransaction(ctx, "test: close wisp blocker", func(tx storage.IssueLifecycleTransaction) error { + return tx.CloseIssue(ctx, wispID, "done", "tester", "session") + }) + }, + }, + { + name: "reopen", + wispID: "embedded-tx-wisp-reopen", + dependerID: "embedded-tx-reopen-depender", + wantBlocked: true, + run: func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error { + return store.RunInIssueLifecycleTransaction(ctx, "test: reopen wisp blocker", func(tx storage.IssueLifecycleTransaction) error { + changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester") + if err != nil { + return err + } + if !changed { + t.Fatal("transactional reopen reported Changed=false") + } + return nil + }) + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + te := newTestEnv(t, "txwisp") + seedEmbeddedTransactionWispBlocker(t, te, ctx, test.dependerID, test.wispID) + if err := te.store.Commit(ctx, "test: seed wisp blocker"); err != nil { + t.Fatalf("Commit seed: %v", err) + } + if test.name == "reopen" { + if err := te.store.CloseIssue(ctx, test.wispID, "done", "tester", "session"); err != nil { + t.Fatalf("seed CloseIssue: %v", err) + } + if err := te.store.Commit(ctx, "test: seed closed wisp blocker"); err != nil { + t.Fatalf("Commit closed seed: %v", err) + } + } + before, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit before: %v", err) + } + + if err := test.run(t, te.store, ctx, test.wispID); err != nil { + t.Fatalf("RunInTransaction: %v", err) + } + + after, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit after: %v", err) + } + if after == before { + t.Errorf("transactional wisp lifecycle did not publish durable dependent; HEAD remained %s", before) + } + + var working, committed bool + te.queryScalar(t, ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{test.dependerID}, &working) + te.queryScalar(t, ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{test.dependerID}, &committed) + if working != test.wantBlocked { + t.Errorf("working durable depender is_blocked = %t, want %t", working, test.wantBlocked) + } + if committed != test.wantBlocked { + t.Errorf("committed durable depender is_blocked = %t, want %t", committed, test.wantBlocked) + } + }) + } +} + +func TestEmbeddedTransactionStandaloneWispLifecyclePersistsWithoutDoltCommit(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + + for _, test := range []struct { + name string + wispID string + wantStatus types.Status + run func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error + }{ + { + name: "close", + wispID: "embedded-tx-standalone-wisp-close", + wantStatus: types.StatusClosed, + run: func(_ *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error { + return store.RunInIssueLifecycleTransaction(ctx, "test: close standalone wisp", func(tx storage.IssueLifecycleTransaction) error { + return tx.CloseIssue(ctx, wispID, "done", "tester", "session") + }) + }, + }, + { + name: "reopen", + wispID: "embedded-tx-standalone-wisp-reopen", + wantStatus: types.StatusOpen, + run: func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error { + if err := store.CloseIssue(ctx, wispID, "done", "tester", "session"); err != nil { + return err + } + return store.RunInIssueLifecycleTransaction(ctx, "test: reopen standalone wisp", func(tx storage.IssueLifecycleTransaction) error { + changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester") + if err != nil { + return err + } + if !changed { + t.Fatal("transactional reopen reported Changed=false") + } + return nil + }) + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + te := newTestEnv(t, "txstandalone") + if err := te.store.CreateIssue(ctx, &types.Issue{ID: test.wispID, Title: test.wispID, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, "tester"); err != nil { + t.Fatalf("CreateIssue: %v", err) + } + before, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit before: %v", err) + } + + if err := test.run(t, te.store, ctx, test.wispID); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction: %v", err) + } + after, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit after: %v", err) + } + if after != before { + t.Fatalf("standalone wisp lifecycle changed HEAD from %s to %s", before, after) + } + issue, err := te.store.GetIssue(ctx, test.wispID) + if err != nil { + t.Fatalf("GetIssue: %v", err) + } + if issue.Status != test.wantStatus { + t.Errorf("wisp status = %q, want %q", issue.Status, test.wantStatus) + } + }) + } +} + +func TestEmbeddedTransactionSameStatusDoesNotPublishUnrelatedDurableChanges(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + te := newTestEnv(t, "txsamestatus") + const ( + targetID = "embedded-tx-same-status-target" + dirtyID = "embedded-tx-same-status-dirty" + ) + for _, issue := range []*types.Issue{ + {ID: targetID, Title: "target baseline", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + {ID: dirtyID, Title: "dirty baseline", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + } { + if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatalf("CreateIssue(%s): %v", issue.ID, err) + } + } + if err := te.store.Commit(ctx, "test: seed same-status baseline"); err != nil { + t.Fatalf("Commit baseline: %v", err) + } + before, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit before: %v", err) + } + + te.exec(t, ctx, "UPDATE issues SET title = ? WHERE id = ?", "working-only title", dirtyID) + te.exec(t, ctx, + "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?", + "working-only event", dirtyID, string(types.EventCreated)) + + if err := te.store.RunInIssueLifecycleTransaction(ctx, "test: same-status update", func(tx storage.IssueLifecycleTransaction) error { + return tx.UpdateIssue(ctx, targetID, map[string]interface{}{"status": types.StatusOpen}, "tester") + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction: %v", err) + } + after, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit after: %v", err) + } + if after != before { + t.Errorf("same-status transaction changed HEAD from %s to %s", before, after) + } + + var workingTitle, headTitle string + te.queryScalar(t, ctx, "SELECT title FROM issues WHERE id = ?", []any{dirtyID}, &workingTitle) + te.queryScalar(t, ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{dirtyID}, &headTitle) + if workingTitle != "working-only title" || headTitle != "dirty baseline" { + t.Errorf("unrelated issue titles = working:%q HEAD:%q", workingTitle, headTitle) + } + // events is dolt_ignored since migration 0062 (bd-red8u). On the + // production-shaped database this harness builds, the table is absent from + // committed history entirely, so an AS OF 'HEAD' probe errors rather than + // proving anything; the plane contract itself is pinned by + // TestEmbeddedMigration0062FlipsEventsToIgnoredPlane. "Nothing was + // published" is already carried by the HEAD-unchanged assertion above, so + // what is left is that the unrelated audit edit survives in the working set. + var workingEvent int + te.queryScalar(t, ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?", + []any{dirtyID, string(types.EventCreated), "working-only event"}, &workingEvent) + if workingEvent != 1 { + t.Errorf("unrelated working-set event edit count = %d, want 1", workingEvent) + } +} + +func TestEmbeddedTransactionStandaloneWispMutationDoesNotPublishUnrelatedDurableChanges(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + te := newTestEnv(t, "txwispisolation") + const ( + durableID = "tx-wisp-isolation-durable" + wispID = "tx-wisp-isolation-wisp" + baselineLabel = "durable-baseline" + workingLabel = "durable-working-only" + removeWispLabel = "remove-from-wisp" + addWispLabel = "add-to-wisp" + ) + + if err := te.store.CreateIssue(ctx, &types.Issue{ + ID: durableID, Title: "durable baseline", Status: types.StatusOpen, + Priority: 2, IssueType: types.TypeTask, + }, "tester"); err != nil { + t.Fatalf("CreateIssue durable: %v", err) + } + if err := te.store.AddLabel(ctx, durableID, baselineLabel, "tester"); err != nil { + t.Fatalf("AddLabel durable baseline: %v", err) + } + if err := te.store.CreateIssue(ctx, &types.Issue{ + ID: wispID, Title: "wisp baseline", Status: types.StatusOpen, + Priority: 2, IssueType: types.TypeTask, Ephemeral: true, + }, "tester"); err != nil { + t.Fatalf("CreateIssue wisp: %v", err) + } + if err := te.store.AddLabel(ctx, wispID, removeWispLabel, "tester"); err != nil { + t.Fatalf("AddLabel wisp baseline: %v", err) + } + if err := te.store.Commit(ctx, "test: seed durable baseline"); err != nil { + t.Fatalf("Commit baseline: %v", err) + } + before, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit before: %v", err) + } + + te.exec(t, ctx, "UPDATE issues SET title = ? WHERE id = ?", "durable working-only", durableID) + te.exec(t, ctx, "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?", + "durable working-only", durableID, string(types.EventCreated)) + te.exec(t, ctx, "UPDATE labels SET label = ? WHERE issue_id = ? AND label = ?", + workingLabel, durableID, baselineLabel) + + if err := te.store.RunInIssueLifecycleTransaction(ctx, "test: mutate standalone wisp", func(tx storage.IssueLifecycleTransaction) error { + if err := tx.UpdateIssue(ctx, wispID, map[string]interface{}{"title": "wisp updated"}, "tester"); err != nil { + return err + } + if err := tx.RemoveLabel(ctx, wispID, removeWispLabel, "tester"); err != nil { + return err + } + return tx.AddLabel(ctx, wispID, addWispLabel, "tester") + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction: %v", err) + } + + after, err := te.store.GetCurrentCommit(ctx) + if err != nil { + t.Fatalf("GetCurrentCommit after: %v", err) + } + if after != before { + t.Errorf("standalone wisp mutation changed HEAD from %s to %s", before, after) + } + + wisp, err := te.store.GetIssue(ctx, wispID) + if err != nil { + t.Fatalf("GetIssue wisp: %v", err) + } + if wisp.Title != "wisp updated" { + t.Errorf("wisp title = %q, want %q", wisp.Title, "wisp updated") + } + labels, err := te.store.GetLabels(ctx, wispID) + if err != nil { + t.Fatalf("GetLabels wisp: %v", err) + } + if len(labels) != 1 || labels[0] != addWispLabel { + t.Errorf("wisp labels = %v, want [%s]", labels, addWispLabel) + } + for _, event := range []struct { + eventType types.EventType + comment string + }{ + {eventType: types.EventUpdated}, + {eventType: types.EventLabelRemoved, comment: "Removed label: " + removeWispLabel}, + {eventType: types.EventLabelAdded, comment: "Added label: " + addWispLabel}, + } { + var count int + if event.comment == "" { + te.queryScalar(t, ctx, + "SELECT COUNT(*) FROM wisp_events WHERE issue_id = ? AND event_type = ?", + []any{wispID, string(event.eventType)}, &count) + } else { + te.queryScalar(t, ctx, + "SELECT COUNT(*) FROM wisp_events WHERE issue_id = ? AND event_type = ? AND comment = ?", + []any{wispID, string(event.eventType), event.comment}, &count) + } + if count != 1 { + t.Errorf("wisp event %s/%q count = %d, want 1", event.eventType, event.comment, count) + } + } + + var workingTitle, headTitle string + te.queryScalar(t, ctx, "SELECT title FROM issues WHERE id = ?", []any{durableID}, &workingTitle) + te.queryScalar(t, ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{durableID}, &headTitle) + if workingTitle != "durable working-only" || headTitle != "durable baseline" { + t.Errorf("durable issue titles = working:%q HEAD:%q", workingTitle, headTitle) + } + + // events is dolt_ignored since migration 0062 (bd-red8u) and has no HEAD + // state on this production-shaped database (see the same-status test above + // and TestEmbeddedMigration0062FlipsEventsToIgnoredPlane). Publication is + // covered by the HEAD-unchanged assertion; the durable label check below + // still exercises a versioned side table at HEAD. + var workingEvent int + te.queryScalar(t, ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?", + []any{durableID, string(types.EventCreated), "durable working-only"}, &workingEvent) + if workingEvent != 1 { + t.Errorf("durable working-set event edit count = %d, want 1", workingEvent) + } + + var workingLabelCount, headLabelCount int + te.queryScalar(t, ctx, + "SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = ?", + []any{durableID, workingLabel}, &workingLabelCount) + te.queryScalar(t, ctx, + "SELECT COUNT(*) FROM labels AS OF 'HEAD' WHERE issue_id = ? AND label = ?", + []any{durableID, workingLabel}, &headLabelCount) + if workingLabelCount != 1 || headLabelCount != 0 { + t.Errorf("durable label edit counts = working:%d HEAD:%d", workingLabelCount, headLabelCount) + } +} + +func seedEmbeddedTransactionWispBlocker(t *testing.T, te *testEnv, ctx context.Context, dependerID, wispID string) { + t.Helper() + if err := te.store.CreateIssue(ctx, &types.Issue{ID: dependerID, Title: dependerID, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, "tester"); err != nil { + t.Fatalf("CreateIssue durable: %v", err) + } + if err := te.store.CreateIssue(ctx, &types.Issue{ID: wispID, Title: wispID, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, "tester"); err != nil { + t.Fatalf("CreateIssue wisp: %v", err) + } + if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks}, "tester"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + var blocked bool + te.queryScalar(t, ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{dependerID}, &blocked) + if !blocked { + t.Fatal("seed durable depender is not blocked") + } +} diff --git a/internal/storage/errors_unsupported.go b/internal/storage/errors_unsupported.go index 6867b739a..30d50b0f4 100644 --- a/internal/storage/errors_unsupported.go +++ b/internal/storage/errors_unsupported.go @@ -2,9 +2,7 @@ package storage import "fmt" -// ErrUnsupported reports that a storage backend does not implement an -// operation. Typed per PROPOSAL-pluggable-storage-backends.md §4.0 error -// taxonomy; this is the embryo of the seam's ErrUnsupported{Op, Backend}. +// ErrUnsupported reports an operation unavailable on a storage backend. type ErrUnsupported struct { Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues" Backend string // e.g. "sqlite" diff --git a/internal/storage/hook_decorator.go b/internal/storage/hook_decorator.go index f3232e852..da8bdf89b 100644 --- a/internal/storage/hook_decorator.go +++ b/internal/storage/hook_decorator.go @@ -259,6 +259,26 @@ func (h *HookFiringStore) RunInTransaction(ctx context.Context, commitMsg string return nil } +// RunInIssueLifecycleTransaction tracks lifecycle hooks and fires them only +// after the underlying lifecycle transaction commits. +func (h *HookFiringStore) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx IssueLifecycleTransaction) error) error { + var tracked *hookTrackingLifecycleTransaction + err := h.inner.RunInIssueLifecycleTransaction(ctx, commitMsg, func(tx IssueLifecycleTransaction) error { + tracked = &hookTrackingLifecycleTransaction{ + hookTrackingTransaction: &hookTrackingTransaction{Transaction: tx}, + reopener: tx, + } + return fn(tracked) + }) + if err != nil || tracked == nil { + return err + } + for _, p := range tracked.pending { + h.fireHook(p.event, p.issue) + } + return nil +} + // ── Internal helpers ──────────────────────────────────────────────── func (h *HookFiringStore) fireHook(event string, issue *types.Issue) { @@ -268,6 +288,34 @@ func (h *HookFiringStore) fireHook(event string, issue *types.Issue) { h.runner.Run(event, issue) } +// CompleteIssueOperationCreate fires hooks for a committed guarded create. +// dependencies is a request-neutral snapshot of the dependency changes whose +// source issues need update hooks. +func (h *HookFiringStore) CompleteIssueOperationCreate(ctx context.Context, issue *types.Issue, dependencies []*types.Dependency) { + for _, pending := range createHookEvents(issue) { + h.fireHook(pending.event, pending.issue) + } + if h.runner == nil || len(dependencies) == 0 { + return + } + request := &types.Issue{Dependencies: cloneDependenciesForHook(dependencies)} + for _, pending := range dependencyHookEvents(ctx, []*types.Issue{request}, h.inner.GetIssue, h.inner.GetDependencyRecords) { + h.fireHook(pending.event, pending.issue) + } +} + +// CompleteIssueOperationUpdate fires the update hook for a committed guarded +// operation. +func (h *HookFiringStore) CompleteIssueOperationUpdate(issue *types.Issue) { + h.fireHook(hooks.EventUpdate, issue) +} + +// CompleteIssueOperationClose fires the close hook for a committed guarded +// close. +func (h *HookFiringStore) CompleteIssueOperationClose(issue *types.Issue) { + h.fireHook(hooks.EventClose, issue) +} + func (h *HookFiringStore) fireHookByID(ctx context.Context, event, id string) { if h.runner == nil { return @@ -523,6 +571,22 @@ func (t *hookTrackingTransaction) CloseIssue(ctx context.Context, id string, rea return nil } +type hookTrackingLifecycleTransaction struct { + *hookTrackingTransaction + reopener IssueLifecycleTransaction +} + +func (t *hookTrackingLifecycleTransaction) ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) { + changed, err := t.reopener.ReopenIssueWithResult(ctx, id, reason, actor) + if err != nil || !changed { + return changed, err + } + if issue, getErr := t.Transaction.GetIssue(ctx, id); getErr == nil { + t.pending = append(t.pending, pendingHook{hooks.EventUpdate, issue}) + } + return true, nil +} + func (t *hookTrackingTransaction) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error { return t.AddDependencyWithOptions(ctx, dep, actor, DependencyAddOptions{}) } diff --git a/internal/storage/hook_decorator_internal_test.go b/internal/storage/hook_decorator_internal_test.go index 4a3bcae4b..0ae8eabb1 100644 --- a/internal/storage/hook_decorator_internal_test.go +++ b/internal/storage/hook_decorator_internal_test.go @@ -27,7 +27,9 @@ type fakeHookStore struct { dropDependencies bool // updateCheckedErr, when non-nil, is returned by UpdateIssueChecked so a test // can simulate an inner refusal (e.g. ErrVersionMismatch). nil = success. - updateCheckedErr error + updateCheckedErr error + transactionReopenError error + transactionAddLabelErr error } func (s fakeHookStore) CreateIssue(_ context.Context, issue *types.Issue, _ string) error { @@ -70,13 +72,37 @@ func (s fakeHookStore) UpdateIssueChecked(_ context.Context, _ string, _ map[str } func (s fakeHookStore) RunInTransaction(ctx context.Context, _ string, fn func(tx Transaction) error) error { - return fn(fakeHookTransaction{issues: s.issues, dropDependencies: s.dropDependencies}) + return fn(fakeHookTransaction{ + issues: s.issues, + dropDependencies: s.dropDependencies, + reopenError: s.transactionReopenError, + addLabelError: s.transactionAddLabelErr, + }) +} + +func (s fakeHookStore) RunInIssueLifecycleTransaction(ctx context.Context, _ string, fn func(tx IssueLifecycleTransaction) error) error { + return fn(fakeHookTransaction{ + issues: s.issues, + dropDependencies: s.dropDependencies, + reopenError: s.transactionReopenError, + addLabelError: s.transactionAddLabelErr, + }) } type fakeHookTransaction struct { Transaction issues map[string]*types.Issue dropDependencies bool + reopenError error + addLabelError error +} + +func (tx fakeHookTransaction) ReopenIssueWithResult(_ context.Context, _ string, _ string, _ string) (bool, error) { + return tx.reopenError == nil, tx.reopenError +} + +func (tx fakeHookTransaction) AddLabel(_ context.Context, _ string, _ string, _ string) error { + return tx.addLabelError } func (tx fakeHookTransaction) CreateIssue(_ context.Context, issue *types.Issue, _ string) error { @@ -505,3 +531,57 @@ func TestHookFiringStoreUpdateIssueCheckedFiresOnSuccessOnly(t *testing.T) { } }) } + +func TestHookFiringStoreIssueLifecycleTransactionReopenForwardsCommitOnly(t *testing.T) { + t.Run("commit forwards and fires update", func(t *testing.T) { + runner := &recordingHookRunner{} + inner := fakeHookStore{issues: map[string]*types.Issue{"reopen-hook": {ID: "reopen-hook"}}} + store := &HookFiringStore{DoltStorage: inner, inner: inner, runner: runner} + if err := store.RunInIssueLifecycleTransaction(context.Background(), "reopen", func(tx IssueLifecycleTransaction) error { + _, err := tx.ReopenIssueWithResult(context.Background(), "reopen-hook", "", "tester") + return err + }); err != nil { + t.Fatalf("RunInIssueLifecycleTransaction: %v", err) + } + if !reflect.DeepEqual(runner.events, []string{hooks.EventUpdate}) { + t.Fatalf("events = %v, want one on_update after commit", runner.events) + } + }) + + t.Run("later failure fires no hook", func(t *testing.T) { + runner := &recordingHookRunner{} + labelErr := errors.New("label write failed") + inner := fakeHookStore{ + issues: map[string]*types.Issue{"reopen-hook": {ID: "reopen-hook"}}, + transactionAddLabelErr: labelErr, + } + store := &HookFiringStore{DoltStorage: inner, inner: inner, runner: runner} + err := store.RunInIssueLifecycleTransaction(context.Background(), "reopen", func(tx IssueLifecycleTransaction) error { + if _, err := tx.ReopenIssueWithResult(context.Background(), "reopen-hook", "", "tester"); err != nil { + return err + } + return tx.AddLabel(context.Background(), "reopen-hook", "remote", "tester") + }) + if !errors.Is(err, labelErr) { + t.Fatalf("RunInIssueLifecycleTransaction error = %v, want label failure", err) + } + if len(runner.events) != 0 { + t.Fatalf("events = %v, want none after rollback", runner.events) + } + }) + + t.Run("ordinary transaction does not expose lifecycle method", func(t *testing.T) { + inner := fakeHookStore{issues: map[string]*types.Issue{"reopen-hook": {ID: "reopen-hook"}}} + store := &HookFiringStore{DoltStorage: inner, inner: inner} + if err := store.RunInTransaction(context.Background(), "reopen", func(tx Transaction) error { + if _, ok := tx.(interface { + ReopenIssueWithResult(context.Context, string, string, string) (bool, error) + }); ok { + t.Fatal("wrapper exposed absent reopener") + } + return nil + }); err != nil { + t.Fatal(err) + } + }) +} diff --git a/internal/storage/hook_issue_operations.go b/internal/storage/hook_issue_operations.go new file mode 100644 index 000000000..5f0d23f10 --- /dev/null +++ b/internal/storage/hook_issue_operations.go @@ -0,0 +1,81 @@ +package storage + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// IssueLifecycle returns the inner store's lifecycle with this decorator's +// completion hooks layered over it. +// +// It recurses instead of delegating. A blind delegation would hand back the +// inner store's lifecycle unchanged and silently drop every hook this +// decorator exists to fire — the failure would be invisible until someone +// noticed their on_create script had stopped running. +func (h *HookFiringStore) IssueLifecycle() (issueops.Lifecycle, error) { + inner, err := h.inner.IssueLifecycle() + if err != nil { + return nil, err + } + return &hookIssueOperations{inner: inner, hooks: h}, nil +} + +// issueOperationHooks is the completion-hook surface hookIssueOperations needs +// from *HookFiringStore. Depending on the interface instead of the concrete +// decorator makes "did this verb fire a hook?" observable at this boundary, so +// the per-verb firing rules below can be tested without a real +// filesystem-backed async hook runner. +type issueOperationHooks interface { + CompleteIssueOperationCreate(ctx context.Context, issue *types.Issue, dependencies []*types.Dependency) + CompleteIssueOperationUpdate(issue *types.Issue) + CompleteIssueOperationClose(issue *types.Issue) +} + +var _ issueOperationHooks = (*HookFiringStore)(nil) + +type hookIssueOperations struct { + inner issueops.Lifecycle + hooks issueOperationHooks +} + +// Create fires the create hook, plus an update hook for every issue on the far +// end of an edge the create wrote. The edge list comes from the request +// because a reverse edge never appears in the created issue's own +// dependencies. Reading the request back after the call is safe: an +// issueops.Lifecycle never mutates caller-owned request values. +func (o *hookIssueOperations) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) { + result, err := o.inner.Create(ctx, request) + if err == nil && result.Issue != nil { + o.hooks.CompleteIssueOperationCreate(ctx, result.Issue, CreatePublicCreateDependencies(result.Issue.ID, request)) + } + return result, err +} + +func (o *hookIssueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) { + result, err := o.inner.Update(ctx, request) + if err == nil { + o.hooks.CompleteIssueOperationUpdate(result.Issue) + } + return result, err +} + +func (o *hookIssueOperations) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) { + result, err := o.inner.Close(ctx, request) + if err == nil { + o.hooks.CompleteIssueOperationClose(result.Issue) + } + return result, err +} + +// Reopen suppresses the update hook on a no-op, matching the legacy reopen +// path (hookTrackingLifecycleTransaction.ReopenIssueWithResult). Close and +// Update stay unconditional on success, also matching their legacy paths. +func (o *hookIssueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) { + result, err := o.inner.Reopen(ctx, request) + if err == nil && result.Changed { + o.hooks.CompleteIssueOperationUpdate(result.Issue) + } + return result, err +} diff --git a/internal/storage/hook_issue_operations_test.go b/internal/storage/hook_issue_operations_test.go new file mode 100644 index 000000000..5fa4d054b --- /dev/null +++ b/internal/storage/hook_issue_operations_test.go @@ -0,0 +1,229 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/hooks" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// fakeIssueOperations records which verbs reached it and can fail or report an +// unchanged result on demand. +type fakeIssueOperations struct { + calls []string + changed bool + err error +} + +func (f *fakeIssueOperations) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { + f.calls = append(f.calls, "create") + return issueops.CreateResult{}, f.err +} +func (f *fakeIssueOperations) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) { + f.calls = append(f.calls, "update") + return issueops.UpdateResult{Changed: f.changed}, f.err +} +func (f *fakeIssueOperations) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) { + f.calls = append(f.calls, "close") + return issueops.CloseResult{Changed: f.changed}, f.err +} +func (f *fakeIssueOperations) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { + f.calls = append(f.calls, "reopen") + return issueops.ReopenResult{Changed: f.changed}, f.err +} + +// recordingIssueOperationHooks records which completion hooks hookIssueOperations +// fired, so tests can assert the per-verb firing rules without a hook runner. +type recordingIssueOperationHooks struct { + completions []string +} + +func (r *recordingIssueOperationHooks) CompleteIssueOperationCreate(context.Context, *types.Issue, []*types.Dependency) { + r.completions = append(r.completions, "create") +} +func (r *recordingIssueOperationHooks) CompleteIssueOperationUpdate(*types.Issue) { + r.completions = append(r.completions, "update") +} +func (r *recordingIssueOperationHooks) CompleteIssueOperationClose(*types.Issue) { + r.completions = append(r.completions, "close") +} + +// lifecycleStore is a DoltStorage whose only real method is IssueLifecycle. +type lifecycleStore struct { + DoltStorage + lifecycle issueops.Lifecycle + err error +} + +func (s lifecycleStore) IssueLifecycle() (issueops.Lifecycle, error) { return s.lifecycle, s.err } + +// TestHookFiringStoreIssueLifecycleLayersHooksOverInner pins the recursion. +// Delegating to the inner store instead would still compile and still satisfy +// Storage, and every guarded write would silently stop firing hooks. +func TestHookFiringStoreIssueLifecycleLayersHooksOverInner(t *testing.T) { + inner := &fakeIssueOperations{} + store := &HookFiringStore{inner: lifecycleStore{lifecycle: inner}} + + lifecycle, err := store.IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle() error = %v", err) + } + hooked, ok := lifecycle.(*hookIssueOperations) + if !ok { + t.Fatalf("IssueLifecycle() = %T, want *hookIssueOperations", lifecycle) + } + if hooked.inner != issueops.Lifecycle(inner) { + t.Fatalf("hook layer wraps %#v, want the inner store's lifecycle", hooked.inner) + } + if hooked.hooks != issueOperationHooks(store) { + t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks) + } +} + +func TestHookFiringStoreIssueLifecyclePropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: lifecycleStore{err: want}} + + lifecycle, err := store.IssueLifecycle() + if !errors.Is(err, want) { + t.Fatalf("IssueLifecycle() error = %v, want %v", err, want) + } + if lifecycle != nil { + t.Fatalf("IssueLifecycle() = %T, want nil", lifecycle) + } +} + +// TestHookFiringStoreCompleteIssueOperationsFireOncePerCall pins the completion +// entry points to one hook event per call, in the caller's order. Deciding +// whether a committed change warrants a hook belongs to the caller +// (hookIssueOperations, below), not to these methods. +func TestHookFiringStoreCompleteIssueOperationsFireOncePerCall(t *testing.T) { + runner := &recordingHookRunner{} + store := &HookFiringStore{runner: runner} + issue := &types.Issue{ID: "hook-issue"} + + store.CompleteIssueOperationCreate(context.Background(), issue, nil) + store.CompleteIssueOperationUpdate(issue) + store.CompleteIssueOperationClose(issue) + + if !reflect.DeepEqual(runner.events, []string{hooks.EventCreate, hooks.EventUpdate, hooks.EventClose}) { + t.Fatalf("hook events = %#v, want create/update/close", runner.events) + } +} + +func TestHookFiringStoreCompleteIssueOperationCreateFiresReverseDependencyUpdate(t *testing.T) { + runner := &recordingHookRunner{} + reverse := &types.Dependency{IssueID: "existing-source", DependsOnID: "created", Type: types.DepRelatesTo, Metadata: `{"key":"value"}`, ThreadID: "thread"} + inner := fakeHookStore{issues: map[string]*types.Issue{ + "created": {ID: "created"}, + "existing-source": {ID: "existing-source", Dependencies: []*types.Dependency{reverse}}, + }} + store := &HookFiringStore{DoltStorage: inner, inner: inner, runner: runner} + created := &types.Issue{ID: "created"} + + store.CompleteIssueOperationCreate(context.Background(), created, []*types.Dependency{{IssueID: "existing-source", DependsOnID: "created", Type: types.DepRelatesTo}}) + + if !reflect.DeepEqual(runner.events, []string{hooks.EventCreate, hooks.EventUpdate}) { + t.Fatalf("hook events = %#v, want create then dependency update", runner.events) + } + if runner.issues[1].ID != "existing-source" || !reflect.DeepEqual(runner.issues[1].Dependencies, []*types.Dependency{reverse}) { + t.Fatalf("dependency hook snapshot = %#v", runner.issues[1]) + } + if created.Dependencies != nil { + t.Fatalf("created result was mutated: %#v", created.Dependencies) + } +} + +func TestHookIssueOperationsForwardsEveryVerbExactlyOnceAndPreservesErrors(t *testing.T) { + ctx := context.Background() + for _, test := range []struct { + name string + call func(issueops.Lifecycle) error + }{ + {"create", func(ops issueops.Lifecycle) error { _, err := ops.Create(ctx, issueops.CreateRequest{}); return err }}, + {"update", func(ops issueops.Lifecycle) error { _, err := ops.Update(ctx, issueops.UpdateRequest{}); return err }}, + {"close", func(ops issueops.Lifecycle) error { _, err := ops.Close(ctx, issueops.CloseRequest{}); return err }}, + {"reopen", func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err }}, + } { + t.Run(test.name+" success", func(t *testing.T) { + fake := &fakeIssueOperations{changed: true} + if err := test.call(&hookIssueOperations{inner: fake, hooks: NewHookFiringStore(nil, nil)}); err != nil || len(fake.calls) != 1 { + t.Fatalf("forward = %v, calls=%v", err, fake.calls) + } + }) + t.Run(test.name+" error", func(t *testing.T) { + want := errors.New("underlying") + fake := &fakeIssueOperations{changed: true, err: want} + if err := test.call(&hookIssueOperations{inner: fake, hooks: NewHookFiringStore(nil, nil)}); !errors.Is(err, want) || len(fake.calls) != 1 { + t.Fatalf("error=%v calls=%v", err, fake.calls) + } + }) + } +} + +func TestHookIssueOperationsFiresCompletionHooksPerVerbRules(t *testing.T) { + ctx := context.Background() + for _, test := range []struct { + name string + fake *fakeIssueOperations + call func(issueops.Lifecycle) error + wantErr bool + want []string + }{ + { + // Reopen mirrors hookTrackingLifecycleTransaction.ReopenIssueWithResult + // (internal/storage/hook_decorator.go), which queues no hook when the + // reopen changed nothing. + name: "reopen no-op fires nothing", + fake: &fakeIssueOperations{changed: false}, + call: func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err }, + want: nil, + }, + { + name: "reopen change fires update", + fake: &fakeIssueOperations{changed: true}, + call: func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err }, + want: []string{"update"}, + }, + { + name: "reopen error fires nothing", + fake: &fakeIssueOperations{changed: true, err: errors.New("underlying")}, + call: func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err }, + wantErr: true, + want: nil, + }, + { + // Update fires on every success, no-op included, mirroring + // HookFiringStore.UpdateIssueChecked (internal/storage/hook_decorator.go). + // Do not "unify" this with reopen's gating. + name: "update no-op still fires update", + fake: &fakeIssueOperations{changed: false}, + call: func(ops issueops.Lifecycle) error { _, err := ops.Update(ctx, issueops.UpdateRequest{}); return err }, + want: []string{"update"}, + }, + { + // Close fires on every success, including the idempotent re-close, + // mirroring HookFiringStore.CloseIssueChecked + // (internal/storage/hook_decorator.go). Do not "unify" this either. + name: "close no-op still fires close", + fake: &fakeIssueOperations{changed: false}, + call: func(ops issueops.Lifecycle) error { _, err := ops.Close(ctx, issueops.CloseRequest{}); return err }, + want: []string{"close"}, + }, + } { + t.Run(test.name, func(t *testing.T) { + recorder := &recordingIssueOperationHooks{} + err := test.call(&hookIssueOperations{inner: test.fake, hooks: recorder}) + if (err != nil) != test.wantErr { + t.Fatalf("call error = %v, wantErr = %v", err, test.wantErr) + } + if !reflect.DeepEqual(recorder.completions, test.want) { + t.Fatalf("completion hooks = %#v, want %#v", recorder.completions, test.want) + } + }) + } +} diff --git a/internal/storage/issue_create_dependencies.go b/internal/storage/issue_create_dependencies.go new file mode 100644 index 000000000..df414bcad --- /dev/null +++ b/internal/storage/issue_create_dependencies.go @@ -0,0 +1,37 @@ +package storage + +import ( + "encoding/json" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// CreatePublicCreateDependencies returns the dependency snapshot described by +// a public create request after its issue ID is known. +// +// It is derived from the request rather than from the created issue because a +// reverse edge is not an outgoing edge of the new issue: it belongs to the +// target, whose own hooks still need to see it. +func CreatePublicCreateDependencies(issueID string, request issueops.CreateRequest) []*types.Dependency { + dependencies := make([]*types.Dependency, 0, len(request.Dependencies)+2) + if request.ParentID != "" { + dependencies = append(dependencies, &types.Dependency{IssueID: issueID, DependsOnID: request.ParentID, Type: types.DepParentChild}) + } + if request.WaitsFor != nil { + gate := request.WaitsFor.Gate + if gate == "" { + gate = types.WaitsForAllChildren + } + metadata, _ := json.Marshal(types.WaitsForMeta{Gate: gate}) + dependencies = append(dependencies, &types.Dependency{IssueID: issueID, DependsOnID: request.WaitsFor.SpawnerID, Type: types.DepWaitsFor, Metadata: string(metadata)}) + } + for _, dependency := range request.Dependencies { + source, target := issueID, dependency.TargetID + if dependency.Reverse { + source, target = target, issueID + } + dependencies = append(dependencies, &types.Dependency{IssueID: source, DependsOnID: target, Type: dependency.Type, Metadata: dependency.Metadata, ThreadID: dependency.ThreadID}) + } + return dependencies +} diff --git a/internal/storage/issueops/aggregate.go b/internal/storage/issueops/aggregate.go new file mode 100644 index 000000000..7d12c11f5 --- /dev/null +++ b/internal/storage/issueops/aggregate.go @@ -0,0 +1,375 @@ +package issueops + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "sort" + "strings" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ChangedTables records durable tables changed by one guarded operation. +type ChangedTables map[string]bool + +// Add records table names, ignoring empty names and wisp-only tables. +func (tables ChangedTables) Add(names ...string) { + for _, name := range names { + if name != "" && name != "wisps" && !strings.HasPrefix(name, "wisp_") { + tables[name] = true + } + } +} + +// Merge records every table in other. +func (tables ChangedTables) Merge(other map[string]bool) { + for table := range other { + tables.Add(table) + } +} + +// UpdateFields converts the public scalar patch fields to storage updates. +func UpdateFields(patch publicops.IssuePatch) map[string]interface{} { + updates := map[string]interface{}{} + for _, field := range []struct { + set bool + key string + val interface{} + }{ + {patch.Title.Set, "title", patch.Title.Value}, + {patch.Description.Set, "description", patch.Description.Value}, + {patch.Design.Set, "design", patch.Design.Value}, + {patch.AcceptanceCriteria.Set, "acceptance_criteria", patch.AcceptanceCriteria.Value}, + {patch.Notes.Set, "notes", patch.Notes.Value}, + {patch.AppendNotes.Set, "append_notes", patch.AppendNotes.Value}, + {patch.SpecID.Set, "spec_id", patch.SpecID.Value}, + {patch.AwaitID.Set, "await_id", patch.AwaitID.Value}, + {patch.Status.Set, "status", patch.Status.Value}, + {patch.Priority.Set, "priority", patch.Priority.Value}, + {patch.IssueType.Set, "issue_type", patch.IssueType.Value}, + {patch.Assignee.Set, "assignee", patch.Assignee.Value}, + {patch.Owner.Set, "owner", patch.Owner.Value}, + {patch.ClosedBySession.Set, "closed_by_session", patch.ClosedBySession.Value}, + {patch.EstimatedMinutes.Set, "estimated_minutes", patch.EstimatedMinutes.Value}, + {patch.ExternalRef.Set, "external_ref", patch.ExternalRef.Value}, + {patch.DueAt.Set, "due_at", patch.DueAt.Value}, + {patch.DeferUntil.Set, "defer_until", patch.DeferUntil.Value}, + } { + if field.set { + updates[field.key] = field.val + } + } + return updates +} + +// ValidateUpdateRequest checks mutually exclusive guarded-update options and +// the canonical field values every backend must reject identically. Backends +// call it before touching the row so an invalid patch cannot half-apply. +func ValidateUpdateRequest(request publicops.UpdateRequest) error { + if request.Claim && (request.ExpectedAssignee != nil || request.ExpectedStatus != nil) { + return fmt.Errorf("%w: claim cannot use expected assignee or status", storage.ErrValidation) + } + if request.ForceAssigneeTransfer && (request.Claim || !request.Patch.Assignee.Set || request.ExpectedAssignee != nil) { + return fmt.Errorf("%w: invalid forced assignee transfer", storage.ErrValidation) + } + patch := request.Patch + if patch.Title.Set { + if err := types.ValidateIssueTitle(patch.Title.Value); err != nil { + return fmt.Errorf("%w: update title: %w", storage.ErrValidation, err) + } + } + if patch.Priority.Set { + if err := types.ValidateIssuePriority(patch.Priority.Value); err != nil { + return fmt.Errorf("%w: update priority: %w", storage.ErrValidation, err) + } + } + if patch.EstimatedMinutes.Set { + if err := types.ValidateIssueEstimatedMinutes(patch.EstimatedMinutes.Value); err != nil { + return fmt.Errorf("%w: update estimated_minutes: %w", storage.ErrValidation, err) + } + } + if patch.Persistence.Set && !patch.Persistence.Value.IsValid() { + return fmt.Errorf("%w: invalid persistence mode %q", storage.ErrValidation, patch.Persistence.Value) + } + return nil +} + +// ValidateMetadataPatch checks mutually exclusive metadata edits. +func ValidateMetadataPatch(patch publicops.MetadataPatch) error { + if patch.Replace.Set && (patch.Merge.Set || len(patch.Set) > 0 || len(patch.Unset) > 0) { + return fmt.Errorf("%w: cannot combine metadata replacement with incremental metadata edits", storage.ErrValidation) + } + return nil +} + +// ValidateScalarUpdates checks typed scalar values before they reach SQL. +func ValidateScalarUpdates(ctx context.Context, tx DBTX, updates map[string]interface{}) error { + if rawType, ok := updates["issue_type"]; ok { + var issueType types.IssueType + switch value := rawType.(type) { + case types.IssueType: + issueType = value + case string: + issueType = types.IssueType(value) + default: + return fmt.Errorf("%w: invalid issue type %v", storage.ErrValidation, rawType) + } + customTypes, err := ResolveCustomTypesInTx(ctx, tx) + if err != nil { + return fmt.Errorf("resolve custom issue types: %w", err) + } + if !issueType.IsValidWithCustom(customTypes) { + return fmt.Errorf("%w: invalid issue type %s", storage.ErrValidation, issueType) + } + } + for _, field := range []string{"assignee", "owner"} { + if raw, ok := updates[field]; ok { + if value, ok := raw.(string); ok { + if err := types.CheckFieldLen(field, value); err != nil { + return err + } + } + } + } + return nil +} + +// AuthorizeAssigneeTransfer protects an active assignment from unguarded transfer. +func AuthorizeAssigneeTransfer(ctx context.Context, tx DBTX, before *types.Issue, request publicops.UpdateRequest) error { + if !request.Patch.Assignee.Set || request.Patch.Assignee.Value == before.Assignee || request.ExpectedAssignee != nil || request.ForceAssigneeTransfer || before.Status != types.StatusInProgress || before.Assignee == "" || before.Assignee == request.Actor { + return nil + } + pools, err := ClaimPoolAliasesInTx(ctx, tx) + if err != nil { + return err + } + for _, pool := range pools { + if pool == before.Assignee { + return nil + } + } + return fmt.Errorf("%w: issue %s is assigned to %q", storage.ErrAlreadyClaimed, before.ID, before.Assignee) +} + +// ApplyMetadataPatch returns the canonical metadata value and whether it changes. +func ApplyMetadataPatch(current json.RawMessage, patch publicops.MetadataPatch) (json.RawMessage, bool, error) { + if !patch.Replace.Set && !patch.Merge.Set && len(patch.Set) == 0 && len(patch.Unset) == 0 { + return current, false, nil + } + setKeys := make([]string, 0, len(patch.Set)) + for key := range patch.Set { + setKeys = append(setKeys, key) + } + sort.Strings(setKeys) + for _, key := range setKeys { + if err := storage.ValidateMetadataKey(key); err != nil { + return nil, false, fmt.Errorf("%w: %w", storage.ErrValidation, err) + } + } + for _, key := range patch.Unset { + if err := storage.ValidateMetadataKey(key); err != nil { + return nil, false, fmt.Errorf("%w: %w", storage.ErrValidation, err) + } + } + var next json.RawMessage + if patch.Replace.Set { + next = append(json.RawMessage(nil), patch.Replace.Value...) + if len(next) == 0 { + next = json.RawMessage(`{}`) + } + if !json.Valid(next) { + return nil, false, fmt.Errorf("%w: metadata replacement is not valid JSON", storage.ErrValidation) + } + } else { + next = append(json.RawMessage(nil), current...) + if patch.Merge.Set { + // A JSON null unmarshals into a nil overlay map, so the merge + // below would silently accept it as "change nothing". + if strings.TrimSpace(string(patch.Merge.Value)) == "null" { + return nil, false, fmt.Errorf("%w: metadata merge must be a JSON object", storage.ErrValidation) + } + merged, err := storage.MergeMetadataJSON(next, patch.Merge.Value) + if err != nil { + return nil, false, fmt.Errorf("%w: metadata merge: %v", storage.ErrValidation, err) + } + next = merged + } + if len(patch.Set) > 0 || len(patch.Unset) > 0 { + values := make(map[string]json.RawMessage) + if len(next) > 0 && string(next) != "null" { + if err := json.Unmarshal(next, &values); err != nil { + return nil, false, fmt.Errorf("%w: metadata edits require an object: %v", storage.ErrValidation, err) + } + } + for _, key := range setKeys { + value := patch.Set[key] + if !json.Valid(value) { + return nil, false, fmt.Errorf("%w: metadata value for key %q is not valid JSON", storage.ErrValidation, key) + } + values[key] = append(json.RawMessage(nil), value...) + } + for _, key := range patch.Unset { + delete(values, key) + } + encoded, err := json.Marshal(values) + if err != nil { + return nil, false, fmt.Errorf("%w: encode metadata edits: %v", storage.ErrValidation, err) + } + next = encoded + } + } + if err := ValidateMetadataIfConfigured(next); err != nil { + return nil, false, err + } + changed, err := metadataChanged(current, next) + if err != nil { + return nil, false, fmt.Errorf("%w: compare metadata: %v", storage.ErrValidation, err) + } + return next, changed, nil +} + +func metadataChanged(current, next json.RawMessage) (bool, error) { + canonical := func(raw json.RawMessage) (string, error) { + if len(raw) == 0 || string(raw) == "null" { + return "{}", nil + } + var value any + if err := json.Unmarshal(raw, &value); err != nil { + return "", err + } + encoded, err := json.Marshal(value) + return string(encoded), err + } + left, err := canonical(current) + if err != nil { + return false, err + } + right, err := canonical(next) + if err != nil { + return false, err + } + return left != right, nil +} + +// ApplyLabelPatch applies ordered label edits and reports whether rows changed. +func ApplyLabelPatch(ctx context.Context, tx DBTX, current *types.Issue, patch publicops.LabelPatch, actor string) (bool, error) { + if !patch.Replace.Set && len(patch.Add) == 0 && len(patch.Remove) == 0 { + return false, nil + } + existing := stringSet(current.Labels) + target := make(map[string]struct{}, len(existing)+len(patch.Add)) + if !patch.Replace.Set { + for label := range existing { + target[label] = struct{}{} + } + } + for _, label := range patch.Replace.Value { + target[label] = struct{}{} + } + for _, label := range patch.Add { + target[label] = struct{}{} + } + for _, label := range patch.Remove { + delete(target, label) + } + if sameStringSet(existing, target) { + return false, nil + } + sqlTx, ok := tx.(*sql.Tx) + if !ok { + return false, fmt.Errorf("apply labels: transaction must be *sql.Tx") + } + for _, label := range stringSetDifference(existing, target) { + if err := RemoveLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor); err != nil { + return false, err + } + } + for _, label := range stringSetDifference(target, existing) { + if err := AddLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor); err != nil { + return false, err + } + } + return true, nil +} + +// ParentPatchResult reports the concrete changes made by ApplyParentPatch. +type ParentPatchResult struct { + Changed bool + IssueRowsChanged bool + WispRowsChanged bool +} + +// ApplyParentPatch replaces the parent-child targets and reports concrete changes. +func ApplyParentPatch(ctx context.Context, tx DBTX, current *types.Issue, parent publicops.Field[string], actor string) (ParentPatchResult, error) { + if !parent.Set { + return ParentPatchResult{}, nil + } + dependencies, err := GetDependencyRecordsForIssuesInTx(ctx, tx, []string{current.ID}) + if err != nil { + return ParentPatchResult{}, err + } + existing := map[string]struct{}{} + for _, dependency := range dependencies[current.ID] { + if dependency.Type == types.DepParentChild { + existing[dependency.DependsOnID] = struct{}{} + } + } + target := map[string]struct{}{} + if parent.Value != "" { + target[parent.Value] = struct{}{} + } + if sameStringSet(existing, target) { + return ParentPatchResult{}, nil + } + sqlTx, ok := tx.(*sql.Tx) + if !ok { + return ParentPatchResult{}, fmt.Errorf("apply parent: transaction must be *sql.Tx") + } + var recomputed RecomputeIsBlockedResult + for _, parentID := range stringSetDifference(existing, target) { + if _, err := removeDependencyInTx(ctx, sqlTx, current.ID, parentID, actor, false, &recomputed); err != nil { + return ParentPatchResult{}, err + } + } + for _, parentID := range stringSetDifference(target, existing) { + if _, err := addDependencyInTx(ctx, sqlTx, &types.Dependency{IssueID: current.ID, DependsOnID: parentID, Type: types.DepParentChild}, actor, AddDependencyOpts{}, &recomputed); err != nil { + return ParentPatchResult{}, err + } + } + return ParentPatchResult{Changed: true, IssueRowsChanged: recomputed.IssueRowsChanged, WispRowsChanged: recomputed.WispRowsChanged}, nil +} + +func stringSet(values []string) map[string]struct{} { + set := make(map[string]struct{}, len(values)) + for _, value := range values { + set[value] = struct{}{} + } + return set +} + +func sameStringSet(left, right map[string]struct{}) bool { + if len(left) != len(right) { + return false + } + for value := range left { + if _, ok := right[value]; !ok { + return false + } + } + return true +} + +func stringSetDifference(left, right map[string]struct{}) []string { + values := make([]string, 0) + for value := range left { + if _, ok := right[value]; !ok { + values = append(values, value) + } + } + sort.Strings(values) + return values +} diff --git a/internal/storage/issueops/blocked_state.go b/internal/storage/issueops/blocked_state.go index 3e960d851..871a238d5 100644 --- a/internal/storage/issueops/blocked_state.go +++ b/internal/storage/issueops/blocked_state.go @@ -93,27 +93,48 @@ const waitsForGateBlockedSQL = ` ) ` +// RecomputeIsBlockedResult reports which issue tables had rows changed while +// the blocked-state fixpoint converged. +type RecomputeIsBlockedResult struct { + IssueRowsChanged bool + WispRowsChanged bool +} + +// RecomputeIsBlockedInTx recomputes blocked state and discards the per-table +// change result retained by RecomputeIsBlockedInTxWithResult. func RecomputeIsBlockedInTx(ctx context.Context, tx DBTX, issueIDs, wispIDs []string) error { + _, err := RecomputeIsBlockedInTxWithResult(ctx, tx, issueIDs, wispIDs) + return err +} + +// RecomputeIsBlockedInTxWithResult recomputes blocked state to a fixpoint and +// reports whether an UPDATE changed rows in each issue table. +func RecomputeIsBlockedInTxWithResult( + ctx context.Context, tx DBTX, issueIDs, wispIDs []string, +) (RecomputeIsBlockedResult, error) { + var result RecomputeIsBlockedResult if len(issueIDs) == 0 && len(wispIDs) == 0 { - return nil + return result, nil } for { var changed int64 n, err := recomputeIsBlockedPassForIssuesInTx(ctx, tx, issueIDs) if err != nil { - return err + return result, err } changed += n + result.IssueRowsChanged = result.IssueRowsChanged || n > 0 n, err = recomputeIsBlockedPassForWispsInTx(ctx, tx, wispIDs) if err != nil { - return err + return result, err } changed += n + result.WispRowsChanged = result.WispRowsChanged || n > 0 if changed == 0 { - return nil + return result, nil } } } @@ -384,14 +405,20 @@ func runMarkUnmarkBatchedInTx(ctx context.Context, tx DBTX, markTmpl, unmarkTmpl if err != nil { return changed, fmt.Errorf("recompute is_blocked (mark): %w", err) } - n, _ := res.RowsAffected() + n, err := res.RowsAffected() + if err != nil { + return changed, fmt.Errorf("recompute is_blocked (mark rows affected): %w", err) + } changed += n res, err = tx.ExecContext(ctx, fmt.Sprintf(unmarkTmpl, placeholders), args...) if err != nil { return changed, fmt.Errorf("recompute is_blocked (unmark): %w", err) } - n, _ = res.RowsAffected() + n, err = res.RowsAffected() + if err != nil { + return changed, fmt.Errorf("recompute is_blocked (unmark rows affected): %w", err) + } changed += n } return changed, nil diff --git a/internal/storage/issueops/blocked_state_result_test.go b/internal/storage/issueops/blocked_state_result_test.go new file mode 100644 index 000000000..e84ef356c --- /dev/null +++ b/internal/storage/issueops/blocked_state_result_test.go @@ -0,0 +1,104 @@ +package issueops + +import ( + "context" + "database/sql/driver" + "errors" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" +) + +func newBlockedStateResultMock(t *testing.T) (sqlmock.Sqlmock, DBTX) { + t.Helper() + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + t.Cleanup(func() { + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("unmet sqlmock expectations: %v", err) + } + _ = db.Close() + }) + return mock, db +} + +func expectBlockedStatePass(mock sqlmock.Sqlmock, table, alias string, mark, unmark driver.Result) { + mock.ExpectExec(regexp.QuoteMeta("UPDATE " + table + " " + alias + " SET " + alias + ".is_blocked = 1")). + WillReturnResult(mark) + mock.ExpectExec(regexp.QuoteMeta("UPDATE " + table + " " + alias + " SET " + alias + ".is_blocked = 0")). + WillReturnResult(unmark) +} + +func TestRecomputeIsBlockedInTxWithResult(t *testing.T) { + t.Run("issue rows changed", func(t *testing.T) { + mock, db := newBlockedStateResultMock(t) + expectBlockedStatePass(mock, "issues", "i", sqlmock.NewResult(0, 1), sqlmock.NewResult(0, 0)) + expectBlockedStatePass(mock, "issues", "i", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0)) + + result, err := RecomputeIsBlockedInTxWithResult(context.Background(), db, []string{"issue-1"}, nil) + if err != nil { + t.Fatalf("RecomputeIsBlockedInTxWithResult: %v", err) + } + if !result.IssueRowsChanged || result.WispRowsChanged { + t.Fatalf("result = %+v, want issue change only", result) + } + }) + + t.Run("wisp rows changed", func(t *testing.T) { + mock, db := newBlockedStateResultMock(t) + expectBlockedStatePass(mock, "wisps", "w", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 1)) + expectBlockedStatePass(mock, "wisps", "w", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0)) + + result, err := RecomputeIsBlockedInTxWithResult(context.Background(), db, nil, []string{"wisp-1"}) + if err != nil { + t.Fatalf("RecomputeIsBlockedInTxWithResult: %v", err) + } + if result.IssueRowsChanged || !result.WispRowsChanged { + t.Fatalf("result = %+v, want wisp change only", result) + } + }) + + t.Run("no rows changed", func(t *testing.T) { + mock, db := newBlockedStateResultMock(t) + expectBlockedStatePass(mock, "issues", "i", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0)) + expectBlockedStatePass(mock, "wisps", "w", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0)) + + result, err := RecomputeIsBlockedInTxWithResult( + context.Background(), db, []string{"issue-1"}, []string{"wisp-1"}, + ) + if err != nil { + t.Fatalf("RecomputeIsBlockedInTxWithResult: %v", err) + } + if result.IssueRowsChanged || result.WispRowsChanged { + t.Fatalf("result = %+v, want no changes", result) + } + }) +} + +func TestRunMarkUnmarkBatchedInTxPropagatesRowsAffectedErrors(t *testing.T) { + sentinel := errors.New("rows affected unavailable") + for _, phase := range []string{"mark", "unmark"} { + t.Run(phase, func(t *testing.T) { + mock, db := newBlockedStateResultMock(t) + if phase == "mark" { + mock.ExpectExec(regexp.QuoteMeta("UPDATE issues i SET i.is_blocked = 1")). + WillReturnResult(sqlmock.NewErrorResult(sentinel)) + } else { + mock.ExpectExec(regexp.QuoteMeta("UPDATE issues i SET i.is_blocked = 1")). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(regexp.QuoteMeta("UPDATE issues i SET i.is_blocked = 0")). + WillReturnResult(sqlmock.NewErrorResult(sentinel)) + } + + _, err := runMarkUnmarkBatchedInTx( + context.Background(), db, markBlockedTemplateForIssues(), unmarkBlockedTemplateForIssues(), []string{"issue-1"}, + ) + if !errors.Is(err, sentinel) { + t.Fatalf("err = %v, want rows-affected error", err) + } + }) + } +} diff --git a/internal/storage/issueops/close.go b/internal/storage/issueops/close.go index 15046d165..e03dcb890 100644 --- a/internal/storage/issueops/close.go +++ b/internal/storage/issueops/close.go @@ -5,16 +5,26 @@ import ( "database/sql" "errors" "fmt" + "strconv" + "sync/atomic" "time" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) +const closeCheckedSavepointPrefix = "issueops_close_checked_" + +var closeCheckedSavepointCounter atomic.Uint64 + // CloseResult holds the result of a CloseIssueInTx call. type CloseResult struct { IsWisp bool AlreadyClosed bool + OpenChildren int + // IssueRowsChanged reports whether this close changed a durable issues row, + // either directly or while recomputing a dependent's blocked state. + IssueRowsChanged bool } // CloseIssueInTx closes an issue within a transaction, setting status to closed @@ -29,6 +39,7 @@ func CloseIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, reason, } // CloseIssueCheckedInTx closes an issue within a transaction, refusing with +// storage.ErrCloseOpenChildren when it has open parent-child dependents and // storage.ErrCloseBlocked when it has a LIVE direct blocker unless force is set. // The guard (IsBlockedInTx) and the close (CloseIssueInTx) share the SAME // transaction, so no blocker can clear between the check and the close. @@ -46,7 +57,7 @@ func CloseIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, reason, // precondition: the row's current RowVersion (row_lock) must still equal // *expectedVersion or the close refuses with storage.ErrVersionMismatch. This // runs first — before the is_blocked guard and before force short-circuits it — -// so force bypasses only the is_blocked guard, never the version check. Because +// so force bypasses the child and blocker policies, never the version check. Because // the read shares this transaction, a mismatch returns before any write and the // transaction rolls back with the issue unchanged (a true compare-and-swap). // row_lock only tracks lifecycle/ownership writes (status, assignee, started_at), @@ -59,56 +70,212 @@ func CloseIssueCheckedInTx(ctx context.Context, tx DBTX, id, reason, actor, sess return nil, err } } - if !force { - // The blocked guard only has meaning for an open→closed transition. An - // already-closed row is an idempotent no-op (Unchanged=true per the - // Storage.CloseIssueChecked contract), so detect that first. A closed - // row can still carry a stale is_blocked=1 — e.g. after a cross-clone - // Dolt merge, a state the schema explicitly models (GetStatistics - // filters `is_blocked = 1 AND status <> 'closed'`). Guarding such a row - // would refuse the idempotent re-close with ErrCloseBlocked. Only guard - // rows that are not already closed; CloseIssueInTx below is the sole - // detector of the already-closed no-op (and matches the Force path, - // which already reaches Unchanged=true by skipping the guard). - closed, err := isClosedInTx(ctx, tx, id) + // Read the target before policy checks. A closed target can still have open + // children, which refuses without Force just like an open target. + closed, targetColumn, found, err := isClosedInTx(ctx, tx, id) + if err != nil { + return nil, err + } + if !found { + return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) + } + // domain/db also supplies a *sql.DB Runner, whose independently pooled + // statements cannot retain a savepoint. The shared UOW uses a pinned + // *sql.Conn after START TRANSACTION, while embedded callers use *sql.Tx. + if !closeCheckedSavepointEligible(tx) { + return closeIssueCheckedAfterSavepoint(ctx, tx, id, reason, actor, session, force, closed, targetColumn) + } + savepoint, err := createCloseCheckedSavepoint(ctx, tx) + if err != nil { + return nil, err + } + result, scopedErr := closeIssueCheckedAfterSavepoint(ctx, tx, id, reason, actor, session, force, closed, targetColumn) + if scopedErr != nil { + if cleanupErr := rollbackAndReleaseCloseCheckedSavepoint(ctx, tx, savepoint); cleanupErr != nil { + return nil, fmt.Errorf("discard checked close savepoint after %v: %w", scopedErr, cleanupErr) + } + return nil, scopedErr + } + if err := releaseCloseCheckedSavepoint(ctx, tx, savepoint); err != nil { + if rollbackErr := rollbackToCloseCheckedSavepoint(ctx, tx, savepoint); rollbackErr != nil { + return nil, fmt.Errorf("release checked close savepoint: %v; rollback to savepoint: %w", err, rollbackErr) + } + return nil, err + } + return result, nil +} + +func closeCheckedSavepointEligible(tx DBTX) bool { + switch tx.(type) { + case *sql.Tx, *sql.Conn: + return true + default: + return false + } +} + +func closeIssueCheckedAfterSavepoint(ctx context.Context, tx DBTX, id, reason, actor, session string, force, closed bool, targetColumn string) (*CloseResult, error) { + // This write precedes every child-count policy branch, including Force and + // idempotent closes. A concurrent new parent-child edge writes its own tier + // cell, while a close writes both tiers, so Dolt cannot merge a stale count + // with a new edge. + if err := touchDependencyCoordinationInTx(ctx, tx, id); err != nil { + return nil, err + } + openChildren, err := countOpenChildrenForTargetInTx(ctx, tx, id, targetColumn) + if err != nil { + return nil, err + } + if !force && openChildren > 0 { + return nil, &storage.CloseOpenChildrenError{IssueID: id, OpenChildren: openChildren} + } + if !force && !closed { + blocked, blockers, err := IsBlockedInTx(ctx, tx, id) if err != nil { return nil, err } - if !closed { - blocked, blockers, err := IsBlockedInTx(ctx, tx, id) - if err != nil { - return nil, err - } - if blocked && len(blockers) > 0 { - return nil, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, id, blockers) - } + if blocked && len(blockers) > 0 { + return nil, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, id, blockers) } } - return CloseIssueInTx(ctx, tx, id, reason, actor, session) + result, err := CloseIssueInTx(ctx, tx, id, reason, actor, session) + if err != nil { + return nil, err + } + result.OpenChildren = openChildren + return result, nil } -// isClosedInTx reports whether the issue (or wisp) identified by id is already -// in the closed status. It probes the issues table then the optional wisps -// table, mirroring IsBlockedInTx's table order. A missing row reports false so -// the caller falls through to CloseIssueInTx, which returns ErrNotFound. +func countOpenChildrenInTx(ctx context.Context, tx DBTX, id string) (int, error) { + targetColumn, err := dependencyTargetColumnForIDInTx(ctx, tx, id) + if err != nil { + return 0, err + } + return countOpenChildrenForTargetInTx(ctx, tx, id, targetColumn) +} + +func countOpenChildrenForTargetInTx(ctx context.Context, tx DBTX, id, targetColumn string) (int, error) { + if targetColumn != "depends_on_issue_id" && targetColumn != "depends_on_wisp_id" { + return 0, fmt.Errorf("count open children: unsupported target column %q", targetColumn) + } + var durableCount int + //nolint:gosec // G201: targetColumn is validated above against two hardcoded identifiers. + durableQuery := fmt.Sprintf(` + SELECT COUNT(DISTINCT dependency.issue_id) + FROM dependencies AS dependency + JOIN issues AS child ON child.id = dependency.issue_id + WHERE dependency.%s = ? + AND dependency.type = 'parent-child' + AND child.status != 'closed' + `, targetColumn) + if err := tx.QueryRowContext(ctx, durableQuery, id).Scan(&durableCount); err != nil { + return 0, fmt.Errorf("count open durable children for %s: %w", id, err) + } + + var wispCount int + //nolint:gosec // G201: targetColumn is validated above against two hardcoded identifiers. + wispQuery := fmt.Sprintf(` + SELECT COUNT(DISTINCT dependency.issue_id) + FROM wisp_dependencies AS dependency + JOIN wisps AS child ON child.id = dependency.issue_id + WHERE dependency.%s = ? + AND dependency.type = 'parent-child' + AND child.status != 'closed' + AND NOT EXISTS ( + SELECT 1 FROM dependencies AS durable WHERE durable.id = dependency.id + ) + `, targetColumn) + if err := tx.QueryRowContext(ctx, wispQuery, id).Scan(&wispCount); err != nil { + if optionalBlockedTable("wisp_dependencies") && isTableNotExistError(err) { + return durableCount, nil + } + return 0, fmt.Errorf("count open wisp children for %s: %w", id, err) + } + return durableCount + wispCount, nil +} + +func createCloseCheckedSavepoint(ctx context.Context, tx DBTX) (string, error) { + name := closeCheckedSavepointPrefix + strconv.FormatUint(closeCheckedSavepointCounter.Add(1), 10) + //nolint:gosec // G201: name is a fixed identifier-safe prefix plus an atomic decimal counter. + if _, err := tx.ExecContext(ctx, "SAVEPOINT "+name); err != nil { + return "", fmt.Errorf("create checked close savepoint: %w", err) + } + return name, nil +} + +func rollbackAndReleaseCloseCheckedSavepoint(ctx context.Context, tx DBTX, name string) error { + rollbackErr := rollbackToCloseCheckedSavepoint(ctx, tx, name) + releaseErr := releaseCloseCheckedSavepoint(ctx, tx, name) + return errors.Join(rollbackErr, releaseErr) +} + +func rollbackToCloseCheckedSavepoint(ctx context.Context, tx DBTX, name string) error { + //nolint:gosec // G201: name is generated by createCloseCheckedSavepoint. + if _, err := tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT "+name); err != nil { + return fmt.Errorf("rollback checked close savepoint: %w", err) + } + return nil +} + +func releaseCloseCheckedSavepoint(ctx context.Context, tx DBTX, name string) error { + //nolint:gosec // G201: name is generated by createCloseCheckedSavepoint. + if _, err := tx.ExecContext(ctx, "RELEASE SAVEPOINT "+name); err != nil { + return fmt.Errorf("release checked close savepoint: %w", err) + } + return nil +} + +// dependencyTargetColumnForIDInTx returns the typed target column for id, +// preferring a durable row when an id is present in both tables. +func dependencyTargetColumnForIDInTx(ctx context.Context, tx DBTX, id string) (string, error) { + var found int + err := tx.QueryRowContext(ctx, "SELECT 1 FROM issues WHERE id = ?", id).Scan(&found) + if err == nil { + return "depends_on_issue_id", nil + } + if !errors.Is(err, sql.ErrNoRows) { + return "", fmt.Errorf("classify child-count target in issues: %w", err) + } + err = tx.QueryRowContext(ctx, "SELECT 1 FROM wisps WHERE id = ?", id).Scan(&found) + if err == nil { + return "depends_on_wisp_id", nil + } + if optionalBlockedTable("wisps") && isTableNotExistError(err) { + return "depends_on_issue_id", nil + } + if !errors.Is(err, sql.ErrNoRows) { + return "", fmt.Errorf("classify child-count target in wisps: %w", err) + } + return "depends_on_issue_id", nil +} + +// isClosedInTx reports whether the issue (or wisp) identified by id exists and +// is already closed. It probes the issues table then the optional wisps table, +// mirroring IsBlockedInTx's table order. // //nolint:gosec // G201: table is a hardcoded "issues" or "wisps". -func isClosedInTx(ctx context.Context, tx DBTX, id string) (bool, error) { - for _, table := range []string{"issues", "wisps"} { +func isClosedInTx(ctx context.Context, tx DBTX, id string) (closed bool, targetColumn string, found bool, err error) { + for _, target := range []struct { + table string + column string + }{ + {table: "issues", column: "depends_on_issue_id"}, + {table: "wisps", column: "depends_on_wisp_id"}, + } { var status string - err := tx.QueryRowContext(ctx, "SELECT status FROM "+table+" WHERE id = ?", id).Scan(&status) + err := tx.QueryRowContext(ctx, "SELECT status FROM "+target.table+" WHERE id = ?", id).Scan(&status) if err == nil { - return types.Status(status) == types.StatusClosed, nil + return types.Status(status) == types.StatusClosed, target.column, true, nil } if errors.Is(err, sql.ErrNoRows) { continue } - if optionalBlockedTable(table) && isTableNotExistError(err) { + if optionalBlockedTable(target.table) && isTableNotExistError(err) { continue } - return false, fmt.Errorf("read status from %s: %w", table, err) + return false, "", false, fmt.Errorf("read status from %s: %w", target.table, err) } - return false, nil + return false, "", false, nil } //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) @@ -174,9 +341,10 @@ func closeIssueInTx(ctx context.Context, tx DBTX, id string, reason, actor, sess } } - if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil { + recompute, err := RecomputeIsBlockedInTxWithResult(ctx, tx, affectedIssues, affectedWisps) + if err != nil { return nil, fmt.Errorf("recompute is_blocked after close for %s: %w", id, err) } - return &CloseResult{IsWisp: isWisp}, nil + return &CloseResult{IsWisp: isWisp, IssueRowsChanged: !isWisp || recompute.IssueRowsChanged}, nil } diff --git a/internal/storage/issueops/close_test.go b/internal/storage/issueops/close_test.go new file mode 100644 index 000000000..538d07be8 --- /dev/null +++ b/internal/storage/issueops/close_test.go @@ -0,0 +1,45 @@ +package issueops + +import ( + "context" + "testing" + + "github.com/DATA-DOG/go-sqlmock" +) + +// TestCountOpenChildrenInTxUsesTargetedOpenEdges keeps the close guard from +// regressing to a dependent-record scan followed by full issue hydration. The +// count needs only two indexed aggregates: permanent children and wisp children +// whose natural edge is not already durable. +func TestCountOpenChildrenInTxUsesTargetedOpenEdges(t *testing.T) { + t.Parallel() + + _, mock, tx := beginMockTx(t) + const parent = "close-count-parent" + + // Route the target durable-first, then use direct typed-target predicates + // (not COALESCE), literal closed filtering, and a durable-id anti-join for + // the wisp aggregate. The regexes intentionally leave SQL layout free. + mock.ExpectQuery(`SELECT 1 FROM issues WHERE id = \?`). + WithArgs(parent). + WillReturnRows(sqlmock.NewRows([]string{"1"}).AddRow(1)) + durableQuery := `(?s)SELECT\s+COUNT\(DISTINCT\s+dependency\.issue_id\).*FROM\s+dependencies.*JOIN\s+issues.*depends_on_issue_id\s*=\s*\?.*type\s*=\s*'parent-child'.*status\s*!=\s*'closed'` + wispQuery := `(?s)SELECT\s+COUNT\(DISTINCT\s+dependency\.issue_id\).*FROM\s+wisp_dependencies.*JOIN\s+wisps.*depends_on_issue_id\s*=\s*\?.*type\s*=\s*'parent-child'.*status\s*!=\s*'closed'.*NOT EXISTS.*FROM\s+dependencies.*durable\.id\s*=\s*dependency\.id` + mock.ExpectQuery(durableQuery). + WithArgs(parent). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + mock.ExpectQuery(wispQuery). + WithArgs(parent). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + + got, err := countOpenChildrenInTx(context.Background(), tx, parent) + if err != nil { + t.Fatalf("countOpenChildrenInTx: %v", err) + } + if got != 2 { + t.Fatalf("open child count = %d, want 2 (one durable + one wisp parent-child edge)", got) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet targeted-count SQL expectations: %v", err) + } +} diff --git a/internal/storage/issueops/comments.go b/internal/storage/issueops/comments.go index 1fec6a73d..0cc9d31ce 100644 --- a/internal/storage/issueops/comments.go +++ b/internal/storage/issueops/comments.go @@ -15,7 +15,7 @@ import ( // transaction. Automatically routes to wisp_comments if the ID is an active wisp. // //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func GetIssueCommentsInTx(ctx context.Context, tx *sql.Tx, issueID string) ([]*types.Comment, error) { +func GetIssueCommentsInTx(ctx context.Context, tx DBTX, issueID string) ([]*types.Comment, error) { table := "comments" if IsActiveWispInTx(ctx, tx, issueID) { table = "wisp_comments" diff --git a/internal/storage/issueops/config_helpers.go b/internal/storage/issueops/config_helpers.go index f765bddb0..21d45daa6 100644 --- a/internal/storage/issueops/config_helpers.go +++ b/internal/storage/issueops/config_helpers.go @@ -177,13 +177,17 @@ func getConfigKeysInTx(ctx context.Context, tx DBTX, keys ...string) (map[string func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx DBTX) ([]types.CustomStatus, error) { // Try the normalized table first rows, err := tx.QueryContext(ctx, "SELECT name, category FROM custom_statuses ORDER BY name") - if err == nil { + if err != nil { + if !isTableNotExistError(err) { + return nil, fmt.Errorf("query custom_statuses: %w", err) + } + } else { defer rows.Close() var result []types.CustomStatus for rows.Next() { var name, category string if err := rows.Scan(&name, &category); err != nil { - continue + return nil, fmt.Errorf("scan custom_statuses: %w", err) } result = append(result, types.CustomStatus{ Name: name, @@ -225,6 +229,26 @@ func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx DBTX) ([]types.Cu return nil, nil } +// ReopenCategoryInTx resolves the reopen category for status from the same +// transaction that will perform the state change. Unknown and malformed custom +// statuses are treated as unspecified so callers leave them unchanged. +func ReopenCategoryInTx(ctx context.Context, tx DBTX, status types.Status) (types.StatusCategory, error) { + if status.IsValid() { + return types.BuiltInStatusCategory(status), nil + } + + statuses, err := ResolveCustomStatusesDetailedInTx(ctx, tx) + if err != nil { + return types.CategoryUnspecified, fmt.Errorf("resolve custom statuses: %w", err) + } + for _, custom := range statuses { + if custom.Name == string(status) { + return custom.Category, nil + } + } + return types.CategoryUnspecified, nil +} + // ResolveCustomTypesInTx reads custom issue types from the custom_types table, // falling back to config string when the table is empty or pre-migration, // and always overlay-unions project-extension types from .beads/config.yaml on diff --git a/internal/storage/issueops/config_helpers_test.go b/internal/storage/issueops/config_helpers_test.go index 47cd2bfe3..db579486b 100644 --- a/internal/storage/issueops/config_helpers_test.go +++ b/internal/storage/issueops/config_helpers_test.go @@ -1,11 +1,160 @@ package issueops import ( + "context" + "errors" + "regexp" "testing" + "github.com/DATA-DOG/go-sqlmock" "github.com/steveyegge/beads/internal/types" ) +func TestReopenCategoryInTx(t *testing.T) { + t.Run("literal closed is done without configuration", func(t *testing.T) { + category, err := ReopenCategoryInTx(context.Background(), nil, types.StatusClosed) + if err != nil { + t.Fatalf("ReopenCategoryInTx: %v", err) + } + if category != types.CategoryDone { + t.Fatalf("category = %q, want %q", category, types.CategoryDone) + } + }) + + t.Run("normalized custom done status", func(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}). + AddRow("archived", string(types.CategoryDone))) + mock.ExpectRollback() + + category, err := ReopenCategoryInTx(context.Background(), tx, "archived") + if err != nil { + t.Fatalf("ReopenCategoryInTx: %v", err) + } + if category != types.CategoryDone { + t.Fatalf("category = %q, want %q", category, types.CategoryDone) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("legacy config fallback", func(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnError(errors.New("Error 1146 (42S02): Table 'beads.custom_statuses' doesn't exist")) + mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")). + WithArgs("status.custom"). + WillReturnRows(sqlmock.NewRows([]string{"value"}).AddRow("archived:done")) + mock.ExpectRollback() + + category, err := ReopenCategoryInTx(context.Background(), tx, "archived") + if err != nil { + t.Fatalf("ReopenCategoryInTx: %v", err) + } + if category != types.CategoryDone { + t.Fatalf("category = %q, want %q", category, types.CategoryDone) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("normalized query failure does not fall back to legacy config", func(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnError(errors.New("connection reset")) + mock.ExpectRollback() + + _, err := ReopenCategoryInTx(context.Background(), tx, "archived") + if err == nil || !regexp.MustCompile("connection reset").MatchString(err.Error()) { + t.Fatalf("err = %v, want normalized query failure", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("normalized row scan failure does not fall back to legacy config", func(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("archived", nil)) + mock.ExpectRollback() + + _, err := ReopenCategoryInTx(context.Background(), tx, "archived") + if err == nil || !regexp.MustCompile("scan custom_statuses").MatchString(err.Error()) { + t.Fatalf("err = %v, want normalized scan failure", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("malformed legacy config is unspecified", func(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"})) + mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")). + WithArgs("status.custom"). + WillReturnRows(sqlmock.NewRows([]string{"value"}).AddRow("archived:not-a-category")) + mock.ExpectRollback() + + category, err := ReopenCategoryInTx(context.Background(), tx, "archived") + if err != nil { + t.Fatalf("ReopenCategoryInTx: %v", err) + } + if category != types.CategoryUnspecified { + t.Fatalf("category = %q, want %q", category, types.CategoryUnspecified) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("configuration query failure is returned", func(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"})) + mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")). + WithArgs("status.custom"). + WillReturnError(errors.New("configuration unavailable")) + mock.ExpectRollback() + + _, err := ReopenCategoryInTx(context.Background(), tx, "archived") + if err == nil || !regexp.MustCompile("configuration unavailable").MatchString(err.Error()) { + t.Fatalf("err = %v, want configuration query failure", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) +} + func TestParseStatusFallback(t *testing.T) { tests := []struct { name string diff --git a/internal/storage/issueops/create.go b/internal/storage/issueops/create.go index ae98cbcaa..5dc9813dc 100644 --- a/internal/storage/issueops/create.go +++ b/internal/storage/issueops/create.go @@ -3,10 +3,13 @@ package issueops import ( "context" "database/sql" + "errors" "fmt" "strings" "time" + gmssql "github.com/dolthub/go-mysql-server/sql" + "github.com/go-sql-driver/mysql" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/depid" "github.com/steveyegge/beads/internal/types" @@ -58,7 +61,15 @@ type CreateIssueResult struct { // StaleRejected reports that the RejectStaleUpserts guard kept the stored // row: nothing was written, and the issue's aux data must not be // persisted by later batch stages either (bd-578h9.8). - StaleRejected bool + StaleRejected bool + persistedDependencies []persistedDependency +} + +type persistedDependency struct { + source string + target string + depType types.DependencyType + sourceWisp bool } func (r *CreateIssueResult) markChanged(table string) { @@ -89,23 +100,12 @@ func CreateIssueInTxWithResult(ctx context.Context, tx *sql.Tx, bc *BatchContext issueTable, eventTable := TableRouting(issue) - if issue.ID == "" { - prefix := bc.ConfigPrefix - if issue.PrefixOverride != "" { - prefix = issue.PrefixOverride - } else if issue.IDPrefix != "" { - prefix = bc.ConfigPrefix + "-" + issue.IDPrefix - } else if IsWisp(issue) { - prefix = bc.ConfigPrefix + "-wisp" - } - var err error - issue.ID, err = GenerateIssueIDInTable(ctx, tx, issueTable, prefix, issue, actor) - if err != nil { - return result, fmt.Errorf("failed to generate issue ID: %w", err) - } - } else if !bc.Opts.SkipPrefixValidation { - if err := ValidateIssueIDPrefix(issue.ID, bc.ConfigPrefix, bc.AllowedPrefixes); err != nil { - return result, fmt.Errorf("prefix validation failed for %s: %w", issue.ID, err) + if err := assignCreateIssueIDInTx(ctx, tx, bc, issue, actor); err != nil { + return result, err + } + if bc.Opts.CreateOnly { + if err := EnsureIssueIDAvailableInTx(ctx, tx, issue.ID); err != nil { + return result, err } } @@ -167,6 +167,32 @@ func CreateIssueInTxWithResult(ctx context.Context, tx *sql.Tx, bc *BatchContext return result, nil } +func assignCreateIssueIDInTx(ctx context.Context, tx *sql.Tx, bc *BatchContext, issue *types.Issue, actor string) error { + if issue.ID == "" { + issueTable, _ := TableRouting(issue) + prefix := bc.ConfigPrefix + if issue.PrefixOverride != "" { + prefix = issue.PrefixOverride + } else if issue.IDPrefix != "" { + prefix = bc.ConfigPrefix + "-" + issue.IDPrefix + } else if IsWisp(issue) { + prefix = bc.ConfigPrefix + "-wisp" + } + var err error + issue.ID, err = GenerateIssueIDInTable(ctx, tx, issueTable, prefix, issue, actor) + if err != nil { + return fmt.Errorf("failed to generate issue ID: %w", err) + } + return nil + } + if !bc.Opts.SkipPrefixValidation { + if err := ValidateIssueIDPrefix(issue.ID, bc.ConfigPrefix, bc.AllowedPrefixes); err != nil { + return fmt.Errorf("prefix validation failed for %s: %w", issue.ID, err) + } + } + return nil +} + // CreateIssuesResult reports side effects that callers need for selective // Dolt staging after CreateIssuesInTxWithResult returns. type CreateIssuesResult struct { @@ -236,14 +262,18 @@ func CreateIssuesInTxWithResult(ctx context.Context, tx *sql.Tx, issues []*types for table := range changedCounters { result.markChanged(table) } - issueIDs, wispIDs := createBlockedRecomputeIDs(issues) - if err := RecomputeIsBlockedInTx(ctx, tx, issueIDs, wispIDs); err != nil { + issueIDs, wispIDs, err := createBlockedRecomputeIDs(ctx, tx, issues, depResult.persistedDependencies) + if err != nil { return CreateIssuesResult{}, err } - if len(issueIDs) > 0 { + recomputed, err := RecomputeIsBlockedInTxWithResult(ctx, tx, issueIDs, wispIDs) + if err != nil { + return CreateIssuesResult{}, err + } + if recomputed.IssueRowsChanged { result.markChanged("issues") } - if len(wispIDs) > 0 { + if recomputed.WispRowsChanged { result.markChanged("wisps") } return result, nil @@ -386,7 +416,7 @@ func filterCreateIssuesMixedBucketDependencies(issues []*types.Issue, opts stora return issues, nil } -func createBlockedRecomputeIDs(issues []*types.Issue) ([]string, []string) { +func createBlockedRecomputeIDs(ctx context.Context, tx *sql.Tx, issues []*types.Issue, dependencies []persistedDependency) ([]string, []string, error) { issueSeen := make(map[string]bool, len(issues)) wispSeen := make(map[string]bool, len(issues)) issueIDs := make([]string, 0, len(issues)) @@ -413,18 +443,26 @@ func createBlockedRecomputeIDs(issues []*types.Issue) ([]string, []string) { } isWisp := IsWisp(issue) add(issue.ID, isWisp) - for _, dep := range issue.Dependencies { - if dep == nil { - continue - } - src := dep.IssueID - if src == "" { - src = issue.ID - } - add(src, isWisp) + } + for _, dependency := range dependencies { + var affectedIssues, affectedWisps []string + var err error + if dependency.sourceWisp { + affectedIssues, affectedWisps, err = AffectedByDepChangeForWispInTx(ctx, tx, dependency.source, dependency.target, dependency.depType) + } else { + affectedIssues, affectedWisps, err = AffectedByDepChangeInTx(ctx, tx, dependency.source, dependency.target, dependency.depType) + } + if err != nil { + return nil, nil, fmt.Errorf("affected by created dependency %s -> %s: %w", dependency.source, dependency.target, err) + } + for _, id := range affectedIssues { + add(id, false) + } + for _, id := range affectedWisps { + add(id, true) } } - return issueIDs, wispIDs + return issueIDs, wispIDs, nil } // PrepareIssueForInsert normalizes timestamps, validates, and computes the content hash. @@ -601,7 +639,7 @@ func checkCrossTableIDCollision(ctx context.Context, tx *sql.Tx, id, issueTable // additively (bd-hj85c). // //nolint:gosec // G201: table is a hardcoded constant -func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue *types.Issue, opts storage.BatchCreateOptions) (isNew bool, staleRejected bool, err error) { +func InsertIssueIfNew(ctx context.Context, tx DBTX, issueTable string, issue *types.Issue, opts storage.BatchCreateOptions) (isNew bool, staleRejected bool, err error) { var existingCount int if issue.ID != "" { if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ?`, issueTable), issue.ID).Scan(&existingCount); err != nil { @@ -611,6 +649,15 @@ func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue if opts.ConflictSkip && existingCount > 0 { return false, false, nil // issue already exists — skip, never overwrite } + if opts.CreateOnly { + if err := insertIssueCreateOnly(ctx, tx, issueTable, issue); err != nil { + if isCreateOnlyDuplicateError(err) { + return false, false, fmt.Errorf("%w: %s", storage.ErrAlreadyExists, issue.ID) + } + return false, false, err + } + return true, false, nil + } if opts.RejectStaleUpserts && existingCount > 0 { var storedNewer int if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ? AND updated_at > ?`, issueTable), issue.ID, issue.UpdatedAt).Scan(&storedNewer); err != nil { @@ -628,6 +675,27 @@ func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue return existingCount == 0, false, nil } +func isCreateOnlyDuplicateError(err error) bool { + var mysqlError *mysql.MySQLError + if errors.As(err, &mysqlError) && mysqlError.Number == 1062 { + return true + } + return gmssql.ErrPrimaryKeyViolation.Is(err) || gmssql.ErrUniqueKeyViolation.Is(err) +} + +// InsertIssueStrictInTx inserts one issue without probing either storage plane. +// Callers that move an aggregate use it while the source row necessarily still +// occupies the shared ID, so cross-plane create guards would reject a valid move. +func InsertIssueStrictInTx(ctx context.Context, tx DBTX, table string, issue *types.Issue) error { + if err := insertIssueCreateOnly(ctx, tx, table, issue); err != nil { + if isCreateOnlyDuplicateError(err) { + return fmt.Errorf("%w: %s", storage.ErrAlreadyExists, issue.ID) + } + return err + } + return nil +} + func PersistLabels(ctx context.Context, tx *sql.Tx, issue *types.Issue, actor, eventTable string) (CreateIssueResult, error) { var result CreateIssueResult if len(issue.Labels) == 0 { @@ -764,16 +832,16 @@ func PersistDependenciesWithOptionsResult(ctx context.Context, tx *sql.Tx, issue if len(issue.Dependencies) == 0 { continue } - depTable := "dependencies" - if IsWisp(issue) { - depTable = "wisp_dependencies" - } for _, dep := range issue.Dependencies { // Default IssueID to the owning issue when not pre-set (e.g., // markdown bulk create where the ID is auto-generated). if dep.IssueID == "" { dep.IssueID = issue.ID } + depTable := "dependencies" + if IsActiveWispInTx(ctx, tx, dep.IssueID) { + depTable = "wisp_dependencies" + } pending = append(pending, pendingDependency{dep: dep, depTable: depTable}) } } @@ -835,12 +903,16 @@ func PersistDependenciesWithOptionsResult(ctx context.Context, tx *sql.Tx, issue // merge-safe across clones — two clones importing the same JSONL get the // same primary key, not two random UUIDs that collide on uk_dep_* (#4259). createdBy := dependencyCreatedBy(dep, actor) + metadata := dep.Metadata + if metadata == "" { + metadata = "{}" + } //nolint:gosec // G201: item.depTable is one of two hardcoded constants; target column from DepTargetKind.Column() sqlResult, err := tx.ExecContext(ctx, fmt.Sprintf(` - INSERT INTO %s (id, issue_id, %s, type, created_by, created_at) - VALUES (?, ?, ?, ?, ?, ?) + INSERT INTO %s (id, issue_id, %s, type, created_by, created_at, metadata, thread_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE type = type - `, item.depTable, kind.Column()), depid.New(dep.IssueID, dep.DependsOnID), dep.IssueID, dep.DependsOnID, dep.Type, createdBy, createdAt) + `, item.depTable, kind.Column()), depid.New(dep.IssueID, dep.DependsOnID), dep.IssueID, dep.DependsOnID, dep.Type, createdBy, createdAt, metadata, dep.ThreadID) if err != nil { return result, fmt.Errorf("failed to insert dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err) } @@ -850,6 +922,17 @@ func PersistDependenciesWithOptionsResult(ctx context.Context, tx *sql.Tx, issue } if rowsAffected > 0 { result.markChanged(item.depTable) + result.persistedDependencies = append(result.persistedDependencies, persistedDependency{ + source: dep.IssueID, + target: dep.DependsOnID, + depType: dep.Type, + sourceWisp: item.depTable == "wisp_dependencies", + }) + if dep.Type == types.DepParentChild { + if err := TouchDependencyCoordinationTableInTx(ctx, tx, dep.DependsOnID, item.depTable); err != nil { + return result, err + } + } } } } diff --git a/internal/storage/issueops/create_only_errors_test.go b/internal/storage/issueops/create_only_errors_test.go new file mode 100644 index 000000000..d2157a33d --- /dev/null +++ b/internal/storage/issueops/create_only_errors_test.go @@ -0,0 +1,33 @@ +package issueops + +import ( + "errors" + "fmt" + "testing" + + gmssql "github.com/dolthub/go-mysql-server/sql" + "github.com/go-sql-driver/mysql" +) + +func TestIsCreateOnlyDuplicateError(t *testing.T) { + for _, err := range []error{ + &mysql.MySQLError{Number: 1062, Message: "Duplicate entry"}, + fmt.Errorf("wrapped: %w", &mysql.MySQLError{Number: 1062}), + gmssql.ErrPrimaryKeyViolation.New(), + gmssql.ErrUniqueKeyViolation.New(), + } { + if !isCreateOnlyDuplicateError(err) { + t.Fatalf("isCreateOnlyDuplicateError(%v) = false, want true", err) + } + } +} + +func TestIsCreateOnlyDuplicateErrorPreservesOtherFailures(t *testing.T) { + err := &mysql.MySQLError{Number: 1045, Message: "access denied"} + if isCreateOnlyDuplicateError(err) { + t.Fatal("isCreateOnlyDuplicateError() = true for non-duplicate MySQL error") + } + if isCreateOnlyDuplicateError(errors.New("duplicate wording only")) { + t.Fatal("isCreateOnlyDuplicateError() = true for untyped error") + } +} diff --git a/internal/storage/issueops/create_only_guard.go b/internal/storage/issueops/create_only_guard.go new file mode 100644 index 000000000..cac3a0ddb --- /dev/null +++ b/internal/storage/issueops/create_only_guard.go @@ -0,0 +1,40 @@ +package issueops + +import ( + "context" + "crypto/sha256" + "fmt" + "strconv" + + "github.com/steveyegge/beads/internal/storage" +) + +// EnsureIssueIDAvailableInTx serializes same-shard creates and rejects occupied IDs. +func EnsureIssueIDAvailableInTx(ctx context.Context, tx DBTX, id string) error { + if tx == nil { + return fmt.Errorf("ensure issue ID available: transaction is nil") + } + if id == "" { + return fmt.Errorf("ensure issue ID available: ID is empty") + } + key := issueCreateCoordinationKey(id) + if _, err := tx.ExecContext(ctx, "REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", key, strconv.FormatInt(FreshRowLock(), 10)); err != nil { + return fmt.Errorf("coordinate issue create: %w", err) + } + for _, table := range []string{"issues", "wisps"} { + var count int + if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM "+table+" WHERE id = ?", id).Scan(&count); err != nil { + return fmt.Errorf("check %s for issue %q: %w", table, id, err) + } + if count > 0 { + return fmt.Errorf("%w: %s", storage.ErrAlreadyExists, id) + } + } + return nil +} + +func issueCreateCoordinationKey(id string) string { + sum := sha256.Sum256([]byte(id)) + shard := uint16(sum[0])<<4 | uint16(sum[1])>>4 + return fmt.Sprintf("issue-create/v1/%03x", shard) +} diff --git a/internal/storage/issueops/create_only_guard_test.go b/internal/storage/issueops/create_only_guard_test.go new file mode 100644 index 000000000..2cc67a506 --- /dev/null +++ b/internal/storage/issueops/create_only_guard_test.go @@ -0,0 +1,12 @@ +package issueops + +import ( + "context" + "testing" +) + +func TestEnsureIssueIDAvailableInTxRejectsEmptyID(t *testing.T) { + if err := EnsureIssueIDAvailableInTx(context.Background(), nil, ""); err == nil { + t.Fatal("EnsureIssueIDAvailableInTx() error = nil, want error") + } +} diff --git a/internal/storage/issueops/create_test.go b/internal/storage/issueops/create_test.go index 119ecc00a..33c553d53 100644 --- a/internal/storage/issueops/create_test.go +++ b/internal/storage/issueops/create_test.go @@ -174,7 +174,7 @@ func TestPersistDependenciesHonorsImportedCreatedBy(t *testing.T) { WithArgs("target"). WillReturnRows(sqlmock.NewRows([]string{"1"}).AddRow(1)) mock.ExpectExec("INSERT INTO dependencies"). - WithArgs(depid.New("source", "target"), "source", "target", types.DepRelated, "someone.else", sqlmock.AnyArg()). + WithArgs(depid.New("source", "target"), "source", "target", types.DepRelated, "someone.else", sqlmock.AnyArg(), "{}", ""). WillReturnResult(sqlmock.NewResult(0, 1)) result, err := PersistDependenciesWithOptionsResult(ctx, tx, []*types.Issue{target, source}, "current.user", storage.BatchCreateOptions{}) @@ -216,7 +216,7 @@ func TestPersistDependenciesDefaultsCreatedByToActor(t *testing.T) { WithArgs("target"). WillReturnRows(sqlmock.NewRows([]string{"1"}).AddRow(1)) mock.ExpectExec("INSERT INTO dependencies"). - WithArgs(depid.New("source", "target"), "source", "target", types.DepRelated, "current.user", sqlmock.AnyArg()). + WithArgs(depid.New("source", "target"), "source", "target", types.DepRelated, "current.user", sqlmock.AnyArg(), "{}", ""). WillReturnResult(sqlmock.NewResult(0, 1)) _, err := PersistDependenciesWithOptionsResult(ctx, tx, []*types.Issue{target, source}, "current.user", storage.BatchCreateOptions{}) @@ -251,7 +251,7 @@ func TestPersistDependenciesClassifiesBareCrossPrefixTargetAsExternal(t *testing // A bare target with a different issue prefix is external. In particular, // persistence must not probe either local target table before this insert. mock.ExpectExec("INSERT INTO dependencies \\(id, issue_id, depends_on_external"). - WithArgs(depid.New("sym-3su", "mkt-456"), "sym-3su", "mkt-456", types.DepRelated, "tester", sqlmock.AnyArg()). + WithArgs(depid.New("sym-3su", "mkt-456"), "sym-3su", "mkt-456", types.DepRelated, "tester", sqlmock.AnyArg(), "{}", ""). WillReturnResult(sqlmock.NewResult(0, 1)) result, err := PersistDependenciesWithOptionsResult(ctx, tx, []*types.Issue{source}, "tester", storage.BatchCreateOptions{ @@ -429,8 +429,11 @@ func TestPersistDependenciesValidatesPlannedHierarchyBeforeBlocking(t *testing.T WithArgs(pair[1], pair[0]). WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) mock.ExpectExec("INSERT INTO dependencies"). - WithArgs(depid.New(pair[0], pair[1]), pair[0], pair[1], types.DepParentChild, "tester", sqlmock.AnyArg()). + WithArgs(depid.New(pair[0], pair[1]), pair[0], pair[1], types.DepParentChild, "tester", sqlmock.AnyArg(), "{}", ""). WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("REPLACE INTO local_metadata"). + WithArgs(dependencyCoordinationKey(pair[1], dependencyCoordinationDurableTier), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) } mock.ExpectQuery("SELECT 1 FROM wisps WHERE id = \\? LIMIT 1"). WithArgs("bd-grand"). @@ -475,7 +478,7 @@ func TestPersistDependenciesSkipsHierarchyValidationAcrossPrefixes(t *testing.T) WithArgs("bb-target", "aa-source"). WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) mock.ExpectExec("INSERT INTO dependencies \\(id, issue_id, depends_on_external"). - WithArgs(depid.New("aa-source", "bb-target"), "aa-source", "bb-target", types.DepBlocks, "tester", sqlmock.AnyArg()). + WithArgs(depid.New("aa-source", "bb-target"), "aa-source", "bb-target", types.DepBlocks, "tester", sqlmock.AnyArg(), "{}", ""). WillReturnResult(sqlmock.NewResult(0, 1)) _, err := PersistDependenciesWithOptionsResult(ctx, tx, []*types.Issue{issue}, "tester", storage.BatchCreateOptions{}) diff --git a/internal/storage/issueops/dependencies.go b/internal/storage/issueops/dependencies.go index da3703dc6..5533279ee 100644 --- a/internal/storage/issueops/dependencies.go +++ b/internal/storage/issueops/dependencies.go @@ -154,6 +154,10 @@ type DepTargetPrecheck struct { // Dolt commit stage the events table only when an event row exists, so a // no-event add cannot sweep unrelated pending rows into the commit (GH#2455). func AddDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, actor string, opts AddDependencyOpts) (bool, error) { + return addDependencyInTx(ctx, tx, dep, actor, opts, nil) +} + +func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, actor string, opts AddDependencyOpts, recomputeResult *RecomputeIsBlockedResult) (bool, error) { // Auto-detect source routing if not provided. sourceTable := opts.SourceTable writeTable := opts.WriteTable @@ -273,6 +277,11 @@ func AddDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a `, writeTable, targetCol), depid.New(dep.IssueID, dep.DependsOnID), dep.IssueID, dep.DependsOnID, dep.Type, actor, metadata, dep.ThreadID); err != nil { return false, fmt.Errorf("failed to add dependency: %w", err) } + if dep.Type == types.DepParentChild { + if err := TouchDependencyCoordinationTableInTx(ctx, tx, dep.DependsOnID, writeTable); err != nil { + return false, err + } + } srcIsWisp := writeTable == "wisp_dependencies" @@ -312,9 +321,11 @@ func AddDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a if dep.Type == types.DepParentChild { // Parent-child adds are not monotonic: adding an already-closed child can // satisfy an any-children waits-for gate and unblock the waiter. - if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil { + recomputed, err := RecomputeIsBlockedInTxWithResult(ctx, tx, affectedIssues, affectedWisps) + if err != nil { return false, fmt.Errorf("recompute is_blocked after add dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err) } + mergeRecomputeIsBlockedResult(recomputeResult, recomputed) return eventWritten, nil } if err := MarkIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil { @@ -755,7 +766,7 @@ func nullTimeValue(value sql.NullTime) any { return value.Time } -func RetargetInboundDependenciesToWispInTx(ctx context.Context, tx *sql.Tx, id string) error { +func RetargetInboundDependenciesToWispInTx(ctx context.Context, tx DBTX, id string) error { for _, table := range []string{"dependencies", "wisp_dependencies"} { if err := checkRetargetTargetCollision(ctx, tx, table, "depends_on_issue_id", "depends_on_wisp_id", id); err != nil { return err @@ -774,7 +785,7 @@ func RetargetInboundDependenciesToWispInTx(ctx context.Context, tx *sql.Tx, id s return nil } -func RetargetInboundDependenciesToIssueInTx(ctx context.Context, tx *sql.Tx, id string) error { +func RetargetInboundDependenciesToIssueInTx(ctx context.Context, tx DBTX, id string) error { for _, table := range []string{"dependencies", "wisp_dependencies"} { if err := checkRetargetTargetCollision(ctx, tx, table, "depends_on_wisp_id", "depends_on_issue_id", id); err != nil { return err @@ -807,7 +818,7 @@ func UpdateIssueIDInDependencyTargetsInTx(ctx context.Context, tx *sql.Tx, _, ne } //nolint:gosec // G201: table and typed columns are hardcoded constants. -func checkRetargetTargetCollision(ctx context.Context, tx *sql.Tx, table, sourceCol, destCol, id string) error { +func checkRetargetTargetCollision(ctx context.Context, tx DBTX, table, sourceCol, destCol, id string) error { var conflictCols []string switch destCol { case "depends_on_issue_id": @@ -844,7 +855,7 @@ func checkRetargetTargetCollision(ctx context.Context, tx *sql.Tx, table, source } //nolint:gosec // G201: table and typedCol are hardcoded constants. -func checkRenameTargetCollision(ctx context.Context, tx *sql.Tx, table, typedCol, newID string) error { +func checkRenameTargetCollision(ctx context.Context, tx DBTX, table, typedCol, newID string) error { var otherCols []string switch typedCol { case "depends_on_issue_id": @@ -895,6 +906,10 @@ func checkRenameTargetCollision(ctx context.Context, tx *sql.Tx, table, typedCol // //nolint:gosec // G201: depTable from WispTableRouting (hardcoded constants) func RemoveDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID, actor string, emitEvent bool) (bool, error) { + return removeDependencyInTx(ctx, tx, issueID, dependsOnID, actor, emitEvent, nil) +} + +func removeDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID, actor string, emitEvent bool, recomputeResult *RecomputeIsBlockedResult) (bool, error) { isWisp := IsActiveWispInTx(ctx, tx, issueID) _, _, eventTable, depTable := WispTableRouting(isWisp) @@ -941,12 +956,22 @@ func RemoveDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID, if aerr != nil { return false, fmt.Errorf("affected by remove dependency %s -> %s: %w", issueID, dependsOnID, aerr) } - if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil { + recomputed, err := RecomputeIsBlockedInTxWithResult(ctx, tx, affectedIssues, affectedWisps) + if err != nil { return false, fmt.Errorf("recompute is_blocked after remove dependency %s -> %s: %w", issueID, dependsOnID, err) } + mergeRecomputeIsBlockedResult(recomputeResult, recomputed) return eventWritten, nil } +func mergeRecomputeIsBlockedResult(target *RecomputeIsBlockedResult, source RecomputeIsBlockedResult) { + if target == nil { + return + } + target.IssueRowsChanged = target.IssueRowsChanged || source.IssueRowsChanged + target.WispRowsChanged = target.WispRowsChanged || source.WispRowsChanged +} + // GetIssuesByIDsInTx retrieves multiple issues by ID within an existing // transaction, including labels. Automatically routes each ID to the correct // table (issues/wisps). Uses batched IN clauses. diff --git a/internal/storage/issueops/dependency_coordination.go b/internal/storage/issueops/dependency_coordination.go new file mode 100644 index 000000000..2746d7117 --- /dev/null +++ b/internal/storage/issueops/dependency_coordination.go @@ -0,0 +1,60 @@ +package issueops + +import ( + "context" + "crypto/sha256" + "fmt" + "strconv" +) + +const ( + dependencyCoordinationKeyPrefix = "dependency-coordination/" + dependencyCoordinationKeyVersion = "v1" + dependencyCoordinationDurableTier = "dependencies" + dependencyCoordinationEphemeralTier = "wisp_dependencies" + dependencyCoordinationShardCount = 1 << 12 +) + +// touchDependencyCoordinationInTx rewrites the coordination cells for both +// dependency tables in a fixed order. Writers that need a stable view of an +// issue's incoming parent-child edges use these cells to make concurrent Dolt +// transactions conflict rather than cell-merge. +func touchDependencyCoordinationInTx(ctx context.Context, tx DBTX, parentID string) error { + for _, tier := range [2]string{dependencyCoordinationDurableTier, dependencyCoordinationEphemeralTier} { + if err := TouchDependencyCoordinationTableInTx(ctx, tx, parentID, tier); err != nil { + return err + } + } + return nil +} + +// TouchDependencyCoordinationTableInTx rewrites the coordination cell for one +// dependency table. table must be dependencies or wisp_dependencies. +func TouchDependencyCoordinationTableInTx(ctx context.Context, tx DBTX, parentID, table string) error { + if parentID == "" { + return fmt.Errorf("touch dependency coordination: parent ID must not be empty") + } + if table != dependencyCoordinationDurableTier && table != dependencyCoordinationEphemeralTier { + return fmt.Errorf("touch dependency coordination: unsupported table %q", table) + } + key := dependencyCoordinationKey(parentID, table) + if _, err := tx.ExecContext(ctx, + "REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", key, strconv.FormatInt(FreshRowLock(), 10)); err != nil { + return fmt.Errorf("touch dependency coordination for %s: %w", table, err) + } + return nil +} + +func dependencyCoordinationKey(parentID, table string) string { + shard := dependencyCoordinationShard(parentID) + // A tier has 4096 shard rows: enough to keep unrelated writes apart while + // bounding the clone-local coordination state at 8192 rows. Same-parent + // operations always resolve to the same shard; a hash collision only adds a + // safe serialization conflict. + return fmt.Sprintf("%s%s/%s/%03x", dependencyCoordinationKeyPrefix, dependencyCoordinationKeyVersion, table, shard) +} + +func dependencyCoordinationShard(parentID string) uint16 { + sum := sha256.Sum256([]byte(parentID)) + return uint16(sum[0])<<4 | uint16(sum[1])>>4 +} diff --git a/internal/storage/issueops/dependency_coordination_test.go b/internal/storage/issueops/dependency_coordination_test.go new file mode 100644 index 000000000..fe6eb3f9e --- /dev/null +++ b/internal/storage/issueops/dependency_coordination_test.go @@ -0,0 +1,68 @@ +package issueops + +import ( + "context" + "fmt" + "regexp" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" +) + +func TestDependencyCoordinationKeyShardProperties(t *testing.T) { + t.Parallel() + + const parent = "bd-sensitive-parent-id" + durable := dependencyCoordinationKey(parent, dependencyCoordinationDurableTier) + if got := dependencyCoordinationKey(parent, dependencyCoordinationDurableTier); got != durable { + t.Fatalf("durable key is not deterministic: first %q, second %q", durable, got) + } + wisp := dependencyCoordinationKey(parent, dependencyCoordinationEphemeralTier) + if durable == wisp { + t.Fatalf("tier keys collide: %q", durable) + } + for _, key := range []string{durable, wisp} { + if len(key) >= 255 { + t.Fatalf("key length = %d, want < 255: %q", len(key), key) + } + if strings.Contains(key, parent) { + t.Fatalf("key exposes parent ID: %q", key) + } + } + if dependencyCoordinationShardCount != 4096 { + t.Fatalf("shard count = %d, want 4096", dependencyCoordinationShardCount) + } + seen := make(map[uint16]struct{}) + for i := 0; i < 8192; i++ { + shard := dependencyCoordinationShard(fmt.Sprintf("parent-%d", i)) + if shard >= dependencyCoordinationShardCount { + t.Fatalf("shard = %d, want < %d", shard, dependencyCoordinationShardCount) + } + seen[shard] = struct{}{} + } + if len(seen) > dependencyCoordinationShardCount { + t.Fatalf("distinct shards = %d, want <= %d", len(seen), dependencyCoordinationShardCount) + } +} + +func TestTouchDependencyCoordinationInTxTouchesTiersInOrder(t *testing.T) { + t.Parallel() + + _, mock, tx := beginMockTx(t) + const parent = "coordination-parent" + query := regexp.QuoteMeta("REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)") + mock.ExpectExec(query). + WithArgs(dependencyCoordinationKey(parent, dependencyCoordinationDurableTier), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectExec(query). + WithArgs(dependencyCoordinationKey(parent, dependencyCoordinationEphemeralTier), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) + + if err := touchDependencyCoordinationInTx(context.Background(), tx, parent); err != nil { + t.Fatalf("touchDependencyCoordinationInTx: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("coordination touch expectations: %v", err) + } +} diff --git a/internal/storage/issueops/execution.go b/internal/storage/issueops/execution.go new file mode 100644 index 000000000..acdef5b04 --- /dev/null +++ b/internal/storage/issueops/execution.go @@ -0,0 +1,279 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ExecuteCreate applies a guarded create in tx and reports durable tables changed. +func ExecuteCreate(ctx context.Context, tx *sql.Tx, request publicops.CreateRequest) (publicops.CreateResult, ChangedTables, error) { + attempt := CloneCreateRequest(request) + if err := ValidatePublicCreateRequest(attempt); err != nil { + return publicops.CreateResult{}, nil, err + } + batch, err := NewBatchContext(ctx, tx, storage.BatchCreateOptions{CreateOnly: true, OrphanHandling: storage.OrphanAllow, SkipPrefixValidation: attempt.ForceIDPrefix}) + if err != nil { + return publicops.CreateResult{}, nil, err + } + attempt, err = PreparePublicCreateRequest(attempt, PublicCreateContext{ + IssuePrefix: batch.ConfigPrefix, AllowedPrefixes: batch.AllowedPrefixes, + CustomStatuses: batch.CustomStatuses, CustomTypes: batch.CustomTypes, + }) + if err != nil { + return publicops.CreateResult{}, nil, err + } + issue := attempt.Issue + // Configured infra types live in the wisp tables, the same routing the + // stores' own CreateIssue applies (internal/storage/dolt/issues.go). Mark + // the issue before its ID is assigned so ID generation, the create-only + // guard, and table routing all agree on the destination. A no-history + // create keeps its own retention mode. + if !issue.Ephemeral && !issue.NoHistory && ResolveInfraTypesInTx(ctx, tx)[string(issue.IssueType)] { + issue.Ephemeral = true + } + if attempt.InheritLabelsFromParent && attempt.ParentID != "" { + labels, err := GetLabelsInTx(ctx, tx, "", attempt.ParentID) + if err != nil { + return publicops.CreateResult{}, nil, err + } + issue.Labels = append(issue.Labels, labels...) + } + childCounterChanged := false + if issue.ID == "" && attempt.ParentID != "" { + parentIsWisp := IsActiveWispInTx(ctx, tx, attempt.ParentID) + issue.ID, err = GetNextChildIDTx(ctx, tx, attempt.ParentID) + if err != nil { + return publicops.CreateResult{}, nil, ClassifyPublicCreateError(err) + } + childCounterChanged = !parentIsWisp + } + if err := assignCreateIssueIDInTx(ctx, tx, batch, issue, attempt.Actor); err != nil { + return publicops.CreateResult{}, nil, ClassifyPublicCreateError(err) + } + issue.Dependencies = storage.CreatePublicCreateDependencies(issue.ID, attempt) + var skipped []skippedDependency + created, err := CreateIssuesInTxWithResult(ctx, tx, []*types.Issue{issue}, attempt.Actor, storage.BatchCreateOptions{ + CreateOnly: true, OrphanHandling: storage.OrphanAllow, SkipPrefixValidation: attempt.ForceIDPrefix, + OnSkippedDependency: func(issueID, dependsOnID, reason string) { + skipped = append(skipped, skippedDependency{issueID: issueID, dependsOnID: dependsOnID, reason: reason}) + }, + }) + if err != nil { + return publicops.CreateResult{}, nil, ClassifyPublicCreateError(err) + } + if len(skipped) > 0 { + return publicops.CreateResult{}, nil, publicCreateValidationError(skippedDependencyError(skipped)) + } + tables := ChangedTables{} + tables.Merge(CreateIssuesDirtyTables(ctx, []*types.Issue{issue}, created)) + if childCounterChanged { + tables.Add("child_counters") + } + hydrated, err := HydrateIssueOperationResult(ctx, tx, issue.ID, true) + if err != nil { + return publicops.CreateResult{}, nil, err + } + return publicops.CreateResult{Issue: hydrated}, tables, nil +} + +// skippedDependency records an edge the batch engine declined to write. +type skippedDependency struct{ issueID, dependsOnID, reason string } + +// skippedDependencyError refuses a guarded create whose requested edges were +// not all written. The batch engine drops a dangling edge so a partial import +// still lands, but a guarded create that reported success while silently +// discarding a parent, waits-for, or explicit dependency is data loss: the +// caller has no way to learn the relationship is missing. Refusing rolls the +// whole create back with the enclosing transaction. +func skippedDependencyError(skipped []skippedDependency) error { + edges := make([]string, 0, len(skipped)) + for _, edge := range skipped { + edges = append(edges, fmt.Sprintf("%s -> %s (%s)", edge.issueID, edge.dependsOnID, edge.reason)) + } + return fmt.Errorf("create: dependencies could not be created: %s: %w", strings.Join(edges, "; "), storage.ErrNotFound) +} + +// ExecuteUpdate applies a guarded update in tx and reports durable tables changed. +func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequest) (publicops.UpdateResult, ChangedTables, error) { + attempt := CloneUpdateRequest(request) + if attempt.Actor == "" || attempt.IssueID == "" { + return publicops.UpdateResult{}, nil, fmt.Errorf("%w: update requires actor and issue ID", storage.ErrValidation) + } + if err := ValidateUpdateRequest(attempt); err != nil { + return publicops.UpdateResult{}, nil, err + } + if err := ValidateMetadataPatch(attempt.Patch.Metadata); err != nil { + return publicops.UpdateResult{}, nil, err + } + tables := ChangedTables{} + before, err := GetIssueInTx(ctx, tx, attempt.IssueID) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if attempt.ExpectedVersion != nil { + if err := CheckVersionInTx(ctx, tx, attempt.IssueID, *attempt.ExpectedVersion); err != nil { + return publicops.UpdateResult{}, nil, err + } + } + if attempt.ExpectedStatus != nil { + status := string(*attempt.ExpectedStatus) + attempt.ExpectedStatus = nil + if err := CheckExpectedFieldsInTx(ctx, tx, attempt.IssueID, attempt.ExpectedAssignee, &status); err != nil { + return publicops.UpdateResult{}, nil, err + } + } else if err := CheckExpectedFieldsInTx(ctx, tx, attempt.IssueID, attempt.ExpectedAssignee, nil); err != nil { + return publicops.UpdateResult{}, nil, err + } + if err := AuthorizeAssigneeTransfer(ctx, tx, before, attempt); err != nil { + return publicops.UpdateResult{}, nil, err + } + changedAny := false + if attempt.Claim { + claimed, err := ClaimIssueInTx(ctx, tx, attempt.IssueID, attempt.Actor) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if claimed.OldIssue.Status != types.StatusInProgress || claimed.OldIssue.Assignee != attempt.Actor { + changedAny = true + issueTable, _, eventTable, _ := WispTableRouting(claimed.IsWisp) + tables.Add(issueTable, eventTable) + } + } + current := before + if attempt.Claim { + current, err = GetIssueInTx(ctx, tx, attempt.IssueID) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + } + updates := UpdateFields(attempt.Patch) + // A metadata patch rides the same row write as the field edits. Writing it + // separately recorded a second event for one atomic mutation, fabricating + // an update that never happened for every consumer of the event stream. + // ApplyMetadataPatch already resolved the patch against the in-transaction + // row, so the concrete value goes in alongside the other columns and its + // no-op elision is preserved by the changed flag. + metadata, metadataChanged, err := ApplyMetadataPatch(current.Metadata, attempt.Patch.Metadata) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if metadataChanged { + updates["metadata"] = metadata + } + if len(updates) > 0 { + updated, err := UpdateIssueInTx(ctx, tx, attempt.IssueID, updates, attempt.Actor) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if updated.Changed { + changedAny = true + issueTable, _, eventTable, _ := WispTableRouting(updated.IsWisp) + tables.Add(issueTable, eventTable) + if updated.IssueRowsChanged { + tables.Add("issues") + } + } + } + labelsChanged, err := ApplyLabelPatch(ctx, tx, current, attempt.Patch.Labels, attempt.Actor) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if labelsChanged { + changedAny = true + _, labelTable, eventTable, _ := WispTableRouting(IsActiveWispInTx(ctx, tx, attempt.IssueID)) + tables.Add(labelTable, eventTable) + } + parentResult, err := ApplyParentPatch(ctx, tx, current, attempt.Patch.ParentID, attempt.Actor) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if parentResult.Changed { + changedAny = true + _, _, _, dependencyTable := WispTableRouting(IsActiveWispInTx(ctx, tx, attempt.IssueID)) + tables.Add(dependencyTable) + if parentResult.IssueRowsChanged { + tables.Add("issues") + } + } + if attempt.Patch.Persistence.Set { + current, err := GetIssueInTx(ctx, tx, attempt.IssueID) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + moved, err := MoveIssuePersistenceInTx(ctx, tx, current, attempt.Patch.Persistence.Value) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + if moved.Changed { + changedAny = true + tables.Merge(moved.ChangedTables) + } + } + hydrated, err := HydrateIssueOperationResult(ctx, tx, attempt.IssueID, false) + if err != nil { + return publicops.UpdateResult{}, nil, err + } + return publicops.UpdateResult{Issue: hydrated, Changed: changedAny}, tables, nil +} + +// ExecuteClose applies a guarded close in tx and reports durable tables changed. +func ExecuteClose(ctx context.Context, tx *sql.Tx, request publicops.CloseRequest) (publicops.CloseResult, ChangedTables, error) { + attempt := CloneCloseRequest(request) + if attempt.Actor == "" || attempt.IssueID == "" { + return publicops.CloseResult{}, nil, fmt.Errorf("%w: close requires actor and issue ID", storage.ErrValidation) + } + closed, err := CloseIssueCheckedInTx(ctx, tx, attempt.IssueID, attempt.Reason, attempt.Actor, attempt.Session, attempt.Force, attempt.ExpectedVersion) + if err != nil { + return publicops.CloseResult{}, nil, err + } + tables := ChangedTables{} + changed := !closed.AlreadyClosed + if changed { + issueTable, _, eventTable, _ := WispTableRouting(closed.IsWisp) + tables.Add(issueTable, eventTable) + } + if closed.IssueRowsChanged { + tables.Add("issues") + } + hydrated, err := HydrateIssueOperationResult(ctx, tx, attempt.IssueID, false) + if err != nil { + return publicops.CloseResult{}, nil, err + } + return publicops.CloseResult{Issue: hydrated, Changed: changed, OpenChildren: closed.OpenChildren}, tables, nil +} + +// ExecuteReopen applies a guarded reopen in tx and reports durable tables changed. +func ExecuteReopen(ctx context.Context, tx *sql.Tx, request publicops.ReopenRequest) (publicops.ReopenResult, ChangedTables, error) { + attempt := CloneReopenRequest(request) + if attempt.Actor == "" || attempt.IssueID == "" { + return publicops.ReopenResult{}, nil, fmt.Errorf("%w: reopen requires actor and issue ID", storage.ErrValidation) + } + if attempt.ExpectedVersion != nil { + if err := CheckVersionInTx(ctx, tx, attempt.IssueID, *attempt.ExpectedVersion); err != nil { + return publicops.ReopenResult{}, nil, err + } + } + reopened, err := ReopenIssueInTx(ctx, tx, attempt.IssueID, attempt.Reason, attempt.Actor) + if err != nil { + return publicops.ReopenResult{}, nil, err + } + tables := ChangedTables{} + if reopened.Changed { + issueTable, _, eventTable, _ := WispTableRouting(reopened.IsWisp) + tables.Add(issueTable, eventTable) + } + if reopened.IssueRowsChanged { + tables.Add("issues") + } + hydrated, err := HydrateIssueOperationResult(ctx, tx, attempt.IssueID, false) + if err != nil { + return publicops.ReopenResult{}, nil, err + } + return publicops.ReopenResult{Issue: hydrated, Changed: reopened.Changed}, tables, nil +} diff --git a/internal/storage/issueops/helpers.go b/internal/storage/issueops/helpers.go index a7e6848b0..a637303c4 100644 --- a/internal/storage/issueops/helpers.go +++ b/internal/storage/issueops/helpers.go @@ -56,7 +56,7 @@ var issueUpsertColumns = []string{ "content_hash", "title", "description", "design", "acceptance_criteria", "notes", "status", "priority", "issue_type", "assignee", "estimated_minutes", "started_at", "closed_at", "external_ref", - "source_repo", "close_reason", "metadata", + "source_repo", "close_reason", "closed_by_session", "metadata", "row_lock", "updated_at", } @@ -90,12 +90,22 @@ func issueUpsertAssignments(table string, rejectStaleUpdate bool) string { // InsertIssueIntoTable inserts an issue into the specified table ("issues" or "wisps"), // using ON DUPLICATE KEY UPDATE to handle pre-existing records gracefully. -func InsertIssueIntoTable(ctx context.Context, tx *sql.Tx, table string, issue *types.Issue) error { +func InsertIssueIntoTable(ctx context.Context, tx DBTX, table string, issue *types.Issue) error { return insertIssueIntoTable(ctx, tx, table, issue, false) } //nolint:gosec // G201: table is a hardcoded constant ("issues" or "wisps") -func insertIssueIntoTable(ctx context.Context, tx *sql.Tx, table string, issue *types.Issue, rejectStaleUpdate bool) error { +func insertIssueIntoTable(ctx context.Context, tx DBTX, table string, issue *types.Issue, rejectStaleUpdate bool) error { + return executeIssueInsert(ctx, tx, table, issue, "ON DUPLICATE KEY UPDATE\n\t\t\t"+issueUpsertAssignments(table, rejectStaleUpdate)) +} + +//nolint:gosec // G201: table is a hardcoded constant ("issues" or "wisps") +func insertIssueCreateOnly(ctx context.Context, tx DBTX, table string, issue *types.Issue) error { + return executeIssueInsert(ctx, tx, table, issue, "") +} + +//nolint:gosec // G201: table is a hardcoded constant ("issues" or "wisps") +func executeIssueInsert(ctx context.Context, tx DBTX, table string, issue *types.Issue, suffix string) error { _, err := tx.ExecContext(ctx, fmt.Sprintf(` INSERT INTO %s ( id, content_hash, title, description, design, acceptance_criteria, notes, @@ -103,14 +113,14 @@ func insertIssueIntoTable(ctx context.Context, tx *sql.Tx, table string, issue * created_at, created_by, owner, updated_at, started_at, closed_at, external_ref, spec_id, compaction_level, compacted_at, compacted_at_commit, original_size, sender, ephemeral, no_history, wisp_type, pinned, is_template, - mol_type, work_type, source_system, source_repo, close_reason, + mol_type, work_type, source_system, source_repo, close_reason, closed_by_session, event_kind, actor, target, payload, await_type, await_id, timeout_ns, waiters, due_at, defer_until, metadata, row_lock, storage_class ) VALUES ( ?, ?, ?, ?, ?, ?, ?, - ?, ?, ?, ?, ?, + ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @@ -120,15 +130,14 @@ func insertIssueIntoTable(ctx context.Context, tx *sql.Tx, table string, issue * ?, ?, ?, ?, ? ) - ON DUPLICATE KEY UPDATE - %s - `, table, issueUpsertAssignments(table, rejectStaleUpdate)), + %s + `, table, suffix), issue.ID, issue.ContentHash, issue.Title, issue.Description, issue.Design, issue.AcceptanceCriteria, issue.Notes, issue.Status, issue.Priority, issue.IssueType, NullString(issue.Assignee), NullInt(issue.EstimatedMinutes), issue.CreatedAt, issue.CreatedBy, issue.Owner, issue.UpdatedAt, issue.StartedAt, issue.ClosedAt, NullStringPtr(issue.ExternalRef), issue.SpecID, issue.CompactionLevel, issue.CompactedAt, NullStringPtr(issue.CompactedAtCommit), NullIntVal(issue.OriginalSize), issue.Sender, issue.Ephemeral, issue.NoHistory, issue.WispType, issue.Pinned, issue.IsTemplate, - issue.MolType, issue.WorkType, issue.SourceSystem, issue.SourceRepo, issue.CloseReason, + issue.MolType, issue.WorkType, issue.SourceSystem, issue.SourceRepo, issue.CloseReason, issue.ClosedBySession, issue.EventKind, issue.Actor, issue.Target, issue.Payload, issue.AwaitType, issue.AwaitID, issue.Timeout.Nanoseconds(), FormatJSONStringArray(issue.Waiters), issue.DueAt, issue.DeferUntil, JSONMetadata(issue.Metadata), diff --git a/internal/storage/issueops/persistence.go b/internal/storage/issueops/persistence.go new file mode 100644 index 000000000..4ff79eb18 --- /dev/null +++ b/internal/storage/issueops/persistence.go @@ -0,0 +1,210 @@ +package issueops + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/types" +) + +// PersistenceMoveResult reports the durable tables changed by a persistence move. +type PersistenceMoveResult struct { + Changed bool + ChangedTables map[string]bool +} + +// MoveIssuePersistenceInTx moves a complete issue aggregate to the requested persistence mode. +func MoveIssuePersistenceInTx(ctx context.Context, tx DBTX, current *types.Issue, mode types.PersistenceMode) (PersistenceMoveResult, error) { + if tx == nil || current == nil || current.ID == "" { + return PersistenceMoveResult{}, fmt.Errorf("move issue persistence: issue and transaction are required") + } + ephemeral, noHistory, storageClass, err := types.NormalizePersistenceMode(*current, mode) + if err != nil { + return PersistenceMoveResult{}, err + } + sourceWisp, err := isActiveWispForPersistenceMove(ctx, tx, current.ID) + if err != nil { + return PersistenceMoveResult{}, err + } + targetWisp := ephemeral || noHistory + if sourceWisp == targetWisp && current.Ephemeral == ephemeral && current.NoHistory == noHistory && current.StorageClass.Normalize() == storageClass.Normalize() { + return PersistenceMoveResult{}, nil + } + result := PersistenceMoveResult{Changed: true, ChangedTables: map[string]bool{}} + if sourceWisp == targetWisp { + if _, err := tx.ExecContext(ctx, `UPDATE wisps SET ephemeral = ?, no_history = ?, storage_class = ?, row_lock = ? WHERE id = ?`, ephemeral, noHistory, storageClass.Normalize(), FreshRowLock(), current.ID); err != nil { + return PersistenceMoveResult{}, fmt.Errorf("normalize local issue persistence: %w", err) + } + result.ChangedTables["wisps"] = true + return result, nil + } + if !sourceWisp && targetWisp { + if err := rejectPersistenceDemotion(ctx, tx, current.ID); err != nil { + return PersistenceMoveResult{}, err + } + } + move := *current + move.Ephemeral, move.NoHistory, move.StorageClass, move.RowVersion = ephemeral, noHistory, storageClass, FreshRowLock() + if err := InsertIssueStrictInTx(ctx, tx, persistenceIssueTable(targetWisp), &move); err != nil { + return PersistenceMoveResult{}, fmt.Errorf("insert moved issue %s: %w", current.ID, err) + } + auxTables, err := copyPersistenceAuxiliary(ctx, tx, current.ID, sourceWisp, targetWisp) + if err != nil { + return PersistenceMoveResult{}, err + } + for table := range auxTables { + result.ChangedTables[table] = true + } + if targetWisp { + inboundTables, err := inboundPersistenceDependencyTables(ctx, tx, current.ID, "depends_on_issue_id") + if err != nil { + return PersistenceMoveResult{}, err + } + if err := RetargetInboundDependenciesToWispInTx(ctx, tx, current.ID); err != nil { + return PersistenceMoveResult{}, err + } + for table := range inboundTables { + result.ChangedTables[table] = true + } + if err := DeleteLeaseInTx(ctx, tx, current.ID); err != nil { + return PersistenceMoveResult{}, err + } + } else { + inboundTables, err := inboundPersistenceDependencyTables(ctx, tx, current.ID, "depends_on_wisp_id") + if err != nil { + return PersistenceMoveResult{}, err + } + if err := RetargetInboundDependenciesToIssueInTx(ctx, tx, current.ID); err != nil { + return PersistenceMoveResult{}, err + } + for table := range inboundTables { + result.ChangedTables[table] = true + } + } + if _, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE id = ?`, persistenceIssueTable(sourceWisp)), current.ID); err != nil { + return PersistenceMoveResult{}, fmt.Errorf("delete moved issue %s: %w", current.ID, err) + } + issues, wisps, err := affectedForPersistenceMove(ctx, tx, current.ID, targetWisp) + if err != nil { + return PersistenceMoveResult{}, err + } + recompute, err := RecomputeIsBlockedInTxWithResult(ctx, tx, issues, wisps) + if err != nil { + return PersistenceMoveResult{}, fmt.Errorf("recompute blocked state: %w", err) + } + if recompute.IssueRowsChanged { + result.ChangedTables["issues"] = true + } + if recompute.WispRowsChanged { + result.ChangedTables["wisps"] = true + } + result.ChangedTables[persistenceIssueTable(sourceWisp)] = true + result.ChangedTables[persistenceIssueTable(targetWisp)] = true + return result, nil +} + +func persistenceIssueTable(wisp bool) string { + if wisp { + return "wisps" + } + return "issues" +} + +func rejectPersistenceDemotion(ctx context.Context, tx DBTX, id string) error { + for _, table := range []string{"issue_snapshots", "compaction_snapshots"} { + var count int + if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE issue_id = ?`, table), id).Scan(&count); err != nil { + return fmt.Errorf("check retained snapshots in %s: %w", table, err) + } + if count > 0 { + return fmt.Errorf("cannot demote issue %s with retained snapshots", id) + } + } + return nil +} + +func copyPersistenceAuxiliary(ctx context.Context, tx DBTX, id string, sourceWisp, targetWisp bool) (map[string]bool, error) { + changed := map[string]bool{} + for i, from := range persistenceAuxTables(sourceWisp) { + to := persistenceAuxTables(targetWisp)[i] + columns, key, err := persistenceColumns(from) + if err != nil { + return nil, err + } + copied, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO %s (%s) SELECT %s FROM %s WHERE %s = ?`, to, columns, columns, from, key), id) + if err != nil { + return nil, fmt.Errorf("copy %s: %w", from, err) + } + if rows, err := copied.RowsAffected(); err == nil && rows > 0 { + changed[from], changed[to] = true, true + } + deleted, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE %s = ?`, from, key), id) + if err != nil { + return nil, fmt.Errorf("delete %s: %w", from, err) + } + _ = deleted + } + return changed, nil +} + +func isActiveWispForPersistenceMove(ctx context.Context, tx DBTX, id string) (bool, error) { + var wispCount, issueCount int + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisps WHERE id = ?`, id).Scan(&wispCount); err != nil { + return false, fmt.Errorf("locate issue persistence plane: %w", err) + } + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM issues WHERE id = ?`, id).Scan(&issueCount); err != nil { + return false, fmt.Errorf("locate issue persistence plane: %w", err) + } + if issueCount > 0 && wispCount > 0 { + return false, fmt.Errorf("locate issue persistence plane: ID %q exists in both issues and wisps", id) + } + return wispCount > 0, nil +} + +func persistenceAuxTables(wisp bool) []string { + if wisp { + return []string{"wisp_labels", "wisp_dependencies", "wisp_events", "wisp_comments", "wisp_child_counters"} + } + return []string{"labels", "dependencies", "events", "comments", "child_counters"} +} + +func inboundPersistenceDependencyTables(ctx context.Context, tx DBTX, id, targetColumn string) (map[string]bool, error) { + if targetColumn != "depends_on_issue_id" && targetColumn != "depends_on_wisp_id" { + return nil, fmt.Errorf("unknown dependency target column %q", targetColumn) + } + changed := map[string]bool{} + for _, table := range []string{"dependencies", "wisp_dependencies"} { + var count int + if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE %s = ?`, table, targetColumn), id).Scan(&count); err != nil { + return nil, fmt.Errorf("find inbound dependencies in %s: %w", table, err) + } + if count > 0 { + changed[table] = true + } + } + return changed, nil +} + +func persistenceColumns(table string) (string, string, error) { + switch table { + case "labels", "wisp_labels": + return "issue_id, label", "issue_id", nil + case "dependencies", "wisp_dependencies": + return "id, issue_id, depends_on_issue_id, depends_on_wisp_id, depends_on_external, type, created_at, created_by, metadata, thread_id", "issue_id", nil + case "events", "wisp_events": + return "id, issue_id, event_type, actor, old_value, new_value, comment, created_at", "issue_id", nil + case "comments", "wisp_comments": + return "id, issue_id, author, text, created_at", "issue_id", nil + case "child_counters", "wisp_child_counters": + return "parent_id, last_child", "parent_id", nil + default: + return "", "", fmt.Errorf("unknown persistence table %q", table) + } +} + +func affectedForPersistenceMove(ctx context.Context, tx DBTX, id string, targetWisp bool) ([]string, []string, error) { + if targetWisp { + return AffectedByStatusChangeForWispInTx(ctx, tx, id) + } + return AffectedByStatusChangeInTx(ctx, tx, id) +} diff --git a/internal/storage/issueops/public_create.go b/internal/storage/issueops/public_create.go new file mode 100644 index 000000000..e4bfa1ddd --- /dev/null +++ b/internal/storage/issueops/public_create.go @@ -0,0 +1,200 @@ +package issueops + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/dberrors" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// PublicCreateContext holds the configuration required to prepare a public +// create request for the domain create use case. +type PublicCreateContext struct { + IssuePrefix string + AllowedPrefixes string + CustomStatuses []string + CustomTypes []string +} + +// ValidatePublicCreateRequest checks public-create invariants independent of +// database configuration. +func ValidatePublicCreateRequest(request publicops.CreateRequest) error { + if request.Actor == "" || request.Issue == nil { + return publicCreateValidationError(fmt.Errorf("create: actor and issue are required")) + } + if err := types.CheckFieldLen("actor", request.Actor); err != nil { + return publicCreateValidationError(fmt.Errorf("create: %w", err)) + } + if len(request.Issue.Comments) > 0 || len(request.Issue.Dependencies) > 0 { + return publicCreateValidationError(fmt.Errorf("create: issue comments and dependencies must be supplied through request fields")) + } + for _, field := range []struct{ name, value string }{{"assignee", request.Issue.Assignee}, {"owner", request.Issue.Owner}} { + if err := types.CheckFieldLen(field.name, field.value); err != nil { + return publicCreateValidationError(err) + } + } + for _, label := range request.Issue.Labels { + if err := types.CheckFieldLen("label", label); err != nil { + return publicCreateValidationError(err) + } + } + if err := types.CheckFieldLen("parent ID", request.ParentID); err != nil { + return publicCreateValidationError(fmt.Errorf("create: %w", err)) + } + return validatePublicCreateDependencies(request) +} + +// PreparePublicCreateRequest snapshots, normalizes, and validates a public +// create request using the supplied configuration. +func PreparePublicCreateRequest(request publicops.CreateRequest, context PublicCreateContext) (publicops.CreateRequest, error) { + request = CloneCreateRequest(request) + if err := ValidatePublicCreateRequest(request); err != nil { + return publicops.CreateRequest{}, err + } + issue := publicCreateIssue(request.Issue) + if issue.Status == "" { + issue.Status = types.StatusOpen + } + if issue.ID != "" && !request.ForceIDPrefix { + if err := ValidateIssueIDPrefix(issue.ID, strings.TrimSuffix(context.IssuePrefix, "-"), context.AllowedPrefixes); err != nil { + return publicops.CreateRequest{}, publicCreateValidationError(err) + } + } + if err := PrepareIssueForInsert(issue, context.CustomStatuses, context.CustomTypes); err != nil { + return publicops.CreateRequest{}, publicCreateValidationError(err) + } + prepared := request + prepared.Issue = issue + if prepared.WaitsFor != nil && prepared.WaitsFor.Gate == "" { + prepared.WaitsFor.Gate = string(types.WaitsForAllChildren) + } + if err := ValidatePublicCreateRequest(prepared); err != nil { + return publicops.CreateRequest{}, err + } + return prepared, nil +} + +// ClassifyPublicCreateError adds ErrValidation only to known deterministic +// public-create failures and leaves infrastructure and commit errors intact. +func ClassifyPublicCreateError(err error) error { + if err == nil || errors.Is(err, storage.ErrValidation) || errors.Is(err, storage.ErrAlreadyExists) { + return err + } + var conflict *domain.DependencyTypeConflictError + var hierarchyConflict *domain.DependencyHierarchyConflictError + var stateErr interface{ SQLState() string } + if errors.As(err, &stateErr) && stateErr.SQLState() == "23505" { + return fmt.Errorf("%w: %w", storage.ErrAlreadyExists, err) + } + if errors.Is(err, storage.ErrPrefixMismatch) || errors.Is(err, domain.ErrSelfDependency) || errors.Is(err, types.ErrFieldTooLong) || errors.Is(err, domain.ErrDependencyCycle) || errors.As(err, &conflict) || errors.As(err, &hierarchyConflict) { + return publicCreateValidationError(err) + } + // A create whose requested relationship names a row that does not exist + // fails the dependency table's target foreign key. The caller asked for an + // edge to something absent, so this is a deterministic refusal rather than + // an infrastructure error: classify it the same way ExecuteCreate refuses a + // skipped dependency, so every backend reports a missing dependency, + // parent, or waits-for target as ErrValidation wrapping ErrNotFound. + if dberrors.IsMissingForeignKeyTarget(err) { + return publicCreateValidationError(fmt.Errorf("create: dependency target does not exist: %w: %w", err, storage.ErrNotFound)) + } + return err +} + +func publicCreateValidationError(err error) error { + return fmt.Errorf("%w: %w", storage.ErrValidation, err) +} + +func publicCreateIssue(source *types.Issue) *types.Issue { + return &types.Issue{ + ID: source.ID, Title: source.Title, Description: source.Description, Design: source.Design, + AcceptanceCriteria: source.AcceptanceCriteria, Notes: source.Notes, SpecID: source.SpecID, + Status: source.Status, Priority: source.Priority, IssueType: source.IssueType, + Assignee: source.Assignee, Owner: source.Owner, EstimatedMinutes: cloneInt(source.EstimatedMinutes), + CreatedAt: source.CreatedAt, CreatedBy: source.CreatedBy, UpdatedAt: source.UpdatedAt, + StartedAt: cloneTime(source.StartedAt), ClosedAt: cloneTime(source.ClosedAt), CloseReason: source.CloseReason, ClosedBySession: source.ClosedBySession, + DueAt: cloneTime(source.DueAt), DeferUntil: cloneTime(source.DeferUntil), ExternalRef: cloneString(source.ExternalRef), SourceSystem: source.SourceSystem, SourceRepo: source.SourceRepo, + Metadata: cloneRawMessage(source.Metadata), Labels: append([]string(nil), source.Labels...), Sender: source.Sender, + Ephemeral: source.Ephemeral, NoHistory: source.NoHistory, WispType: source.WispType, StorageClass: source.StorageClass, + Pinned: source.Pinned, IsTemplate: source.IsTemplate, BondedFrom: append([]types.BondRef(nil), source.BondedFrom...), + AwaitType: source.AwaitType, AwaitID: source.AwaitID, Timeout: source.Timeout, Waiters: append([]string(nil), source.Waiters...), + SourceFormula: source.SourceFormula, SourceLocation: source.SourceLocation, MolType: source.MolType, WorkType: source.WorkType, + EventKind: source.EventKind, Actor: source.Actor, Target: source.Target, Payload: source.Payload, + } +} + +func validatePublicCreateDependencies(request publicops.CreateRequest) error { + type endpoint struct { + newIssue bool + id string + } + type edge struct { + source endpoint + target endpoint + typ types.DependencyType + } + newIssue := endpoint{newIssue: true} + endpointFor := func(id string) endpoint { + if request.Issue.ID != "" && id == request.Issue.ID { + return newIssue + } + return endpoint{id: id} + } + edges := make([]edge, 0, 1+len(request.Dependencies)+1) + if request.ParentID != "" { + edges = append(edges, edge{newIssue, endpointFor(request.ParentID), types.DepParentChild}) + } + for index, dependency := range request.Dependencies { + if err := types.CheckFieldLen("dependency target ID", dependency.TargetID); err != nil { + return publicCreateValidationError(fmt.Errorf("create: dependency %d: %w", index, err)) + } + if dependency.TargetID == "" || !dependency.Type.IsValid() { + return publicCreateValidationError(fmt.Errorf("create: dependency target and type are required")) + } + if dependency.Metadata != "" && !json.Valid([]byte(dependency.Metadata)) { + return publicCreateValidationError(fmt.Errorf("create: dependency %d metadata must be valid JSON", index)) + } + if err := types.CheckFieldLen("dependency thread_id", dependency.ThreadID); err != nil { + return publicCreateValidationError(fmt.Errorf("create: dependency %d: %w", index, err)) + } + from, to := newIssue, endpointFor(dependency.TargetID) + if dependency.Reverse { + from, to = to, from + } + edges = append(edges, edge{from, to, dependency.Type}) + } + if request.WaitsFor != nil { + if err := types.CheckFieldLen("waits-for spawner ID", request.WaitsFor.SpawnerID); err != nil { + return publicCreateValidationError(fmt.Errorf("create: %w", err)) + } + if request.WaitsFor.SpawnerID == "" || (request.WaitsFor.Gate != "" && request.WaitsFor.Gate != string(types.WaitsForAllChildren) && request.WaitsFor.Gate != string(types.WaitsForAnyChildren)) { + return publicCreateValidationError(fmt.Errorf("create: waits-for spawner and gate are invalid")) + } + edges = append(edges, edge{newIssue, endpointFor(request.WaitsFor.SpawnerID), types.DepWaitsFor}) + } + type edgeKey struct { + source endpoint + target endpoint + } + seen := map[edgeKey]edge{} + for _, edge := range edges { + if edge.source == edge.target { + return publicCreateValidationError(fmt.Errorf("%w: %s", domain.ErrSelfDependency, edge.source.id)) + } + key := edgeKey{source: edge.source, target: edge.target} + if previous, ok := seen[key]; ok { + if previous.typ == edge.typ { + return publicCreateValidationError(fmt.Errorf("create: duplicate dependency %s -> %s", edge.source.id, edge.target.id)) + } + return publicCreateValidationError(&domain.DependencyTypeConflictError{IssueID: edge.source.id, DependsOnID: edge.target.id, ExistingType: string(previous.typ), RequestedType: string(edge.typ)}) + } + seen[key] = edge + } + return nil +} diff --git a/internal/storage/issueops/public_create_test.go b/internal/storage/issueops/public_create_test.go new file mode 100644 index 000000000..af76de060 --- /dev/null +++ b/internal/storage/issueops/public_create_test.go @@ -0,0 +1,269 @@ +package issueops + +import ( + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +func TestPreparePublicCreateRequestNormalizesAcceptedFieldsAndIgnoresDerivedFields(t *testing.T) { + createdAt := time.Date(2026, 7, 30, 12, 0, 0, 0, time.FixedZone("offset", -7*60*60)) + request := publicops.CreateRequest{Actor: "actor", Issue: &publicops.Issue{ + ID: "bd-public-create", Title: "title", Status: "custom", Priority: 2, IssueType: "custom-type", + Metadata: json.RawMessage(`{"key":true}`), ContentHash: "caller-hash", RowVersion: 42, + LeaseExpiresAt: &createdAt, CompactionLevel: 4, IDPrefix: "ignored", PrefixOverride: "ignored", IsLitePartial: true, + }} + + prepared, err := PreparePublicCreateRequest(request, PublicCreateContext{ + IssuePrefix: "bd", CustomStatuses: []string{"custom"}, CustomTypes: []string{"custom-type"}, + }) + if err != nil { + t.Fatalf("PreparePublicCreateRequest() error = %v", err) + } + if prepared.Issue.ContentHash == "caller-hash" || prepared.Issue.RowVersion != 0 || prepared.Issue.LeaseExpiresAt != nil || prepared.Issue.CompactionLevel != 0 || prepared.Issue.IDPrefix != "" || prepared.Issue.PrefixOverride != "" || prepared.Issue.IsLitePartial { + t.Fatalf("derived fields survived preparation: %#v", prepared.Issue) + } +} + +func TestPreparePublicCreateRequestCarriesSourceRepo(t *testing.T) { + prepared, err := PreparePublicCreateRequest(publicops.CreateRequest{Actor: "actor", Issue: &publicops.Issue{ + ID: "bd-source-repo", Title: "title", IssueType: types.TypeTask, Priority: 2, + SourceSystem: "github", SourceRepo: "other/repo", + }}, PublicCreateContext{IssuePrefix: "bd"}) + if err != nil { + t.Fatalf("PreparePublicCreateRequest() error = %v", err) + } + if prepared.Issue.SourceRepo != "other/repo" || prepared.Issue.SourceSystem != "github" { + t.Fatalf("prepared source = %q/%q, want github/other/repo", prepared.Issue.SourceSystem, prepared.Issue.SourceRepo) + } +} + +func TestPublicCreateIssueFieldClassificationIsComplete(t *testing.T) { + accepted := map[string]bool{ + "ID": true, "Title": true, "Description": true, "Design": true, "AcceptanceCriteria": true, "Notes": true, "SpecID": true, + "Status": true, "Priority": true, "IssueType": true, "Assignee": true, "Owner": true, "EstimatedMinutes": true, + "CreatedAt": true, "CreatedBy": true, "UpdatedAt": true, "StartedAt": true, "ClosedAt": true, "CloseReason": true, "ClosedBySession": true, + "DueAt": true, "DeferUntil": true, "ExternalRef": true, "SourceSystem": true, "SourceRepo": true, "Metadata": true, "Labels": true, + "Sender": true, "Ephemeral": true, "NoHistory": true, "WispType": true, "StorageClass": true, "Pinned": true, "IsTemplate": true, + "BondedFrom": true, "AwaitType": true, "AwaitID": true, "Timeout": true, "Waiters": true, "SourceFormula": true, "SourceLocation": true, + "MolType": true, "WorkType": true, "EventKind": true, "Actor": true, "Target": true, "Payload": true, + } + ignored := map[string]bool{ + "ContentHash": true, "LeaseExpiresAt": true, "HeartbeatAt": true, "LeaseGrantedNode": true, "RowVersion": true, + "CompactionLevel": true, "CompactedAt": true, "CompactedAtCommit": true, "OriginalSize": true, + "IDPrefix": true, "PrefixOverride": true, "IsLitePartial": true, + } + rejected := map[string]bool{"Dependencies": true, "Comments": true} + issueType := reflect.TypeFor[types.Issue]() + for field := range issueType.NumField() { + name := issueType.Field(field).Name + if accepted[name] || ignored[name] || rejected[name] { + continue + } + t.Errorf("types.Issue field %q is unclassified at the public create boundary", name) + } + for name := range accepted { + if _, ok := issueType.FieldByName(name); !ok { + t.Errorf("accepted field %q is not a types.Issue field", name) + } + } + for name := range ignored { + if _, ok := issueType.FieldByName(name); !ok { + t.Errorf("ignored field %q is not a types.Issue field", name) + } + } + for name := range rejected { + if _, ok := issueType.FieldByName(name); !ok { + t.Errorf("rejected field %q is not a types.Issue field", name) + } + } +} + +func TestPreparePublicCreateRequestRejectsDependencyDuplicatesAndSelfEdges(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.CreateRequest + conflict bool + }{ + {"same type duplicate", publicops.CreateRequest{Actor: "a", Issue: &publicops.Issue{ID: "bd-new", Title: "x", IssueType: types.TypeTask, Priority: 2}, ParentID: "bd-parent", Dependencies: []publicops.CreateDependency{{TargetID: "bd-parent", Type: types.DepParentChild}}}, false}, + {"different type duplicate", publicops.CreateRequest{Actor: "a", Issue: &publicops.Issue{ID: "bd-new", Title: "x", IssueType: types.TypeTask, Priority: 2}, ParentID: "bd-parent", Dependencies: []publicops.CreateDependency{{TargetID: "bd-parent", Type: types.DepBlocks}}}, true}, + {"explicit self edge", publicops.CreateRequest{Actor: "a", Issue: &publicops.Issue{ID: "bd-new", Title: "x", IssueType: types.TypeTask, Priority: 2}, Dependencies: []publicops.CreateDependency{{TargetID: "bd-new", Type: types.DepBlocks}}}, false}, + {"generated ID duplicate", publicops.CreateRequest{Actor: "a", Issue: &publicops.Issue{Title: "x", IssueType: types.TypeTask, Priority: 2}, ParentID: "bd-parent", Dependencies: []publicops.CreateDependency{{TargetID: "bd-parent", Type: types.DepParentChild}}}, false}, + {"duplicate reverse edge", publicops.CreateRequest{Actor: "a", Issue: &publicops.Issue{ID: "bd-new", Title: "x", IssueType: types.TypeTask, Priority: 2}, Dependencies: []publicops.CreateDependency{{TargetID: "bd-target", Type: types.DepBlocks, Reverse: true}, {TargetID: "bd-target", Type: types.DepBlocks, Reverse: true}}}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := PreparePublicCreateRequest(tc.request, PublicCreateContext{IssuePrefix: "bd"}) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("error = %v, want ErrValidation", err) + } + var conflict *domain.DependencyTypeConflictError + if errors.As(err, &conflict) != tc.conflict { + t.Fatalf("conflict identity = %v, want %v (%v)", errors.As(err, &conflict), tc.conflict, err) + } + }) + } +} + +func TestPreparePublicCreateRequestAllowsOppositeDependencyDirections(t *testing.T) { + request := publicops.CreateRequest{ + Actor: "a", + Issue: &publicops.Issue{ID: "bd-new", Title: "x", IssueType: types.TypeTask, Priority: 2}, + Dependencies: []publicops.CreateDependency{ + {TargetID: "bd-target", Type: types.DepBlocks}, + {TargetID: "bd-target", Type: types.DepBlocks, Reverse: true}, + }, + } + + if _, err := PreparePublicCreateRequest(request, PublicCreateContext{IssuePrefix: "bd"}); err != nil { + t.Fatalf("PreparePublicCreateRequest() error = %v, want nil", err) + } +} + +func TestValidatePublicCreateRequestChecksDependenciesBeforeContextPreparation(t *testing.T) { + request := publicops.CreateRequest{ + Actor: "a", + Issue: &publicops.Issue{Title: "x"}, + ParentID: "bd-parent", + Dependencies: []publicops.CreateDependency{{TargetID: "bd-parent", Type: types.DepParentChild}}, + } + + err := ValidatePublicCreateRequest(request) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidatePublicCreateRequest() error = %v, want ErrValidation", err) + } +} + +func TestValidatePublicCreateRequestAllowsEmptyWaitsForGate(t *testing.T) { + err := ValidatePublicCreateRequest(publicops.CreateRequest{ + Actor: "a", + Issue: &publicops.Issue{Title: "x"}, + WaitsFor: &publicops.WaitsFor{SpawnerID: "bd-spawner"}, + }) + if err != nil { + t.Fatalf("ValidatePublicCreateRequest() error = %v, want nil", err) + } +} + +func TestValidatePublicCreateRequestRejectsInvalidImportedRelations(t *testing.T) { + checks := []struct { + name string + request publicops.CreateRequest + }{ + { + name: "malformed dependency metadata", + request: publicops.CreateRequest{ + Actor: "actor", + Issue: &publicops.Issue{Title: "title"}, + Dependencies: []publicops.CreateDependency{{TargetID: "bd-target", Type: types.DepRelated, Metadata: "{"}}, + }, + }, + { + name: "overlong dependency thread", + request: publicops.CreateRequest{ + Actor: "actor", + Issue: &publicops.Issue{Title: "title"}, + Dependencies: []publicops.CreateDependency{{TargetID: "bd-target", Type: types.DepRelated, ThreadID: strings.Repeat("t", types.MaxFieldLen+1)}}, + }, + }, + } + + for _, check := range checks { + t.Run(check.name, func(t *testing.T) { + err := ValidatePublicCreateRequest(check.request) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidatePublicCreateRequest() error = %v, want ErrValidation", err) + } + }) + } +} + +func TestValidatePublicCreateRequestRejectsOverlongRelationshipIDs(t *testing.T) { + overlong := strings.Repeat("x", types.MaxFieldLen+1) + checks := []struct { + name string + request publicops.CreateRequest + field string + }{ + { + name: "parent ID", + request: publicops.CreateRequest{Actor: "actor", Issue: &publicops.Issue{Title: "title"}, ParentID: overlong}, + field: "parent", + }, + { + name: "dependency target ID", + request: publicops.CreateRequest{ + Actor: "actor", + Issue: &publicops.Issue{Title: "title"}, + Dependencies: []publicops.CreateDependency{{TargetID: overlong, Type: types.DepRelated}}, + }, + field: "dependency target", + }, + { + name: "waits-for spawner ID", + request: publicops.CreateRequest{ + Actor: "actor", + Issue: &publicops.Issue{Title: "title"}, + WaitsFor: &publicops.WaitsFor{SpawnerID: overlong}, + }, + field: "waits-for spawner", + }, + } + for _, check := range checks { + t.Run(check.name, func(t *testing.T) { + err := ValidatePublicCreateRequest(check.request) + if !errors.Is(err, storage.ErrValidation) || !errors.Is(err, types.ErrFieldTooLong) { + t.Fatalf("ValidatePublicCreateRequest() error = %v, want ErrValidation and ErrFieldTooLong", err) + } + if !strings.Contains(err.Error(), check.field) { + t.Fatalf("ValidatePublicCreateRequest() error = %v, want field %q", err, check.field) + } + }) + } +} + +type sqlStateError string + +func (e sqlStateError) Error() string { return string(e) } +func (e sqlStateError) SQLState() string { return string(e) } + +func TestValidatePublicCreateRequestRejectsOverlongLabelsBeforeOpeningUOW(t *testing.T) { + err := ValidatePublicCreateRequest(publicops.CreateRequest{ + Actor: "actor", + Issue: &publicops.Issue{Title: "title", Labels: []string{strings.Repeat("x", types.MaxFieldLen+1)}}, + }) + if !errors.Is(err, storage.ErrValidation) || !errors.Is(err, types.ErrFieldTooLong) { + t.Fatalf("ValidatePublicCreateRequest() error = %v, want ErrValidation and ErrFieldTooLong", err) + } +} + +func TestValidatePublicCreateRequestChecksAssigneeBeforeOwner(t *testing.T) { + err := ValidatePublicCreateRequest(publicops.CreateRequest{Actor: "actor", Issue: &publicops.Issue{ + Assignee: strings.Repeat("a", types.MaxFieldLen+1), + Owner: strings.Repeat("o", types.MaxFieldLen+1), + }}) + if !errors.Is(err, types.ErrFieldTooLong) || !strings.Contains(err.Error(), "assignee") { + t.Fatalf("field-length error = %v, want assignee first", err) + } +} + +func TestClassifyPublicCreateErrorPreservesDeterministicIdentities(t *testing.T) { + hierarchy := &domain.DependencyHierarchyConflictError{} + for _, err := range []error{types.ErrFieldTooLong, domain.ErrDependencyCycle, hierarchy} { + classified := ClassifyPublicCreateError(err) + if !errors.Is(classified, storage.ErrValidation) || !errors.Is(classified, err) { + t.Fatalf("ClassifyPublicCreateError(%v) = %v, want validation and original identity", err, classified) + } + } + classified := ClassifyPublicCreateError(sqlStateError("23505")) + if !errors.Is(classified, storage.ErrAlreadyExists) || !errors.Is(classified, sqlStateError("23505")) { + t.Fatalf("ClassifyPublicCreateError(23505) = %v, want ErrAlreadyExists and SQLSTATE", classified) + } +} diff --git a/internal/storage/issueops/public_hydration.go b/internal/storage/issueops/public_hydration.go new file mode 100644 index 000000000..18c1f5efe --- /dev/null +++ b/internal/storage/issueops/public_hydration.go @@ -0,0 +1,37 @@ +package issueops + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/types" +) + +// HydrateIssueOperationResult returns a detached issue with requested relations. +func HydrateIssueOperationResult(ctx context.Context, tx DBTX, id string, includeComments bool) (*types.Issue, error) { + if tx == nil { + return nil, fmt.Errorf("hydrate issue operation result: transaction is nil") + } + issue, err := GetIssueInTx(ctx, tx, id) + if err != nil { + return nil, err + } + labels, err := GetLabelsInTx(ctx, tx, "", id) + if err != nil { + return nil, fmt.Errorf("hydrate issue labels: %w", err) + } + issue.Labels = labels + dependencies, err := GetDependencyRecordsForIssuesInTx(ctx, tx, []string{id}) + if err != nil { + return nil, fmt.Errorf("hydrate issue dependencies: %w", err) + } + issue.Dependencies = dependencies[id] + if includeComments { + comments, err := GetIssueCommentsInTx(ctx, tx, id) + if err != nil { + return nil, fmt.Errorf("hydrate issue comments: %w", err) + } + issue.Comments = comments + } + return issue, nil +} diff --git a/internal/storage/issueops/public_hydration_test.go b/internal/storage/issueops/public_hydration_test.go new file mode 100644 index 000000000..dbb23da97 --- /dev/null +++ b/internal/storage/issueops/public_hydration_test.go @@ -0,0 +1,12 @@ +package issueops + +import ( + "context" + "testing" +) + +func TestHydrateIssueOperationResultRequiresIssue(t *testing.T) { + if _, err := HydrateIssueOperationResult(context.Background(), nil, "missing", false); err == nil { + t.Fatal("HydrateIssueOperationResult() error = nil, want error") + } +} diff --git a/internal/storage/issueops/public_snapshot.go b/internal/storage/issueops/public_snapshot.go new file mode 100644 index 000000000..e8393717c --- /dev/null +++ b/internal/storage/issueops/public_snapshot.go @@ -0,0 +1,153 @@ +package issueops + +import ( + "encoding/json" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// CloneCreateRequest returns a deep copy of request. +func CloneCreateRequest(request publicops.CreateRequest) publicops.CreateRequest { + clone := request + clone.Issue = clonePublicIssue(request.Issue) + clone.Dependencies = append([]publicops.CreateDependency(nil), request.Dependencies...) + if request.WaitsFor != nil { + waitsFor := *request.WaitsFor + clone.WaitsFor = &waitsFor + } + return clone +} + +// CloneUpdateRequest returns a deep copy of request. +func CloneUpdateRequest(request publicops.UpdateRequest) publicops.UpdateRequest { + clone := request + clone.Patch.Labels.Add = append([]string(nil), request.Patch.Labels.Add...) + clone.Patch.Labels.Remove = append([]string(nil), request.Patch.Labels.Remove...) + clone.Patch.Labels.Replace.Value = append([]string(nil), request.Patch.Labels.Replace.Value...) + clone.Patch.Metadata.Replace.Value = cloneRawMessage(request.Patch.Metadata.Replace.Value) + clone.Patch.Metadata.Merge.Value = cloneRawMessage(request.Patch.Metadata.Merge.Value) + clone.Patch.Metadata.Set = cloneRawMessageMap(request.Patch.Metadata.Set) + clone.Patch.Metadata.Unset = append([]string(nil), request.Patch.Metadata.Unset...) + clone.Patch.EstimatedMinutes.Value = cloneInt(request.Patch.EstimatedMinutes.Value) + clone.Patch.ExternalRef.Value = cloneString(request.Patch.ExternalRef.Value) + clone.Patch.DueAt.Value = cloneTime(request.Patch.DueAt.Value) + clone.Patch.DeferUntil.Value = cloneTime(request.Patch.DeferUntil.Value) + clone.ExpectedVersion = cloneInt64(request.ExpectedVersion) + clone.ExpectedAssignee = cloneString(request.ExpectedAssignee) + if request.ExpectedStatus != nil { + status := *request.ExpectedStatus + clone.ExpectedStatus = &status + } + return clone +} + +// CloneCloseRequest returns a deep copy of request. +func CloneCloseRequest(request publicops.CloseRequest) publicops.CloseRequest { + clone := request + clone.ExpectedVersion = cloneInt64(request.ExpectedVersion) + return clone +} + +// CloneReopenRequest returns a deep copy of request. +func CloneReopenRequest(request publicops.ReopenRequest) publicops.ReopenRequest { + clone := request + clone.ExpectedVersion = cloneInt64(request.ExpectedVersion) + return clone +} + +func clonePublicIssue(issue *publicops.Issue) *publicops.Issue { + if issue == nil { + return nil + } + clone := *issue + clone.EstimatedMinutes = cloneInt(issue.EstimatedMinutes) + clone.ExternalRef = cloneString(issue.ExternalRef) + clone.StartedAt = cloneTime(issue.StartedAt) + clone.ClosedAt = cloneTime(issue.ClosedAt) + clone.LeaseExpiresAt = cloneTime(issue.LeaseExpiresAt) + clone.HeartbeatAt = cloneTime(issue.HeartbeatAt) + clone.DueAt = cloneTime(issue.DueAt) + clone.DeferUntil = cloneTime(issue.DeferUntil) + clone.CompactedAt = cloneTime(issue.CompactedAt) + clone.CompactedAtCommit = cloneString(issue.CompactedAtCommit) + clone.Metadata = cloneRawMessage(issue.Metadata) + clone.Labels = append([]string(nil), issue.Labels...) + clone.Dependencies = cloneDependencies(issue.Dependencies) + clone.Comments = cloneComments(issue.Comments) + clone.BondedFrom = append([]types.BondRef(nil), issue.BondedFrom...) + clone.Waiters = append([]string(nil), issue.Waiters...) + return &clone +} + +func cloneDependencies(dependencies []*types.Dependency) []*types.Dependency { + clone := make([]*types.Dependency, len(dependencies)) + for i, dependency := range dependencies { + if dependency == nil { + continue + } + copy := *dependency + clone[i] = © + } + return clone +} + +func cloneComments(comments []*types.Comment) []*types.Comment { + clone := make([]*types.Comment, len(comments)) + for i, comment := range comments { + if comment == nil { + continue + } + copy := *comment + clone[i] = © + } + return clone +} + +func cloneRawMessage(value json.RawMessage) json.RawMessage { + return append(json.RawMessage(nil), value...) +} + +func cloneRawMessageMap(values map[string]json.RawMessage) map[string]json.RawMessage { + if values == nil { + return nil + } + clone := make(map[string]json.RawMessage, len(values)) + for key, value := range values { + clone[key] = cloneRawMessage(value) + } + return clone +} + +func cloneInt(value *int) *int { + if value == nil { + return nil + } + clone := *value + return &clone +} + +func cloneInt64(value *int64) *int64 { + if value == nil { + return nil + } + clone := *value + return &clone +} + +func cloneString(value *string) *string { + if value == nil { + return nil + } + clone := *value + return &clone +} + +func cloneTime(value *time.Time) *time.Time { + if value == nil { + return nil + } + clone := *value + return &clone +} diff --git a/internal/storage/issueops/public_snapshot_test.go b/internal/storage/issueops/public_snapshot_test.go new file mode 100644 index 000000000..3077d6050 --- /dev/null +++ b/internal/storage/issueops/public_snapshot_test.go @@ -0,0 +1,122 @@ +package issueops + +import ( + "encoding/json" + "reflect" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +func TestCloneIssueOperationRequestsDeepCopyMutableFields(t *testing.T) { + value := 3 + ref := "ref" + metadata := json.RawMessage(`{"key":"value"}`) + now := time.Now().UTC() + request := publicops.CreateRequest{ + Actor: "actor", + Issue: &publicops.Issue{Labels: []string{"one"}, Metadata: metadata, EstimatedMinutes: &value, ExternalRef: &ref, StartedAt: &now, ClosedAt: &now, LeaseExpiresAt: &now, HeartbeatAt: &now, DueAt: &now, DeferUntil: &now, CompactedAt: &now, CompactedAtCommit: &ref, Dependencies: []*types.Dependency{{Metadata: "dependency"}}, Comments: []*types.Comment{{Text: "nested"}}, BondedFrom: []types.BondRef{{SourceID: "source"}}, Waiters: []string{"waiter"}}, + Dependencies: []publicops.CreateDependency{{TargetID: "target"}}, + WaitsFor: &publicops.WaitsFor{SpawnerID: "parent"}, + } + + cloned := CloneCreateRequest(request) + cloned.Issue.Labels[0] = "changed" + cloned.Issue.Metadata[0] = '{' + *cloned.Issue.EstimatedMinutes = 4 + *cloned.Issue.ExternalRef = "changed" + cloned.Issue.Waiters[0] = "changed" + cloned.Issue.Dependencies[0].Metadata = "changed" + cloned.Issue.Comments[0].Text = "changed" + cloned.Dependencies[0].TargetID = "changed" + cloned.WaitsFor.SpawnerID = "changed" + + if request.Issue.Labels[0] != "one" || string(request.Issue.Metadata) != `{"key":"value"}` || *request.Issue.EstimatedMinutes != 3 || *request.Issue.ExternalRef != "ref" || request.Issue.Waiters[0] != "waiter" || request.Issue.Dependencies[0].Metadata != "dependency" || request.Issue.Comments[0].Text != "nested" || request.Dependencies[0].TargetID != "target" || request.WaitsFor.SpawnerID != "parent" { + t.Fatal("CloneCreateRequest() retained mutable caller-owned state") + } + + update := publicops.UpdateRequest{Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"key": metadata}, Unset: []string{"remove"}, Replace: publicops.Field[json.RawMessage]{Set: true, Value: metadata}}}} + update.Patch.Labels.Add = []string{"add"} + update.Patch.Labels.Remove = []string{"remove-label"} + update.Patch.Labels.Replace = publicops.Field[[]string]{Set: true, Value: []string{"replacement"}} + update.Patch.EstimatedMinutes = publicops.Field[*int]{Set: true, Value: &value} + update.Patch.ExternalRef = publicops.Field[*string]{Set: true, Value: &ref} + update.Patch.DueAt = publicops.Field[*time.Time]{Set: true, Value: &now} + update.Patch.DeferUntil = publicops.Field[*time.Time]{Set: true, Value: &now} + updateClone := CloneUpdateRequest(update) + updateClone.Patch.Metadata.Set["key"][0] = '{' + updateClone.Patch.Metadata.Unset[0] = "changed" + updateClone.Patch.Metadata.Replace.Value[0] = '{' + updateClone.Patch.Labels.Add[0] = "changed" + updateClone.Patch.Labels.Remove[0] = "changed" + updateClone.Patch.Labels.Replace.Value[0] = "changed" + *updateClone.Patch.EstimatedMinutes.Value = 5 + *updateClone.Patch.ExternalRef.Value = "changed" + *updateClone.Patch.DueAt.Value = now.Add(time.Hour) + *updateClone.Patch.DeferUntil.Value = now.Add(time.Hour) + if string(update.Patch.Metadata.Set["key"]) != `{"key":"value"}` || update.Patch.Metadata.Unset[0] != "remove" || string(update.Patch.Metadata.Replace.Value) != `{"key":"value"}` || update.Patch.Labels.Add[0] != "add" || update.Patch.Labels.Remove[0] != "remove-label" || update.Patch.Labels.Replace.Value[0] != "replacement" || *update.Patch.EstimatedMinutes.Value != 3 || *update.Patch.ExternalRef.Value != "ref" || !update.Patch.DueAt.Value.Equal(now) || !update.Patch.DeferUntil.Value.Equal(now) { + t.Fatal("CloneUpdateRequest() retained mutable caller-owned state") + } +} + +func TestIssueOperationCloneFunctionsKeepFrozenRequestFields(t *testing.T) { + issueMutable := map[string]bool{"EstimatedMinutes": true, "StartedAt": true, "ClosedAt": true, "LeaseExpiresAt": true, "HeartbeatAt": true, "DueAt": true, "DeferUntil": true, "ExternalRef": true, "CompactedAt": true, "CompactedAtCommit": true, "Metadata": true, "Labels": true, "Dependencies": true, "Comments": true, "BondedFrom": true, "Waiters": true} + for index := 0; index < reflect.TypeOf(types.Issue{}).NumField(); index++ { + field := reflect.TypeOf(types.Issue{}).Field(index) + if isMutableKind(field.Type.Kind()) && !issueMutable[field.Name] { + t.Errorf("clonePublicIssue must deep-copy newly mutable Issue field %s", field.Name) + } + } + + requestMutable := map[reflect.Type]map[string]bool{ + reflect.TypeOf(publicops.CreateRequest{}): {"Issue": true, "Dependencies": true, "WaitsFor": true}, + reflect.TypeOf(publicops.UpdateRequest{}): {"ExpectedVersion": true, "ExpectedAssignee": true, "ExpectedStatus": true}, + reflect.TypeOf(publicops.CloseRequest{}): {"ExpectedVersion": true}, + reflect.TypeOf(publicops.ReopenRequest{}): {"ExpectedVersion": true}, + } + for typeOf, allowlist := range requestMutable { + for index := 0; index < typeOf.NumField(); index++ { + field := typeOf.Field(index) + if isMutableKind(field.Type.Kind()) && !allowlist[field.Name] { + t.Errorf("request clone must deep-copy newly mutable %s field %s", typeOf, field.Name) + } + } + } + + assertMutableFields(t, reflect.TypeOf(publicops.LabelPatch{}), map[string]bool{"Add": true, "Remove": true}) + assertMutableFields(t, reflect.TypeOf(publicops.MetadataPatch{}), map[string]bool{"Set": true, "Unset": true}) + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[[]string]{}), "LabelPatch.Replace") + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[json.RawMessage]{}), "MetadataPatch.Replace") + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[json.RawMessage]{}), "MetadataPatch.Merge") + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*int]{}), "IssuePatch.EstimatedMinutes") + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*string]{}), "IssuePatch.ExternalRef") + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*time.Time]{}), "IssuePatch.DueAt") + assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*time.Time]{}), "IssuePatch.DeferUntil") +} + +func isMutableKind(kind reflect.Kind) bool { + return kind == reflect.Pointer || kind == reflect.Slice || kind == reflect.Map || kind == reflect.Interface +} + +func assertMutableFields(t *testing.T, typeOf reflect.Type, allowlist map[string]bool) { + t.Helper() + for index := 0; index < typeOf.NumField(); index++ { + field := typeOf.Field(index) + if isMutableKind(field.Type.Kind()) && !allowlist[field.Name] { + t.Errorf("clone must deep-copy newly mutable %s field %s", typeOf, field.Name) + } + } +} + +func assertFieldValueMutable(t *testing.T, typeOf reflect.Type, path string) { + t.Helper() + field, ok := typeOf.FieldByName("Value") + if !ok { + t.Fatalf("%s lacks Value", typeOf) + } + if !isMutableKind(field.Type.Kind()) { + t.Fatalf("%s Value is no longer mutable; update clone coverage", path) + } +} diff --git a/internal/storage/issueops/reopen.go b/internal/storage/issueops/reopen.go index 79b05d003..380a3acb4 100644 --- a/internal/storage/issueops/reopen.go +++ b/internal/storage/issueops/reopen.go @@ -3,77 +3,122 @@ package issueops import ( "context" "database/sql" + "errors" "fmt" "time" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) type ReopenResult struct { IsWisp bool AlreadyOpen bool + Changed bool + // IssueRowsChanged is the concrete SQL fact that at least one issues row + // changed in this transaction, either the reopened row or a recomputed row. + IssueRowsChanged bool +} + +// ReopenIssueInTx reopens only statuses in the done category. It leaves all +// other statuses unchanged. +func ReopenIssueInTx(ctx context.Context, tx DBTX, id, reason, actor string) (*ReopenResult, error) { + return reopenIssueInTx(ctx, tx, id, reason, actor, true) } //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func ReopenIssueInTx(ctx context.Context, tx DBTX, id, reason, actor string) (*ReopenResult, error) { +func reopenIssueInTx(ctx context.Context, tx DBTX, id, reason, actor string, retryOnConditionalMiss bool) (*ReopenResult, error) { isWisp := IsActiveWispInTx(ctx, tx, id) issueTable, _, eventTable, _ := WispTableRouting(isWisp) - var affectedIssues, affectedWisps []string - var aerr error - if isWisp { - affectedIssues, affectedWisps, aerr = AffectedByStatusChangeForWispInTx(ctx, tx, id) - } else { - affectedIssues, affectedWisps, aerr = AffectedByStatusChangeInTx(ctx, tx, id) + var current string + err := tx.QueryRowContext(ctx, fmt.Sprintf("SELECT status FROM %s WHERE id = ?", issueTable), id).Scan(¤t) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) } - if aerr != nil { - return nil, fmt.Errorf("affected by reopen for %s: %w", id, aerr) + if err != nil { + return nil, fmt.Errorf("read reopen status for %s: %w", id, err) + } + + status := types.Status(current) + category, err := ReopenCategoryInTx(ctx, tx, status) + if err != nil { + return nil, fmt.Errorf("resolve reopen category for %s: %w", id, err) + } + if category != types.CategoryDone { + return &ReopenResult{IsWisp: isWisp, AlreadyOpen: status == types.StatusOpen}, nil + } + + var affectedIssues, affectedWisps []string + if isWisp { + affectedIssues, affectedWisps, err = AffectedByStatusChangeForWispInTx(ctx, tx, id) + } else { + affectedIssues, affectedWisps, err = AffectedByStatusChangeInTx(ctx, tx, id) + } + if err != nil { + return nil, fmt.Errorf("affected by reopen for %s: %w", id, err) } now := time.Now().UTC() - result, err := tx.ExecContext(ctx, fmt.Sprintf(` - UPDATE %s SET status = ?, closed_at = NULL, close_reason = '', closed_by_session = '', defer_until = NULL, updated_at = ? + UPDATE %s + SET status = ?, closed_at = NULL, close_reason = '', closed_by_session = '', defer_until = NULL, + updated_at = ?, row_lock = ? WHERE id = ? AND status = ? - `, issueTable), types.StatusOpen, now, id, types.StatusClosed) + `, issueTable), types.StatusOpen, now, freshRowLock(), id, status) if err != nil { - return nil, fmt.Errorf("failed to reopen issue: %w", err) + return nil, fmt.Errorf("reopen issue: %w", err) } rows, err := result.RowsAffected() if err != nil { - return nil, fmt.Errorf("failed to get rows affected: %w", err) + return nil, fmt.Errorf("get reopen rows affected: %w", err) } if rows == 0 { - var status string - qerr := tx.QueryRowContext(ctx, - fmt.Sprintf(`SELECT status FROM %s WHERE id = ?`, issueTable), id, - ).Scan(&status) - if qerr == sql.ErrNoRows { - return nil, fmt.Errorf("issue not found: %s", id) + var latest string + err := tx.QueryRowContext(ctx, fmt.Sprintf("SELECT status FROM %s WHERE id = ?", issueTable), id).Scan(&latest) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) } - if qerr != nil { - return nil, fmt.Errorf("failed to check issue existence: %w", qerr) + if err != nil { + return nil, fmt.Errorf("check reopen status for %s: %w", id, err) } - if types.Status(status) != types.StatusClosed { - return &ReopenResult{IsWisp: isWisp, AlreadyOpen: true}, nil + latestStatus := types.Status(latest) + latestCategory, err := ReopenCategoryInTx(ctx, tx, latestStatus) + if err != nil { + return nil, fmt.Errorf("resolve latest reopen category for %s: %w", id, err) } - return nil, fmt.Errorf("failed to reopen issue: %s", id) + if latestCategory != types.CategoryDone { + return &ReopenResult{IsWisp: isWisp, AlreadyOpen: latestStatus == types.StatusOpen}, nil + } + if retryOnConditionalMiss { + return reopenIssueInTx(ctx, tx, id, reason, actor, false) + } + return nil, fmt.Errorf("reopen issue %s: status changed concurrently", id) + } + + if err := DeleteLeaseInTx(ctx, tx, id); err != nil { + return nil, err } if err := RecordEventInTable(ctx, tx, eventTable, id, types.EventReopened, actor, reason); err != nil { - return nil, fmt.Errorf("failed to record event: %w", err) + return nil, fmt.Errorf("record reopen event: %w", err) } if reason != "" { if err := AddCommentEventInTx(ctx, tx, id, actor, reason); err != nil { - return nil, fmt.Errorf("failed to add reopen comment: %w", err) + return nil, fmt.Errorf("add reopen comment: %w", err) } } - if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil { + recompute, err := RecomputeIsBlockedInTxWithResult(ctx, tx, affectedIssues, affectedWisps) + if err != nil { return nil, fmt.Errorf("recompute is_blocked after reopen for %s: %w", id, err) } - return &ReopenResult{IsWisp: isWisp}, nil + return &ReopenResult{ + IsWisp: isWisp, + Changed: true, + IssueRowsChanged: !isWisp || recompute.IssueRowsChanged, + }, nil } diff --git a/internal/storage/issueops/reopen_test.go b/internal/storage/issueops/reopen_test.go new file mode 100644 index 000000000..47cd8610e --- /dev/null +++ b/internal/storage/issueops/reopen_test.go @@ -0,0 +1,195 @@ +package issueops + +import ( + "context" + "database/sql" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/steveyegge/beads/internal/types" +) + +func TestReopenIssueInTxRetriesConditionalUpdateWhenLatestStatusIsCustomDone(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + + const id = "bd-reopen-race" + emptyRows := func() *sqlmock.Rows { + return sqlmock.NewRows([]string{"issue_id"}) + } + expectInactiveWisp := func() { + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps WHERE id = ? LIMIT 1")). + WithArgs(id). + WillReturnError(sql.ErrNoRows) + } + expectStatus := func(status types.Status) { + mock.ExpectQuery(regexp.QuoteMeta("SELECT status FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow(string(status))) + } + expectAffectedQueries := func() { + for range 9 { + mock.ExpectQuery("(?s).*").WillReturnRows(emptyRows()) + } + } + + expectInactiveWisp() + expectStatus(types.StatusClosed) + expectAffectedQueries() + mock.ExpectExec(`(?s)UPDATE issues\s+SET status`).WillReturnResult(sqlmock.NewResult(0, 0)) + expectStatus("archived") + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("archived", string(types.CategoryDone))) + + // A fresh custom done status after the conditional miss must be retried, not + // reported as an unchanged reopen. + expectInactiveWisp() + expectStatus("archived") + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("archived", string(types.CategoryDone))) + expectAffectedQueries() + mock.ExpectExec(`(?s)UPDATE issues\s+SET status`). + WithArgs(types.StatusOpen, sqlmock.AnyArg(), sqlmock.AnyArg(), id, types.Status("archived")). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(regexp.QuoteMeta("DELETE FROM leases WHERE issue_id = ?")).WithArgs(id). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT id FROM events`). + WillReturnRows(sqlmock.NewRows([]string{"id"})) + mock.ExpectExec(`(?s)INSERT INTO events`).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`(?s)UPDATE issues i SET`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(`(?s)UPDATE issues i SET`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectRollback() + + result, err := ReopenIssueInTx(context.Background(), tx, id, "", "tester") + if err != nil { + t.Fatalf("ReopenIssueInTx: %v", err) + } + if !result.Changed { + t.Fatal("ReopenIssueInTx reported Changed=false after the latest status remained done") + } + if !result.IssueRowsChanged { + t.Fatal("permanent reopen must report its concrete issues-row update") + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + +func TestReopenIssueInTxCustomNonDoneIsNotAlreadyOpen(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + + const id = "bd-reopen-custom-active" + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps WHERE id = ? LIMIT 1")). + WithArgs(id). + WillReturnError(sql.ErrNoRows) + mock.ExpectQuery(regexp.QuoteMeta("SELECT status FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow("triaged")) + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("triaged", string(types.CategoryActive))) + mock.ExpectRollback() + + result, err := ReopenIssueInTx(context.Background(), tx, id, "", "tester") + if err != nil { + t.Fatalf("ReopenIssueInTx: %v", err) + } + if result.Changed || result.AlreadyOpen || result.IssueRowsChanged { + t.Fatalf("result = %+v, want unchanged and not already open", result) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + +func TestReopenIssueInTxConditionalMissToCustomNonDoneIsNotAlreadyOpen(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + + const id = "bd-reopen-race-active" + emptyRows := func() *sqlmock.Rows { return sqlmock.NewRows([]string{"issue_id"}) } + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps WHERE id = ? LIMIT 1")). + WithArgs(id). + WillReturnError(sql.ErrNoRows) + mock.ExpectQuery(regexp.QuoteMeta("SELECT status FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow(string(types.StatusClosed))) + for range 9 { + mock.ExpectQuery("(?s).*").WillReturnRows(emptyRows()) + } + mock.ExpectExec(`(?s)UPDATE issues\s+SET status`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT status FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow("triaged")) + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("triaged", string(types.CategoryActive))) + mock.ExpectRollback() + + result, err := ReopenIssueInTx(context.Background(), tx, id, "ignored", "tester") + if err != nil { + t.Fatalf("ReopenIssueInTx: %v", err) + } + if result.Changed || result.AlreadyOpen || result.IssueRowsChanged { + t.Fatalf("result = %+v, want unchanged and not already open", result) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unexpected lease, event, comment, or recompute write: %v", err) + } +} + +func TestReopenIssueInTxReportsConcurrentChangeAfterRetryExhaustion(t *testing.T) { + db, mock, tx := beginMockTx(t) + defer db.Close() + + const id = "bd-reopen-race-exhausted" + emptyRows := func() *sqlmock.Rows { + return sqlmock.NewRows([]string{"issue_id"}) + } + expectInactiveWisp := func() { + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps WHERE id = ? LIMIT 1")). + WithArgs(id). + WillReturnError(sql.ErrNoRows) + } + expectStatus := func() { + mock.ExpectQuery(regexp.QuoteMeta("SELECT status FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow(string(types.StatusClosed))) + } + expectAffectedQueries := func() { + for range 9 { + mock.ExpectQuery("(?s).*").WillReturnRows(emptyRows()) + } + } + expectAttempt := func() { + expectInactiveWisp() + expectStatus() + expectAffectedQueries() + mock.ExpectExec(`(?s)UPDATE issues\s+SET status`).WillReturnResult(sqlmock.NewResult(0, 0)) + expectStatus() + } + + expectAttempt() + expectAttempt() + mock.ExpectRollback() + + _, err := ReopenIssueInTx(context.Background(), tx, id, "", "tester") + if err == nil || !regexp.MustCompile("status changed concurrently").MatchString(err.Error()) { + t.Fatalf("err = %v, want bounded concurrent-change error", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} diff --git a/internal/storage/issueops/scan.go b/internal/storage/issueops/scan.go index 668e60094..f92cc2db7 100644 --- a/internal/storage/issueops/scan.go +++ b/internal/storage/issueops/scan.go @@ -36,7 +36,7 @@ const IssueSelectColumns = sqlbuild.IssueSelectColumns const IssueSelectColumnsLite = `id, content_hash, title, status, priority, issue_type, assignee, estimated_minutes, created_at, created_by, owner, updated_at, started_at, closed_at, external_ref, spec_id, - compaction_level, compacted_at, compacted_at_commit, original_size, source_repo, close_reason, + compaction_level, compacted_at, compacted_at_commit, original_size, source_repo, close_reason, closed_by_session, sender, ephemeral, no_history, wisp_type, pinned, is_template, await_type, await_id, timeout_ns, mol_type, @@ -83,7 +83,7 @@ func ScanIssueFrom(s IssueScanner, extra ...any) (*types.Issue, error) { var estimatedMinutes, originalSize, timeoutNs sql.NullInt64 var createdBy sql.NullString var assignee, externalRef, specID, compactedAtCommit, owner sql.NullString - var contentHash, sourceRepo, closeReason sql.NullString + var contentHash, sourceRepo, closeReason, closedBySession sql.NullString var workType, sourceSystem sql.NullString var sender, wispType, molType, eventKind, actor, target, payload sql.NullString var awaitType, awaitID, waiters sql.NullString @@ -97,7 +97,7 @@ func ScanIssueFrom(s IssueScanner, extra ...any) (*types.Issue, error) { &issue.AcceptanceCriteria, &issue.Notes, &issue.Status, &issue.Priority, &issue.IssueType, &assignee, &estimatedMinutes, &createdAtStr, &createdBy, &owner, &updatedAtStr, &startedAt, &closedAt, &externalRef, &specID, - &issue.CompactionLevel, &compactedAt, &compactedAtCommit, &originalSize, &sourceRepo, &closeReason, + &issue.CompactionLevel, &compactedAt, &compactedAtCommit, &originalSize, &sourceRepo, &closeReason, &closedBySession, &sender, &ephemeral, &noHistory, &wispType, &pinned, &isTemplate, &awaitType, &awaitID, &timeoutNs, &waiters, &molType, @@ -163,6 +163,9 @@ func ScanIssueFrom(s IssueScanner, extra ...any) (*types.Issue, error) { if closeReason.Valid { issue.CloseReason = closeReason.String } + if closedBySession.Valid { + issue.ClosedBySession = closedBySession.String + } if sender.Valid { issue.Sender = sender.String } @@ -261,7 +264,7 @@ func ScanIssueLiteFrom(s IssueScanner, extra ...any) (*types.Issue, error) { var estimatedMinutes, originalSize, timeoutNs sql.NullInt64 var createdBy sql.NullString var assignee, externalRef, specID, compactedAtCommit, owner sql.NullString - var contentHash, sourceRepo, closeReason sql.NullString + var contentHash, sourceRepo, closeReason, closedBySession sql.NullString var workType, sourceSystem sql.NullString var sender, wispType, molType, eventKind, actor, target sql.NullString var awaitType, awaitID sql.NullString @@ -275,7 +278,7 @@ func ScanIssueLiteFrom(s IssueScanner, extra ...any) (*types.Issue, error) { &issue.Status, &issue.Priority, &issue.IssueType, &assignee, &estimatedMinutes, &createdAtStr, &createdBy, &owner, &updatedAtStr, &startedAt, &closedAt, &externalRef, &specID, - &issue.CompactionLevel, &compactedAt, &compactedAtCommit, &originalSize, &sourceRepo, &closeReason, + &issue.CompactionLevel, &compactedAt, &compactedAtCommit, &originalSize, &sourceRepo, &closeReason, &closedBySession, &sender, &ephemeral, &noHistory, &wispType, &pinned, &isTemplate, &awaitType, &awaitID, &timeoutNs, &molType, @@ -339,6 +342,9 @@ func ScanIssueLiteFrom(s IssueScanner, extra ...any) (*types.Issue, error) { if closeReason.Valid { issue.CloseReason = closeReason.String } + if closedBySession.Valid { + issue.ClosedBySession = closedBySession.String + } if sender.Valid { issue.Sender = sender.String } diff --git a/internal/storage/issueops/search_lite_merge_test.go b/internal/storage/issueops/search_lite_merge_test.go index 40a1e900f..ba6117320 100644 --- a/internal/storage/issueops/search_lite_merge_test.go +++ b/internal/storage/issueops/search_lite_merge_test.go @@ -19,7 +19,7 @@ func liteColumnNames() []string { "status", "priority", "issue_type", "assignee", "estimated_minutes", "created_at", "created_by", "owner", "updated_at", "started_at", "closed_at", "external_ref", "spec_id", - "compaction_level", "compacted_at", "compacted_at_commit", "original_size", "source_repo", "close_reason", + "compaction_level", "compacted_at", "compacted_at_commit", "original_size", "source_repo", "close_reason", "closed_by_session", "sender", "ephemeral", "no_history", "wisp_type", "pinned", "is_template", "await_type", "await_id", "timeout_ns", "mol_type", @@ -39,7 +39,7 @@ func liteMergeRow(id string, createdAt time.Time) []driver.Value { "open", // status 2, "task", nil, nil, // priority, issue_type, assignee, estimated_minutes createdAt.Format(time.RFC3339), nil, nil, nil, nil, nil, nil, nil, // created_at, created_by, owner, updated_at, started_at, closed_at, external_ref, spec_id - 0, nil, nil, nil, nil, nil, // compaction_level, compacted_at, compacted_at_commit, original_size, source_repo, close_reason + 0, nil, nil, nil, nil, nil, nil, // compaction_level, compacted_at, compacted_at_commit, original_size, source_repo, close_reason, closed_by_session nil, nil, nil, nil, nil, nil, // sender, ephemeral, no_history, wisp_type, pinned, is_template nil, nil, nil, // await_type, await_id, timeout_ns nil, // mol_type diff --git a/internal/storage/issueops/update.go b/internal/storage/issueops/update.go index e8e7aaec0..21b01d6f0 100644 --- a/internal/storage/issueops/update.go +++ b/internal/storage/issueops/update.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "slices" + "sort" "strings" "time" @@ -14,7 +16,7 @@ import ( // IsAllowedUpdateField checks if a field name is valid for issue updates. func IsAllowedUpdateField(key string) bool { allowed := map[string]bool{ - "status": true, "priority": true, "title": true, "assignee": true, + "status": true, "priority": true, "title": true, "assignee": true, "owner": true, "description": true, "design": true, "acceptance_criteria": true, "notes": true, "issue_type": true, "estimated_minutes": true, "external_ref": true, "spec_id": true, "started_at": true, @@ -171,8 +173,11 @@ func DetermineEventType(oldIssue *types.Issue, updates map[string]interface{}) t // UpdateResult holds the result of an UpdateIssueInTx call. type UpdateResult struct { - OldIssue *types.Issue - IsWisp bool + OldIssue *types.Issue + IsWisp bool + Changed bool + IssueRowsChanged bool + WispRowsChanged bool } // UpdateIssueInTx performs the full update SQL logic within a transaction. @@ -192,6 +197,8 @@ func UpdateIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, update } func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string, recordEvent bool) (*UpdateResult, error) { + updates = cloneUpdateFields(updates) + // Route to correct table. isWisp := IsActiveWispInTx(ctx, tx, id) issueTable, _, eventTable, _ := WispTableRouting(isWisp) @@ -210,35 +217,16 @@ func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string if err != nil { return nil, err } - - // Validate issue_type against built-in + custom types (GH#3030). - // This mirrors the create path (PrepareIssueForInsert → ValidateWithCustom) - // and reads custom types from the same transaction, so it works reliably - // even in subprocess contexts where the CLI-level store may be unavailable. - if rawType, ok := updates["issue_type"]; ok { - if issueType, ok := rawType.(string); ok { - customTypes, err := ResolveCustomTypesInTx(ctx, tx) - if err != nil { - return nil, fmt.Errorf("failed to get custom types for validation: %w", err) - } - if !types.IssueType(issueType).IsValidWithCustom(customTypes) { - return nil, fmt.Errorf("invalid issue type: %s", issueType) - } - } + updates, err = DiscardNoopIssueUpdates(oldIssue, updates) + if err != nil { + return nil, err + } + if len(updates) == 0 { + return &UpdateResult{OldIssue: oldIssue, IsWisp: isWisp, Changed: false}, nil } - // Bound the VARCHAR(255) assignment columns before touching SQL, so an - // over-length assignee/owner aborts with a typed ErrFieldTooLong instead of - // a raw backend "data too long" error. Create validates these via - // ValidateWithCustom; the generic update path does not, so guard it here. - for _, field := range []string{"assignee", "owner"} { - if raw, ok := updates[field]; ok { - if val, ok := raw.(string); ok { - if err := types.CheckFieldLen(field, val); err != nil { - return nil, err - } - } - } + if err := ValidateScalarUpdates(ctx, tx, updates); err != nil { + return nil, err } // Build SET clauses. @@ -351,13 +339,23 @@ func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string if aerr != nil { return nil, fmt.Errorf("affected by status change for %s: %w", id, aerr) } - if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil { + recompute, err := RecomputeIsBlockedInTxWithResult(ctx, tx, affectedIssues, affectedWisps) + if err != nil { return nil, fmt.Errorf("recompute is_blocked after status change for %s: %w", id, err) } + return &UpdateResult{OldIssue: oldIssue, IsWisp: isWisp, Changed: true, IssueRowsChanged: !isWisp || recompute.IssueRowsChanged, WispRowsChanged: isWisp || recompute.WispRowsChanged}, nil } } - return &UpdateResult{OldIssue: oldIssue, IsWisp: isWisp}, nil + return &UpdateResult{OldIssue: oldIssue, IsWisp: isWisp, Changed: true, IssueRowsChanged: !isWisp, WispRowsChanged: isWisp}, nil +} + +func cloneUpdateFields(updates map[string]interface{}) map[string]interface{} { + cloned := make(map[string]interface{}, len(updates)) + for key, value := range updates { + cloned[key] = value + } + return cloned } // Merge-operation update keys. Unlike plain column updates, these are resolved @@ -369,8 +367,8 @@ const ( // OpMergeMetadata merges a JSON object's top-level keys into the issue's // metadata (bd update --metadata). Value: string, []byte, or json.RawMessage. OpMergeMetadata = "_merge_metadata" - // OpSetMetadata sets individual key=value metadata entries - // (bd update --set-metadata). Value: []string. + // OpSetMetadata sets individual metadata entries. CLI callers use []string + // key=value values; public issue operations use map[string]json.RawMessage. OpSetMetadata = "_set_metadata" // OpUnsetMetadata removes metadata keys (bd update --unset-metadata). // Value: []string. @@ -419,6 +417,216 @@ func ResolveMergeOps(oldIssue *types.Issue, updates map[string]interface{}) (map return resolved, nil } +// DiscardNoopIssueUpdates removes concrete updates whose value already matches +// the row read by the caller. This keeps idempotent updates from advancing the +// row version or recording an event. +func DiscardNoopIssueUpdates(oldIssue *types.Issue, updates map[string]interface{}) (map[string]interface{}, error) { + filtered := make(map[string]interface{}, len(updates)) + for key, value := range updates { + unchanged, err := issueFieldMatches(oldIssue, key, value) + if err != nil { + return nil, err + } + if !unchanged { + filtered[key] = value + } + } + return filtered, nil +} + +func issueFieldMatches(issue *types.Issue, key string, value interface{}) (bool, error) { + switch key { + case "title": + return matchesString(issue.Title, value), nil + case "description": + return matchesString(issue.Description, value), nil + case "design": + return matchesString(issue.Design, value), nil + case "acceptance_criteria": + return matchesString(issue.AcceptanceCriteria, value), nil + case "notes": + return matchesString(issue.Notes, value), nil + case "spec_id": + return matchesString(issue.SpecID, value), nil + case "await_id": + return matchesString(issue.AwaitID, value), nil + case "status": + return matchesStatus(issue.Status, value), nil + case "priority": + return matchesInt(issue.Priority, value), nil + case "issue_type": + return matchesIssueType(issue.IssueType, value), nil + case "assignee": + return matchesString(issue.Assignee, value), nil + case "owner": + return matchesString(issue.Owner, value), nil + case "estimated_minutes": + return matchesIntPointer(issue.EstimatedMinutes, value), nil + case "external_ref": + return matchesStringPointer(issue.ExternalRef, value), nil + case "started_at": + return matchesTimePointer(issue.StartedAt, value), nil + case "closed_at": + return matchesTimePointer(issue.ClosedAt, value), nil + case "due_at": + return matchesTimePointer(issue.DueAt, value), nil + case "defer_until": + return matchesTimePointer(issue.DeferUntil, value), nil + case "close_reason": + return matchesString(issue.CloseReason, value), nil + case "closed_by_session": + return matchesString(issue.ClosedBySession, value), nil + case "source_repo": + return matchesString(issue.SourceRepo, value), nil + case "sender": + return matchesString(issue.Sender, value), nil + case "wisp": + return matchesBool(issue.Ephemeral, value), nil + case "wisp_type": + return matchesWispType(issue.WispType, value), nil + case "no_history": + return matchesBool(issue.NoHistory, value), nil + case "pinned": + return matchesBool(issue.Pinned, value), nil + case "mol_type": + return matchesMolType(issue.MolType, value), nil + case "event_category", "event_kind": + return matchesString(issue.EventKind, value), nil + case "event_actor", "actor": + return matchesString(issue.Actor, value), nil + case "event_target", "target": + return matchesString(issue.Target, value), nil + case "event_payload", "payload": + return matchesString(issue.Payload, value), nil + case "waiters": + waiters, ok := value.([]string) + return ok && slices.Equal(issue.Waiters, waiters), nil + case "metadata": + current, err := normalizedMetadata(issue.Metadata) + if err != nil { + return false, err + } + candidate, err := storage.NormalizeMetadataValue(value) + if err != nil { + return false, err + } + return current == candidate, nil + default: + return false, nil + } +} + +func matchesString(current string, candidate interface{}) bool { + switch value := candidate.(type) { + case nil: + return current == "" + case string: + return current == value + default: + return false + } +} + +func matchesInt(current int, candidate interface{}) bool { + value, ok := candidate.(int) + return ok && current == value +} + +func matchesBool(current bool, candidate interface{}) bool { + value, ok := candidate.(bool) + return ok && current == value +} + +func matchesStatus(current types.Status, candidate interface{}) bool { + switch value := candidate.(type) { + case string: + return current == types.Status(value) + case types.Status: + return current == value + default: + return false + } +} + +func matchesIssueType(current types.IssueType, candidate interface{}) bool { + switch value := candidate.(type) { + case string: + return current == types.IssueType(value) + case types.IssueType: + return current == value + default: + return false + } +} + +func matchesWispType(current types.WispType, candidate interface{}) bool { + switch value := candidate.(type) { + case string: + return current == types.WispType(value) + case types.WispType: + return current == value + default: + return false + } +} + +func matchesMolType(current types.MolType, candidate interface{}) bool { + switch value := candidate.(type) { + case string: + return current == types.MolType(value) + case types.MolType: + return current == value + default: + return false + } +} + +func matchesIntPointer(current *int, candidate interface{}) bool { + switch value := candidate.(type) { + case nil: + return current == nil + case *int: + return (current == nil && value == nil) || (current != nil && value != nil && *current == *value) + case int: + return current != nil && *current == value + default: + return false + } +} + +func matchesStringPointer(current *string, candidate interface{}) bool { + switch value := candidate.(type) { + case nil: + return current == nil + case *string: + return (current == nil && value == nil) || (current != nil && value != nil && *current == *value) + case string: + return current != nil && *current == value + default: + return false + } +} + +func matchesTimePointer(current *time.Time, candidate interface{}) bool { + switch value := candidate.(type) { + case nil: + return current == nil + case *time.Time: + return (current == nil && value == nil) || (current != nil && value != nil && current.Equal(*value)) + case time.Time: + return current != nil && current.Equal(value) + default: + return false + } +} + +func normalizedMetadata(value json.RawMessage) (string, error) { + if len(value) == 0 { + return "{}", nil + } + return storage.NormalizeMetadataValue(value) +} + // isMergeOpKey reports whether k is a read-merge-write operation key consumed by // ResolveMergeOps rather than a concrete column value to pass through unchanged. func isMergeOpKey(k string) bool { @@ -458,15 +666,21 @@ func resolveMetadataMergeOps(oldIssue *types.Issue, updates, resolved map[string current = merged } if hasSet || hasUnset { - set, err := mergeOpStrings(OpSetMetadata, updates[OpSetMetadata], hasSet) - if err != nil { - return err - } unset, err := mergeOpStrings(OpUnsetMetadata, updates[OpUnsetMetadata], hasUnset) if err != nil { return err } - merged, err := storage.ApplyMetadataEdits(current, set, unset) + var merged json.RawMessage + if set, typed := updates[OpSetMetadata].(map[string]json.RawMessage); typed { + merged, err = applyTypedMetadataEdits(current, set, unset) + } else { + var set []string + set, err = mergeOpStrings(OpSetMetadata, updates[OpSetMetadata], hasSet) + if err != nil { + return err + } + merged, err = storage.ApplyMetadataEdits(current, set, unset) + } if err != nil { return fmt.Errorf("metadata edit failed: %w", err) } @@ -481,6 +695,43 @@ func resolveMetadataMergeOps(oldIssue *types.Issue, updates, resolved map[string return nil } +func applyTypedMetadataEdits(existing json.RawMessage, set map[string]json.RawMessage, unset []string) (json.RawMessage, error) { + data := make(map[string]json.RawMessage) + if len(existing) > 0 { + trimmed := strings.TrimSpace(string(existing)) + if trimmed != "" && trimmed != "null" { + if err := json.Unmarshal(existing, &data); err != nil { + return nil, fmt.Errorf("existing metadata is not a JSON object: %w", err) + } + } + } + keys := make([]string, 0, len(set)) + for key := range set { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + if err := storage.ValidateMetadataKey(key); err != nil { + return nil, err + } + if !json.Valid(set[key]) { + return nil, fmt.Errorf("metadata value for key %q is not valid JSON", key) + } + data[key] = set[key] + } + for _, key := range unset { + if err := storage.ValidateMetadataKey(key); err != nil { + return nil, err + } + delete(data, key) + } + result, err := json.Marshal(data) + if err != nil { + return nil, fmt.Errorf("failed to marshal metadata: %w", err) + } + return json.RawMessage(result), nil +} + // resolveNotesAppendOp folds OpAppendNotes into a concrete "notes" value on // resolved, appending to oldIssue.Notes (read in the same mutation transaction). // It is a no-op when the append op is absent. @@ -490,7 +741,7 @@ func resolveNotesAppendOp(oldIssue *types.Issue, updates, resolved map[string]in return nil } if _, direct := resolved["notes"]; direct { - return fmt.Errorf("cannot combine a notes replacement with %s", OpAppendNotes) + return fmt.Errorf("%w: cannot combine a notes replacement with %s", storage.ErrValidation, OpAppendNotes) } text, ok := raw.(string) if !ok { diff --git a/internal/storage/issueops/update_mergeops_test.go b/internal/storage/issueops/update_mergeops_test.go new file mode 100644 index 000000000..2c9a160fb --- /dev/null +++ b/internal/storage/issueops/update_mergeops_test.go @@ -0,0 +1,72 @@ +package issueops + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func TestResolveMergeOpsTypedMetadataSetPreservesJSONValuesAndOrder(t *testing.T) { + resolved, err := ResolveMergeOps(&types.Issue{Metadata: json.RawMessage(`{"keep":"yes","remove":"gone","overlap":"old"}`)}, map[string]any{ + OpMergeMetadata: json.RawMessage(`{"merged":{"source":"merge"},"overlap":"merged"}`), + OpSetMetadata: map[string]json.RawMessage{ + "nested": json.RawMessage(`{"enabled":true}`), + "number": json.RawMessage(`7`), + "bool": json.RawMessage(`true`), + "overlap": json.RawMessage(`"set"`), + }, + OpUnsetMetadata: []string{"overlap", "remove"}, + }) + if err != nil { + t.Fatalf("ResolveMergeOps() error = %v", err) + } + var metadata map[string]any + if err := json.Unmarshal(resolved["metadata"].(json.RawMessage), &metadata); err != nil { + t.Fatalf("unmarshal resolved metadata: %v", err) + } + if metadata["keep"] != "yes" || metadata["number"] != float64(7) || metadata["bool"] != true { + t.Fatalf("metadata = %#v", metadata) + } + if _, ok := metadata["overlap"]; ok { + t.Fatalf("metadata overlap survived unset: %#v", metadata) + } + if _, ok := metadata["remove"]; ok { + t.Fatalf("metadata remove survived unset: %#v", metadata) + } +} + +func TestResolveMergeOpsSetMetadataKeepsCLIListForms(t *testing.T) { + for _, set := range []any{ + []string{"first=one", "second=two"}, + []any{"first=one", "second=two"}, + } { + resolved, err := ResolveMergeOps(&types.Issue{Metadata: json.RawMessage(`{"keep":"yes"}`)}, map[string]any{OpSetMetadata: set}) + if err != nil { + t.Fatalf("ResolveMergeOps(%T) error = %v", set, err) + } + var metadata map[string]any + if err := json.Unmarshal(resolved["metadata"].(json.RawMessage), &metadata); err != nil { + t.Fatalf("unmarshal resolved metadata: %v", err) + } + if metadata["keep"] != "yes" || metadata["first"] != "one" || metadata["second"] != "two" { + t.Fatalf("ResolveMergeOps(%T) metadata = %#v", set, metadata) + } + } +} + +func TestResolveMergeOpsSurfacesUntypedSetMetadataFailure(t *testing.T) { + for _, set := range []any{ + []string{"missing-separator"}, + []any{"missing-separator"}, + } { + resolved, err := ResolveMergeOps(&types.Issue{Metadata: json.RawMessage(`{"keep":"yes"}`)}, map[string]any{OpSetMetadata: set}) + if err == nil { + t.Fatalf("ResolveMergeOps(%T) error = nil, want a metadata edit failure; resolved = %#v", set, resolved) + } + if !strings.Contains(err.Error(), "metadata edit failed") { + t.Fatalf("ResolveMergeOps(%T) error = %v, want it wrapped as a metadata edit failure", set, err) + } + } +} diff --git a/internal/storage/issueops/update_validation_test.go b/internal/storage/issueops/update_validation_test.go new file mode 100644 index 000000000..d1834583c --- /dev/null +++ b/internal/storage/issueops/update_validation_test.go @@ -0,0 +1,50 @@ +package issueops + +import ( + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage" + publicops "github.com/steveyegge/beads/issueops" +) + +func TestValidateUpdateRequestRejectsInvalidCanonicalFields(t *testing.T) { + negative := -1 + for _, tc := range []struct { + name string + patch publicops.IssuePatch + }{ + {"priority above range", publicops.IssuePatch{Priority: publicops.Field[int]{Set: true, Value: 9}}}, + {"empty title", publicops.IssuePatch{Title: publicops.Field[string]{Set: true}}}, + {"title over byte limit", publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: strings.Repeat("t", 501)}}}, + {"negative estimate", publicops.IssuePatch{EstimatedMinutes: publicops.Field[*int]{Set: true, Value: &negative}}}, + {"unknown persistence mode", publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: "archived"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateUpdateRequest(publicops.UpdateRequest{Actor: "actor", IssueID: "bd-validate", Patch: tc.patch}) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateUpdateRequest() error = %v, want ErrValidation", err) + } + }) + } +} + +func TestApplyMetadataPatchRejectsUnsafeKeysAndNullMerge(t *testing.T) { + for _, tc := range []struct { + name string + patch publicops.MetadataPatch + }{ + {"set key with unsafe characters", publicops.MetadataPatch{Set: map[string]json.RawMessage{"bad-key": json.RawMessage(`"value"`)}}}, + {"unset key with unsafe characters", publicops.MetadataPatch{Unset: []string{"bad-key"}}}, + {"null merge payload", publicops.MetadataPatch{Merge: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`null`)}}}, + } { + t.Run(tc.name, func(t *testing.T) { + next, changed, err := ApplyMetadataPatch(json.RawMessage(`{"keep":"yes"}`), tc.patch) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ApplyMetadataPatch() = %s, %t, %v; want ErrValidation", next, changed, err) + } + }) + } +} diff --git a/internal/storage/issueops/version_commit.go b/internal/storage/issueops/version_commit.go new file mode 100644 index 000000000..dc17814ed --- /dev/null +++ b/internal/storage/issueops/version_commit.go @@ -0,0 +1,26 @@ +package issueops + +import "context" + +// deferVersionCommitKey marks a context whose guarded issue operations must +// leave their writes in the Dolt working set instead of creating a version +// commit. +type deferVersionCommitKey struct{} + +// WithDeferredVersionCommit returns a context whose guarded issue operations +// skip the Dolt version commit they would otherwise create. The SQL write still +// commits; only the version commit is deferred to a later explicit commit point. +// +// `bd --dolt-auto-commit batch` needs this: batch mode exists to avoid one +// version commit per issue, and the commit point for the write verbs lives +// inside the storage layer, so the CLI has no commit message to blank the way +// it does on the RunInTransaction path. +func WithDeferredVersionCommit(ctx context.Context) context.Context { + return context.WithValue(ctx, deferVersionCommitKey{}, true) +} + +// VersionCommitDeferred reports whether ctx defers version commits. +func VersionCommitDeferred(ctx context.Context) bool { + deferred, _ := ctx.Value(deferVersionCommitKey{}).(bool) + return deferred +} diff --git a/internal/storage/sqlbuild/sqlbuild.go b/internal/storage/sqlbuild/sqlbuild.go index 6a1890575..4e42d1c40 100644 --- a/internal/storage/sqlbuild/sqlbuild.go +++ b/internal/storage/sqlbuild/sqlbuild.go @@ -38,7 +38,7 @@ const DepTargetExpr = "COALESCE(depends_on_issue_id, depends_on_wisp_id, depends const IssueBaseColumns = `id, content_hash, title, description, design, acceptance_criteria, notes, status, priority, issue_type, assignee, estimated_minutes, created_at, created_by, owner, updated_at, started_at, closed_at, external_ref, spec_id, - compaction_level, compacted_at, compacted_at_commit, original_size, source_repo, close_reason, + compaction_level, compacted_at, compacted_at_commit, original_size, source_repo, close_reason, closed_by_session, sender, ephemeral, no_history, wisp_type, pinned, is_template, await_type, await_id, timeout_ns, waiters, mol_type, diff --git a/internal/storage/storage.go b/internal/storage/storage.go index cd5ef7795..cbc544bc4 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -13,28 +13,37 @@ import ( "time" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" ) -// ErrAlreadyClaimed is returned when attempting to claim an issue that is already -// claimed by another user. The error message contains the current assignee. -var ErrAlreadyClaimed = errors.New("issue already claimed") +// The guarded issue-operation error vocabulary is declared and documented by +// the public contract package, github.com/steveyegge/beads/issueops. These are +// the same values, so every storage.ErrX reference and every errors.Is site +// keeps matching the identical error. +var ( + ErrAlreadyClaimed = issueops.ErrAlreadyClaimed + ErrNotClaimable = issueops.ErrNotClaimable + ErrAssigneeMismatch = issueops.ErrAssigneeMismatch + ErrNotFound = issueops.ErrNotFound + ErrValidation = issueops.ErrValidation + ErrNotInitialized = issueops.ErrNotInitialized + ErrPrefixMismatch = issueops.ErrPrefixMismatch + ErrCloseBlocked = issueops.ErrCloseBlocked + ErrCloseOpenChildren = issueops.ErrCloseOpenChildren + ErrAlreadyExists = issueops.ErrAlreadyExists + ErrVersionMismatch = issueops.ErrVersionMismatch + ErrStatusMismatch = issueops.ErrStatusMismatch +) -// ErrNotClaimable is returned when attempting to claim an issue that is not in a -// claimable state, such as closed, deferred, or already in progress without the -// same actor owning the claim. -var ErrNotClaimable = errors.New("issue not claimable") +// CloseOpenChildrenError reports the issue and open-child count that refused a +// guarded close. See issueops.CloseOpenChildrenError. +type CloseOpenChildrenError = issueops.CloseOpenChildrenError // ErrNotOwner is returned when an actor tries to unclaim an issue that is claimed // by a different actor. Releasing another actor's claim requires the force // escape hatch (bd unclaim --force), reserved for admin/reaper use. var ErrNotOwner = errors.New("issue claimed by a different actor") -// ErrAssigneeMismatch is returned by UnclaimIssueIfAssignee when the issue's -// current assignee does not match the expected assignee (including when the -// issue is no longer assigned at all). The caller's view of the claim was -// stale; the issue is left untouched. -var ErrAssigneeMismatch = errors.New("assignee mismatch") - // ClaimedByFragment and NotClaimableStatusFragment are the exact message // fragments the claim path (issueops/claim.go) appends after the sentinel to // carry the conflicting assignee/status: ErrAlreadyClaimed is wrapped as @@ -48,33 +57,6 @@ const ( NotClaimableStatusFragment = ": status " ) -// ErrNotFound is returned when a requested entity does not exist in the database. -var ErrNotFound = errors.New("not found") - -// ErrNotInitialized is returned when the database has not been initialized -// (e.g., issue_prefix config is missing). -var ErrNotInitialized = errors.New("database not initialized") - -// ErrPrefixMismatch is returned when an issue ID does not match the configured prefix. -var ErrPrefixMismatch = errors.New("prefix mismatch") - -// ErrCloseBlocked is returned by CloseIssueChecked when an issue cannot be -// closed because it is still blocked (is_blocked=1: an open blocking dependency -// or an open blocking gate). Bypass with CloseIssueOptions.Force. -var ErrCloseBlocked = errors.New("cannot close blocked issue") - -// ErrVersionMismatch is returned by a *Checked op given an ExpectedVersion that -// no longer matches the row's current version (row_lock) — an optimistic -// concurrency failure. Callers errors.Is it to distinguish a lost-update -// precondition from other errors. -var ErrVersionMismatch = errors.New("version mismatch") - -// ErrStatusMismatch is returned by UpdateIssueChecked given an ExpectedStatus -// that no longer matches the issue's current status. The caller's view of the -// issue was stale; the issue is left untouched. The assignee analog is -// ErrAssigneeMismatch, shared with UnclaimIssueIfAssignee. -var ErrStatusMismatch = errors.New("status mismatch") - // CommentPageCursor is the resume position for a keyset page of an issue's // comments: the (created_at, id) of the last comment already returned. The zero // value starts a walk from the beginning of the thread. @@ -97,6 +79,16 @@ type CommentPageCursor struct { // implementations; such additions are called out in CHANGELOG.md and the // examples/library-usage guide so implementers have a migration path. type Storage interface { + // IssueLifecycle returns the guarded issue-lifecycle surface for this + // store. Every decorator in a store's chain answers for itself and layers + // its own behavior onto the inner result, so the returned Lifecycle carries + // the same hook and telemetry layers the store itself carries. + // + // A capability the lifecycle role does not cover gets its own role + // interface and its own accessor here; it does not get appended to + // issueops.Lifecycle. + IssueLifecycle() (issueops.Lifecycle, error) + // Issue CRUD CreateIssue(ctx context.Context, issue *types.Issue, actor string) error CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error @@ -117,8 +109,9 @@ type Storage interface { UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error UpdateIssueType(ctx context.Context, id string, issueType string, actor string) error CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error - // CloseIssueChecked closes an issue, but refuses with ErrCloseBlocked when - // the issue has a live direct blocker (an open blocks/waits-for/ + // CloseIssueChecked closes an issue, but refuses with ErrCloseOpenChildren + // when it has open parent-child dependents, or ErrCloseBlocked when it has a + // live direct blocker (an open blocks/waits-for/ // conditional-blocks edge) unless opts.Force is set — the historical // `bd close` guard. A bare is_blocked=1 with no live direct blocker (a purely // transitive parent-child block, or a stale column) is not refused. The @@ -309,7 +302,7 @@ type CloseIssueOptions struct { // ErrVersionMismatch atomically (the version read and the close share one // transaction). nil disables the check, leaving behavior unchanged. It is a // pointer, not an int64, so nil ("no check") is distinct from a caller that - // requires version 0. Force bypasses only the is_blocked guard, not this + // requires version 0. Force bypasses child and blocker policy, not this // version check. // // RowVersion tracks lifecycle/ownership writes only — it is rewritten by @@ -324,7 +317,8 @@ type CloseIssueOptions struct { // CloseIssueResult reports the outcome of CloseIssueChecked. type CloseIssueResult struct { - Unchanged bool // true when the issue was ALREADY closed (idempotent no-op) + Unchanged bool // true when the issue was ALREADY closed (idempotent no-op) + OpenChildren int // nonzero when Force encountered open children, including idempotent re-closes } // UpdateIssueOptions carries the optional inputs to UpdateIssueChecked. @@ -390,6 +384,7 @@ type FastStatisticsStore interface { // EmbeddedDoltStore satisfy this interface. type DoltStorage interface { Storage + IssueLifecycleStore VersionControl HistoryViewer RemoteStore @@ -685,6 +680,22 @@ type Transaction interface { EventsSince(ctx context.Context, cursor EventCursor, issueID string, limit int) ([]*types.Event, error) } +// IssueLifecycleTransaction is the internal transaction lane for lifecycle +// transitions that must retain the backend's durable publication semantics. +// It deliberately extends neither Storage nor Transaction: ordinary callers +// continue to use the stable generic transaction contract. +type IssueLifecycleTransaction interface { + Transaction + ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) +} + +// IssueLifecycleStore runs a lifecycle-aware transaction. It is an internal +// companion to Storage for code that must close or reopen within one durable +// operation and observe the result before committing. +type IssueLifecycleStore interface { + RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx IssueLifecycleTransaction) error) error +} + // DependencyAddOptions controls dependency insertion for both the store-level // AddDependencyWithOptions and the transaction-scoped AddDependencyWithOptions. type DependencyAddOptions struct { diff --git a/internal/storage/uow/closed_by_session_dolt_test.go b/internal/storage/uow/closed_by_session_dolt_test.go new file mode 100644 index 000000000..d400c47d1 --- /dev/null +++ b/internal/storage/uow/closed_by_session_dolt_test.go @@ -0,0 +1,78 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// TestIssueOperationsCloseSessionSurvivesAllPersistenceMovesWithRealDolt +// verifies the public UOW result preserves close provenance after every +// directed persistence transition between durable and wisp-backed records. +func TestIssueOperationsCloseSessionSurvivesAllPersistenceMovesWithRealDolt(t *testing.T) { + ctx := context.Background() + provider := newTestUOWProvider(t) + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if err := uw.ConfigUseCase().SetConfig(ctx, "issue_prefix", "bd"); err != nil { + return "", err + } + return "initialize close-session fixture", nil + }); err != nil { + t.Fatalf("initialize close-session fixture: %v", err) + } + + operations, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ID: "bd-close-session", Title: "close provenance", IssueType: types.TypeTask, Priority: 2}, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + + const session = "close-session-xyz" + assertSession := func(operation string, issue *issueops.Issue) { + t.Helper() + if issue == nil { + t.Fatalf("%s returned nil issue", operation) + } + if issue.ClosedBySession != session { + t.Fatalf("%s ClosedBySession = %q, want %q", operation, issue.ClosedBySession, session) + } + } + closed, err := operations.Close(ctx, issueops.CloseRequest{ + Actor: "tester", IssueID: created.Issue.ID, Session: session, + }) + if err != nil { + t.Fatalf("Close() error = %v", err) + } + assertSession("Close()", closed.Issue) + + // These transitions cover every directed pair of supported persistence + // modes: persistent<->ephemeral, persistent<->no_history, and + // ephemeral<->no_history. + for _, mode := range []issueops.PersistenceMode{ + issueops.PersistenceModeEphemeral, + issueops.PersistenceModePersistent, + issueops.PersistenceModeNoHistory, + issueops.PersistenceModeEphemeral, + issueops.PersistenceModeNoHistory, + issueops.PersistenceModePersistent, + } { + moved, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", IssueID: created.Issue.ID, + Patch: issueops.IssuePatch{ + Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: mode}, + }, + }) + if err != nil { + t.Fatalf("Update(persistence=%q) error = %v", mode, err) + } + assertSession("Update(persistence="+string(mode)+")", moved.Issue) + } +} diff --git a/internal/storage/uow/errors.go b/internal/storage/uow/errors.go index c47e8676b..a7c0fee61 100644 --- a/internal/storage/uow/errors.go +++ b/internal/storage/uow/errors.go @@ -7,7 +7,7 @@ import ( mysql "github.com/go-sql-driver/mysql" ) -// IsSerializationError reports whether err is a Dolt/MySQL serialization +// IsSerializationError reports whether err is a retryable database transaction // failure that guarantees the server rolled the transaction back. Because the // rollback discards every uncommitted write in the session, the only safe // retry is to redo the WHOLE unit of work (read, merge, write, commit) — @@ -17,16 +17,20 @@ func IsSerializationError(err error) bool { return isSerializationError(err) } -// isSerializationError returns true if the error is a Dolt/MySQL serialization -// failure that guarantees the transaction was rolled back. Safe to retry. -// - 1213 (ER_LOCK_DEADLOCK): concurrent transactions conflict at commit time -// - 1205 (ER_LOCK_WAIT_TIMEOUT): lock wait exceeded, transaction rolled back +// isSerializationError returns true when a MySQL or PostgreSQL transaction +// error guarantees the transaction was rolled back. Safe to retry. +// - MySQL 1213 (ER_LOCK_DEADLOCK) and 1205 (ER_LOCK_WAIT_TIMEOUT) +// - SQLSTATE 40001 (serialization failure) and 40P01 (deadlock detected) func isSerializationError(err error) bool { var mysqlErr *mysql.MySQLError - if !errors.As(err, &mysqlErr) { - return false + if errors.As(err, &mysqlErr) && (mysqlErr.Number == 1213 || mysqlErr.Number == 1205) { + return true } - return mysqlErr.Number == 1213 || mysqlErr.Number == 1205 + var stateErr interface{ SQLState() string } + if errors.As(err, &stateErr) { + return stateErr.SQLState() == "40001" || stateErr.SQLState() == "40P01" + } + return false } // isDatabaseExistsError reports whether err is the server refusing a bare diff --git a/internal/storage/uow/issue_operations.go b/internal/storage/uow/issue_operations.go new file mode 100644 index 000000000..75ae22fb4 --- /dev/null +++ b/internal/storage/uow/issue_operations.go @@ -0,0 +1,502 @@ +package uow + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "sort" + "time" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/dberrors" + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// issueOperations runs public issue mutations through a unit of work. +type issueOperations struct { + provider UnitOfWorkProvider +} + +// IssueLifecycle returns the guarded issue-lifecycle surface for this +// provider. A unit of work is not a special case: callers reach the verbs +// through the same accessor they use on a store. +func (p *doltSQLProvider) IssueLifecycle() (publicops.Lifecycle, error) { + return NewIssueOperations(p) +} + +// NewIssueOperations constructs public issue operations backed by provider. +func NewIssueOperations(provider UnitOfWorkProvider) (publicops.Lifecycle, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new issue operations: unit-of-work provider must not be nil") + } + return &issueOperations{provider: provider}, nil +} + +func isNilUnitOfWorkProvider(provider UnitOfWorkProvider) bool { + if provider == nil { + return true + } + value := reflect.ValueOf(provider) + switch value.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return value.IsNil() + default: + return false + } +} + +var _ publicops.Lifecycle = (*issueOperations)(nil) + +// Create creates one issue in a retried unit-of-work transaction. +func (o *issueOperations) Create(ctx context.Context, request publicops.CreateRequest) (publicops.CreateResult, error) { + snapshot := storageissueops.CloneCreateRequest(request) + if err := storageissueops.ValidatePublicCreateRequest(snapshot); err != nil { + return publicops.CreateResult{}, err + } + return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.CreateResult, string, error) { + attempt := storageissueops.CloneCreateRequest(snapshot) + createContext, err := uw.ConfigUseCase().LoadCreateContext(ctx) + if err != nil { + return publicops.CreateResult{}, "", err + } + attempt, err = storageissueops.PreparePublicCreateRequest(attempt, storageissueops.PublicCreateContext{ + IssuePrefix: createContext.IssuePrefix, + AllowedPrefixes: createContext.AllowedPrefixes, + CustomStatuses: types.CustomStatusNames(createContext.CustomStatuses), + CustomTypes: createContext.CustomTypes, + }) + if err != nil { + return publicops.CreateResult{}, "", err + } + // Configured infra types live in the wisp tables, the same routing the + // stores' own CreateIssue applies (internal/storage/dolt/issues.go) and + // the public facade applies in issueops.ExecuteCreate. Mark the issue + // before createParams reads it so ID minting and table routing agree on + // the destination. A no-history create keeps its own retention mode and + // already routes to wisps. + if attempt.Issue != nil && !attempt.Issue.Ephemeral && !attempt.Issue.NoHistory && createContext.InfraTypes[string(attempt.Issue.IssueType)] { + attempt.Issue.Ephemeral = true + } + params, useWisp, err := createParams(attempt) + if err != nil { + return publicops.CreateResult{}, "", validationError(err) + } + var created domain.CreateIssueResult + if useWisp { + created, err = uw.IssueUseCase().CreateWisp(ctx, params, attempt.Actor) + } else { + created, err = uw.IssueUseCase().CreateIssue(ctx, params, attempt.Actor) + } + if err != nil { + return publicops.CreateResult{}, "", storageissueops.ClassifyPublicCreateError(err) + } + issue, err := hydrateIssueOperation(ctx, uw, created.Issue, true) + if err != nil { + return publicops.CreateResult{}, "", err + } + return publicops.CreateResult{Issue: issue}, "create issue", nil + }) +} + +func createParams(request publicops.CreateRequest) (domain.CreateIssueParams, bool, error) { + if request.Issue == nil { + return domain.CreateIssueParams{}, false, fmt.Errorf("create: issue must not be nil") + } + issue := storageissueops.CloneCreateRequest(publicops.CreateRequest{Issue: request.Issue}).Issue + params := domain.CreateIssueParams{ + Issue: issue, + ExplicitID: issue.ID, + ParentID: request.ParentID, + Labels: append([]string(nil), issue.Labels...), + InheritLabelsFromParent: request.InheritLabelsFromParent, + ForcePrefix: request.ForceIDPrefix, + CreateOnly: true, + } + for _, dependency := range request.Dependencies { + params.Dependencies = append(params.Dependencies, domain.DependencySpec{ + Type: dependency.Type, + TargetID: dependency.TargetID, + SwapDirection: dependency.Reverse, + Metadata: dependency.Metadata, + ThreadID: dependency.ThreadID, + }) + } + if request.WaitsFor != nil { + params.WaitsFor = &domain.WaitsForSpec{SpawnerID: request.WaitsFor.SpawnerID, Gate: request.WaitsFor.Gate} + } + return params, issue.Ephemeral || issue.NoHistory, nil +} + +func hydrateIssueOperation(ctx context.Context, uw UnitOfWork, issue *types.Issue, includeComments bool) (*types.Issue, error) { + if issue == nil { + return nil, fmt.Errorf("hydrate issue operation: created issue is nil") + } + stored, useWisp, err := operationIssue(ctx, uw, issue.ID) + if err != nil { + return nil, fmt.Errorf("hydrate issue operation: %w", err) + } + clone := storageissueops.CloneCreateRequest(publicops.CreateRequest{Issue: stored}).Issue + if !includeComments { + clone.Comments = nil + } + labels := uw.LabelUseCase() + if labels == nil { + return nil, fmt.Errorf("hydrate issue labels: label use case is unavailable") + } + if useWisp { + clone.Labels, err = labels.GetWispLabels(ctx, clone.ID) + } else { + clone.Labels, err = labels.GetLabels(ctx, clone.ID) + } + if err != nil { + return nil, fmt.Errorf("hydrate issue labels: %w", err) + } + + dependencies := uw.DependencyUseCase() + if dependencies == nil { + return nil, fmt.Errorf("hydrate issue dependencies: dependency use case is unavailable") + } + var records map[string][]*types.Dependency + if useWisp { + records, err = dependencies.GetWispDependencyRecords(ctx, []string{clone.ID}) + } else { + records, err = dependencies.GetIssueDependencyRecords(ctx, []string{clone.ID}) + } + if err != nil { + return nil, fmt.Errorf("hydrate issue dependencies: %w", err) + } + clone.Dependencies = records[clone.ID] + + if includeComments { + comments := uw.CommentUseCase() + if comments == nil { + return nil, fmt.Errorf("hydrate issue comments: comment use case is unavailable") + } + if useWisp { + clone.Comments, err = comments.GetCommentsForWisp(ctx, clone.ID) + } else { + clone.Comments, err = comments.GetCommentsForIssue(ctx, clone.ID) + } + if err != nil { + return nil, fmt.Errorf("hydrate issue comments: %w", err) + } + } + return storageissueops.CloneCreateRequest(publicops.CreateRequest{Issue: clone}).Issue, nil +} + +// Update updates one issue in a retried unit-of-work transaction. +func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRequest) (publicops.UpdateResult, error) { + snapshot := storageissueops.CloneUpdateRequest(request) + if err := validateUpdateRequest(snapshot); err != nil { + return publicops.UpdateResult{}, err + } + return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.UpdateResult, string, error) { + attempt := storageissueops.CloneUpdateRequest(snapshot) + spec, err := updateSpec(attempt) + if err != nil { + return publicops.UpdateResult{}, "", validationError(err) + } + before, _, err := operationIssue(ctx, uw, attempt.IssueID) + if err != nil { + return publicops.UpdateResult{}, "", err + } + before, err = hydrateIssueOperation(ctx, uw, before, false) + if err != nil { + return publicops.UpdateResult{}, "", err + } + claimChanged := attempt.Claim && (before.Status != types.StatusInProgress || before.Assignee != attempt.Actor) + updated, err := uw.IssueUseCase().ApplyUpdate(ctx, attempt.IssueID, spec, attempt.Actor) + if err != nil { + return publicops.UpdateResult{}, "", err + } + issue, err := hydrateIssueOperation(ctx, uw, updated, false) + if err != nil { + return publicops.UpdateResult{}, "", err + } + return publicops.UpdateResult{Issue: issue, Changed: claimChanged || !semanticIssueEqual(before, issue)}, "update issue", nil + }) +} + +func updateSpec(request publicops.UpdateRequest) (domain.UpdateSpec, error) { + fields := make(map[string]any) + patch := request.Patch + if err := validateMetadataPatch(patch.Metadata); err != nil { + return domain.UpdateSpec{}, validationError(err) + } + setField(fields, "title", patch.Title) + setField(fields, "description", patch.Description) + setField(fields, "design", patch.Design) + setField(fields, "acceptance_criteria", patch.AcceptanceCriteria) + setField(fields, "spec_id", patch.SpecID) + setField(fields, "await_id", patch.AwaitID) + setField(fields, "status", patch.Status) + setField(fields, "priority", patch.Priority) + if patch.IssueType.Set { + fields["issue_type"] = string(patch.IssueType.Value) + } + setField(fields, "assignee", patch.Assignee) + setField(fields, "owner", patch.Owner) + setField(fields, "closed_by_session", patch.ClosedBySession) + setField(fields, "estimated_minutes", patch.EstimatedMinutes) + setField(fields, "external_ref", patch.ExternalRef) + setField(fields, "due_at", patch.DueAt) + setField(fields, "defer_until", patch.DeferUntil) + if patch.Notes.Set && patch.AppendNotes.Set { + return domain.UpdateSpec{}, validationError(fmt.Errorf("update: notes and append notes cannot both be set")) + } + setField(fields, "notes", patch.Notes) + if patch.AppendNotes.Set { + fields[storageissueops.OpAppendNotes] = patch.AppendNotes.Value + } + if patch.Metadata.Replace.Set { + replacement := json.RawMessage("{}") + if len(patch.Metadata.Replace.Value) > 0 { + replacement = patch.Metadata.Replace.Value + } + if err := storageissueops.ValidateMetadataIfConfigured(replacement); err != nil { + return domain.UpdateSpec{}, validationError(err) + } + fields["metadata"] = replacement + } else { + if patch.Metadata.Merge.Set { + fields[storageissueops.OpMergeMetadata] = patch.Metadata.Merge.Value + } + if len(patch.Metadata.Set) > 0 { + fields[storageissueops.OpSetMetadata] = patch.Metadata.Set + } + if len(patch.Metadata.Unset) > 0 { + fields[storageissueops.OpUnsetMetadata] = patch.Metadata.Unset + } + } + var persistence *types.PersistenceMode + if patch.Persistence.Set { + value := patch.Persistence.Value + persistence = &value + } + var setLabels *([]string) + if patch.Labels.Replace.Set { + labels := append([]string(nil), patch.Labels.Replace.Value...) + setLabels = &labels + } + return domain.UpdateSpec{ + Fields: fields, + Claim: request.Claim, + ExpectedVersion: request.ExpectedVersion, + ExpectedAssignee: request.ExpectedAssignee, + ExpectedStatus: statusPointer(request.ExpectedStatus), + Persistence: persistence, + AddLabels: append([]string(nil), patch.Labels.Add...), + RemoveLabels: append([]string(nil), patch.Labels.Remove...), + SetLabels: setLabels, + Reparent: fieldStringPointer(patch.ParentID), + }, nil +} + +func setField[T any](fields map[string]any, name string, field publicops.Field[T]) { + if field.Set { + fields[name] = field.Value + } +} + +func fieldStringPointer(field publicops.Field[string]) *string { + if !field.Set { + return nil + } + value := field.Value + return &value +} + +func statusPointer(status *publicops.Status) *string { + if status == nil { + return nil + } + value := string(*status) + return &value +} + +// Close closes one issue in a retried unit-of-work transaction. +func (o *issueOperations) Close(ctx context.Context, request publicops.CloseRequest) (publicops.CloseResult, error) { + snapshot := storageissueops.CloneCloseRequest(request) + if err := validateCloseRequest(snapshot); err != nil { + return publicops.CloseResult{}, err + } + return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.CloseResult, string, error) { + attempt := storageissueops.CloneCloseRequest(snapshot) + issue, useWisp, err := operationIssue(ctx, uw, attempt.IssueID) + if err != nil { + return publicops.CloseResult{}, "", err + } + if attempt.ExpectedVersion != nil { + if _, err := uw.IssueUseCase().ApplyUpdate(ctx, attempt.IssueID, domain.UpdateSpec{ExpectedVersion: attempt.ExpectedVersion}, attempt.Actor); err != nil { + return publicops.CloseResult{}, "", err + } + } + before, err := hydrateIssueOperation(ctx, uw, issue, false) + if err != nil { + return publicops.CloseResult{}, "", err + } + var closed domain.CloseIssueResult + if useWisp { + closed, err = uw.IssueUseCase().CloseWispChecked(ctx, attempt.IssueID, domain.CloseIssueParams{Reason: attempt.Reason, Session: attempt.Session}, attempt.Actor, attempt.Force) + } else { + closed, err = uw.IssueUseCase().CloseIssueChecked(ctx, attempt.IssueID, domain.CloseIssueParams{Reason: attempt.Reason, Session: attempt.Session}, attempt.Actor, attempt.Force) + } + if err != nil { + return publicops.CloseResult{}, "", err + } + if closed.Issue != nil { + issue = closed.Issue + } + hydrated, err := hydrateIssueOperation(ctx, uw, issue, false) + if err != nil { + return publicops.CloseResult{}, "", err + } + return publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren}, "close issue", nil + }) +} + +// Reopen reopens one issue in a retried unit-of-work transaction. +func (o *issueOperations) Reopen(ctx context.Context, request publicops.ReopenRequest) (publicops.ReopenResult, error) { + snapshot := storageissueops.CloneReopenRequest(request) + if err := validateReopenRequest(snapshot); err != nil { + return publicops.ReopenResult{}, err + } + return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.ReopenResult, string, error) { + attempt := storageissueops.CloneReopenRequest(snapshot) + issue, useWisp, err := operationIssue(ctx, uw, attempt.IssueID) + if err != nil { + return publicops.ReopenResult{}, "", err + } + if attempt.ExpectedVersion != nil { + if _, err := uw.IssueUseCase().ApplyUpdate(ctx, attempt.IssueID, domain.UpdateSpec{ExpectedVersion: attempt.ExpectedVersion}, attempt.Actor); err != nil { + return publicops.ReopenResult{}, "", err + } + } + before, err := hydrateIssueOperation(ctx, uw, issue, false) + if err != nil { + return publicops.ReopenResult{}, "", err + } + var reopened domain.ReopenIssueResult + if useWisp { + reopened, err = uw.IssueUseCase().ReopenWisp(ctx, attempt.IssueID, domain.ReopenIssueParams{Reason: attempt.Reason}, attempt.Actor) + } else { + reopened, err = uw.IssueUseCase().ReopenIssue(ctx, attempt.IssueID, domain.ReopenIssueParams{Reason: attempt.Reason}, attempt.Actor) + } + if err != nil { + return publicops.ReopenResult{}, "", err + } + if reopened.Issue != nil { + issue = reopened.Issue + } + hydrated, err := hydrateIssueOperation(ctx, uw, issue, false) + if err != nil { + return publicops.ReopenResult{}, "", err + } + return publicops.ReopenResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated)}, "reopen issue", nil + }) +} + +func operationIssue(ctx context.Context, uw UnitOfWork, id string) (*types.Issue, bool, error) { + issue, err := uw.IssueUseCase().GetWisp(ctx, id) + if err == nil && issue != nil { + return issue, true, nil + } + if err != nil && !errors.Is(err, publicops.ErrNotFound) && !dberrors.IsNoRows(err) { + return nil, false, fmt.Errorf("read wisp %s: %w", id, err) + } + issue, err = uw.IssueUseCase().GetIssue(ctx, id) + if err != nil { + if errors.Is(err, publicops.ErrNotFound) || dberrors.IsNoRows(err) { + return nil, false, fmt.Errorf("%w: issue %s", publicops.ErrNotFound, id) + } + return nil, false, err + } + if issue == nil { + return nil, false, fmt.Errorf("%w: issue %s", publicops.ErrNotFound, id) + } + return issue, false, nil +} + +func validationError(err error) error { + if errors.Is(err, publicops.ErrValidation) { + return err + } + return fmt.Errorf("%w: %w", publicops.ErrValidation, err) +} + +func validateUpdateRequest(request publicops.UpdateRequest) error { + if request.Actor == "" || request.IssueID == "" { + return validationError(fmt.Errorf("update: actor and issue ID must not be empty")) + } + if err := storageissueops.ValidateUpdateRequest(request); err != nil { + return validationError(err) + } + if err := validateMetadataPatch(request.Patch.Metadata); err != nil { + return validationError(err) + } + return nil +} + +func validateCloseRequest(request publicops.CloseRequest) error { + if request.Actor == "" || request.IssueID == "" { + return validationError(fmt.Errorf("close: actor and issue ID must not be empty")) + } + return nil +} + +func validateMetadataPatch(metadata publicops.MetadataPatch) error { + if metadata.Replace.Set && (metadata.Merge.Set || len(metadata.Set) > 0 || len(metadata.Unset) > 0) { + return fmt.Errorf("metadata replacement cannot combine with incremental edits") + } + if metadata.Replace.Set && len(metadata.Replace.Value) > 0 && !json.Valid(metadata.Replace.Value) { + return fmt.Errorf("metadata replacement is not valid JSON") + } + if metadata.Merge.Set { + var object map[string]json.RawMessage + if len(metadata.Merge.Value) == 0 || json.Unmarshal(metadata.Merge.Value, &object) != nil || object == nil { + return fmt.Errorf("metadata merge must be a JSON object") + } + } + keys := make([]string, 0, len(metadata.Set)) + for key := range metadata.Set { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + if err := storage.ValidateMetadataKey(key); err != nil { + return err + } + if !json.Valid(metadata.Set[key]) { + return fmt.Errorf("metadata value for key %q is not valid JSON", key) + } + } + for _, key := range metadata.Unset { + if err := storage.ValidateMetadataKey(key); err != nil { + return err + } + } + return nil +} + +func validateReopenRequest(request publicops.ReopenRequest) error { + if request.Actor == "" || request.IssueID == "" { + return validationError(fmt.Errorf("reopen: actor and issue ID must not be empty")) + } + return nil +} + +func semanticIssueEqual(left, right *types.Issue) bool { + if left == nil || right == nil { + return left == right + } + leftCopy := *left + rightCopy := *right + leftCopy.UpdatedAt, rightCopy.UpdatedAt = time.Time{}, time.Time{} + leftCopy.RowVersion, rightCopy.RowVersion = 0, 0 + return reflect.DeepEqual(leftCopy, rightCopy) +} diff --git a/internal/storage/uow/issue_operations_contract_test.go b/internal/storage/uow/issue_operations_contract_test.go new file mode 100644 index 000000000..e14ef44af --- /dev/null +++ b/internal/storage/uow/issue_operations_contract_test.go @@ -0,0 +1,107 @@ +package uow + +import ( + "context" + "fmt" + "strconv" + "testing" + + "github.com/steveyegge/beads/internal/storage/conformance" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func TestIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsCreateRoutesInfraTypesToWisps(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsCreateRejectsMissingDependencyTargets(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func newUOWIssueOperationsFixture(t *testing.T, ctx context.Context) conformance.IssueOperationsStagingFixture { + t.Helper() + operations, provider := newRealIssueOperationsWithProvider(t, ctx) + return conformance.IssueOperationsStagingFixture{ + IssuePrefix: "bd", + Operations: operations, + CreateIssue: func(ctx context.Context, issue *types.Issue, actor string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{ + Issue: issue, + ExplicitID: issue.ID, + Labels: append([]string(nil), issue.Labels...), + CreateOnly: true, + }, actor) + return "seed issue", err + }) + }, + SetConfig: func(ctx context.Context, key, value string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "set " + key, uw.ConfigUseCase().SetConfig(ctx, key, value) + }) + }, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + row, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) ([]any, error) { + result, err := uw.RawSQLUseCase().Query(ctx, query, args...) + if err != nil { + return nil, err + } + if len(result.Rows) != 1 { + return nil, fmt.Errorf("query %q returned %d rows, want 1", query, len(result.Rows)) + } + return result.Rows[0], nil + }) + if err != nil { + return err + } + if len(row) != len(dest) { + return fmt.Errorf("query %q returned %d columns, want %d", query, len(row), len(dest)) + } + for i, target := range dest { + if err := scanRawSQLValue(target, row[i]); err != nil { + return fmt.Errorf("query %q column %d: %w", query, i, err) + } + } + return nil + }, + } +} + +// scanRawSQLValue copies one raw SQL column into a destination pointer, +// covering the destination types the issue-operations contract scans into. +func scanRawSQLValue(dest, value any) error { + switch target := dest.(type) { + case *int: + parsed, err := strconv.Atoi(rawSQLString(value)) + if err != nil { + return fmt.Errorf("scan %v into *int: %w", value, err) + } + *target = parsed + case *string: + *target = rawSQLString(value) + default: + return fmt.Errorf("unsupported scan destination %T", dest) + } + return nil +} + +func rawSQLString(value any) string { + switch typed := value.(type) { + case nil: + return "" + case []byte: + return string(typed) + case string: + return typed + default: + return fmt.Sprint(typed) + } +} diff --git a/internal/storage/uow/issue_operations_test.go b/internal/storage/uow/issue_operations_test.go new file mode 100644 index 000000000..6d6638c6f --- /dev/null +++ b/internal/storage/uow/issue_operations_test.go @@ -0,0 +1,878 @@ +package uow + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/dberrors" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +func TestIssueOperationsRejectsInvalidRequestsBeforeOpeningUOW(t *testing.T) { + provider := &mockUnitOfWorkProvider{newUOWErr: errors.New("unexpected unit-of-work open")} + operations, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + negativeEstimate := -1 + checks := []struct { + name string + call func() error + }{ + {"create missing actor", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{Issue: &issueops.Issue{}}) + return err + }}, + {"create nil issue", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{Actor: "a"}) + return err + }}, + {"create embedded relations", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{Actor: "a", Issue: &issueops.Issue{Comments: []*types.Comment{{Text: "no"}}}}) + return err + }}, + {"create duplicate dependency", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{Actor: "a", Issue: &issueops.Issue{Title: "x"}, ParentID: "bd-parent", Dependencies: []issueops.CreateDependency{{TargetID: "bd-parent", Type: types.DepParentChild}}}) + return err + }}, + {"create overlong label", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{Actor: "a", Issue: &issueops.Issue{Title: "x", Labels: []string{strings.Repeat("x", types.MaxFieldLen+1)}}}) + return err + }}, + {"create malformed dependency metadata", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "a", + Issue: &issueops.Issue{Title: "x"}, + Dependencies: []issueops.CreateDependency{{TargetID: "bd-target", Type: types.DepRelated, Metadata: "{"}}, + }) + return err + }}, + {"create overlong dependency thread", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "a", + Issue: &issueops.Issue{Title: "x"}, + Dependencies: []issueops.CreateDependency{{TargetID: "bd-target", Type: types.DepRelated, ThreadID: strings.Repeat("t", types.MaxFieldLen+1)}}, + }) + return err + }}, + {"create overlong parent ID", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "a", + Issue: &issueops.Issue{Title: "x"}, + ParentID: strings.Repeat("p", types.MaxFieldLen+1), + }) + return err + }}, + {"create overlong dependency target ID", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "a", + Issue: &issueops.Issue{Title: "x"}, + Dependencies: []issueops.CreateDependency{{TargetID: strings.Repeat("d", types.MaxFieldLen+1), Type: types.DepRelated}}, + }) + return err + }}, + {"create overlong waits-for spawner ID", func() error { + _, err := operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "a", + Issue: &issueops.Issue{Title: "x"}, + WaitsFor: &issueops.WaitsFor{SpawnerID: strings.Repeat("w", types.MaxFieldLen+1)}, + }) + return err + }}, + {"update missing ID", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{Actor: "a"}) + return err + }}, + {"update empty title", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{ + Actor: "a", IssueID: "bd-1", + Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true}}, + }) + return err + }}, + {"update overlong title", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{ + Actor: "a", IssueID: "bd-1", + Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: strings.Repeat("x", 501)}}, + }) + return err + }}, + {"update negative priority", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{ + Actor: "a", IssueID: "bd-1", + Patch: issueops.IssuePatch{Priority: issueops.Field[int]{Set: true, Value: -1}}, + }) + return err + }}, + {"update priority above maximum", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{ + Actor: "a", IssueID: "bd-1", + Patch: issueops.IssuePatch{Priority: issueops.Field[int]{Set: true, Value: 5}}, + }) + return err + }}, + {"update negative estimated minutes", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{ + Actor: "a", IssueID: "bd-1", + Patch: issueops.IssuePatch{EstimatedMinutes: issueops.Field[*int]{Set: true, Value: &negativeEstimate}}, + }) + return err + }}, + {"close missing ID", func() error { + _, err := operations.Close(context.Background(), issueops.CloseRequest{Actor: "a"}) + return err + }}, + {"reopen missing actor", func() error { + _, err := operations.Reopen(context.Background(), issueops.ReopenRequest{IssueID: "bd-1"}) + return err + }}, + {"invalid claim guards", func() error { + expected := issueops.StatusOpen + _, err := operations.Update(context.Background(), issueops.UpdateRequest{Actor: "a", IssueID: "bd-1", Claim: true, ExpectedStatus: &expected}) + return err + }}, + {"invalid force", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{Actor: "a", IssueID: "bd-1", ForceAssigneeTransfer: true}) + return err + }}, + {"invalid persistence", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{Actor: "a", IssueID: "bd-1", Patch: issueops.IssuePatch{Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: "bad"}}}) + return err + }}, + {"metadata replacement combined", func() error { + _, err := operations.Update(context.Background(), issueops.UpdateRequest{Actor: "a", IssueID: "bd-1", Patch: issueops.IssuePatch{Metadata: issueops.MetadataPatch{Replace: issueops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{}`)}, Unset: []string{"x"}}}}) + return err + }}, + } + for _, check := range checks { + t.Run(check.name, func(t *testing.T) { + if err := check.call(); !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("error = %v, want ErrValidation", err) + } + }) + } + if provider.newUOWCalls != 0 { + t.Fatalf("NewUOW calls = %d, want 0", provider.newUOWCalls) + } +} + +func TestNewIssueOperationsReturnsPublicOperations(t *testing.T) { + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + if operations == nil { + t.Fatal("NewIssueOperations() returned nil") + } +} + +func TestNewIssueOperationsRejectsTypedNilProvider(t *testing.T) { + var provider *mockUnitOfWorkProvider + operations, err := NewIssueOperations(provider) + if err == nil { + t.Fatal("NewIssueOperations() error = nil, want typed-nil provider error") + } + if operations != nil { + t.Fatalf("NewIssueOperations() operations = %T, want nil", operations) + } +} + +func TestIssueOperationsCreateRetriesUsingRunTxResult(t *testing.T) { + first := &mockUnitOfWork{ + commitErr: newMySQLError(1213), + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{}}, + labelUseCase: hydrationLabelUseCaseStub{}, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + issueUseCase: createIssueUseCaseStub{create: func(_ context.Context, params domain.CreateIssueParams, _ string) (domain.CreateIssueResult, error) { + params.Issue.Labels[0] = "mutated-first-attempt" + return domain.CreateIssueResult{Issue: &types.Issue{ID: "bd-first", Title: params.Issue.Title}}, nil + }}, + } + second := &mockUnitOfWork{ + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{}}, + labelUseCase: hydrationLabelUseCaseStub{}, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + issueUseCase: createIssueUseCaseStub{create: func(_ context.Context, params domain.CreateIssueParams, _ string) (domain.CreateIssueResult, error) { + if got := params.Issue.Labels; len(got) != 1 || got[0] != "caller-label" { + t.Fatalf("retry labels = %#v, want pristine caller snapshot", got) + } + return domain.CreateIssueResult{Issue: &types.Issue{ID: "bd-second", Title: params.Issue.Title}}, nil + }}, + } + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{first, second}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + result, err := operations.Create(context.Background(), issueops.CreateRequest{Actor: "tester", Issue: &issueops.Issue{Title: "retry create", IssueType: types.TypeTask, Labels: []string{"caller-label"}}}) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + if result.Issue == nil || result.Issue.ID != "bd-second" { + t.Fatalf("Create() result = %#v, want successful retry result", result) + } + if first.commitCount != 1 || second.commitCount != 1 { + t.Fatalf("commit counts = (%d, %d), want (1, 1)", first.commitCount, second.commitCount) + } +} + +func TestIssueOperationsCreateUsesConfiguredStatusesAndTypes(t *testing.T) { + var received domain.CreateIssueParams + uw := &mockUnitOfWork{ + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{IssuePrefix: "bd", CustomStatuses: []types.CustomStatus{{Name: "review"}}, CustomTypes: []string{"research"}}}, + labelUseCase: hydrationLabelUseCaseStub{}, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + issueUseCase: createIssueUseCaseStub{create: func(_ context.Context, params domain.CreateIssueParams, _ string) (domain.CreateIssueResult, error) { + received = params + return domain.CreateIssueResult{Issue: &types.Issue{ID: params.Issue.ID}}, nil + }}, + } + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + _, err = operations.Create(context.Background(), issueops.CreateRequest{Actor: "tester", Issue: &issueops.Issue{ID: "bd-custom", Title: "custom", Status: "review", IssueType: "research"}}) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + if received.Issue.Status != "review" || received.Issue.IssueType != "research" { + t.Fatalf("Create() parameters = %#v, want configured status and type", received.Issue) + } +} + +func TestIssueOperationsLifecycleWithRealUnitOfWork(t *testing.T) { + ctx := context.Background() + provider := newTestUOWProvider(t) + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if err := uw.ConfigUseCase().SetConfig(ctx, "issue_prefix", "bd"); err != nil { + return "", err + } + return "initialize lifecycle fixture", nil + }); err != nil { + t.Fatalf("initialize lifecycle fixture: %v", err) + } + operations, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + target, err := operations.Create(ctx, issueops.CreateRequest{Actor: "tester", Issue: &issueops.Issue{ID: "bd-life-target", Title: "target", IssueType: types.TypeTask, Priority: 2}}) + if err != nil { + t.Fatalf("Create(target) error = %v", err) + } + if target.Issue == nil { + t.Fatal("Create(target) returned nil issue") + } + importedIssue := &issueops.Issue{ + ID: "bd-life-main", + Title: "main", + IssueType: types.TypeTask, + Priority: 2, + Labels: []string{"imported-label"}, + } + importedDependency := issueops.CreateDependency{ + TargetID: target.Issue.ID, + Type: types.DepRelated, + Metadata: `{"origin":"import"}`, + ThreadID: "import-thread", + } + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: importedIssue, + Dependencies: []issueops.CreateDependency{importedDependency}, + }) + if err != nil { + t.Fatalf("Create(main) error = %v", err) + } + if len(created.Issue.Labels) != 1 || created.Issue.Labels[0] != "imported-label" { + t.Fatalf("Create(main) labels = %#v, want imported label", created.Issue.Labels) + } + if len(created.Issue.Dependencies) != 1 || + created.Issue.Dependencies[0].Metadata != `{"origin":"import"}` || + created.Issue.Dependencies[0].ThreadID != "import-thread" { + t.Fatalf("Create(main) hydration = %#v", created.Issue) + } + if importedIssue.Labels[0] != "imported-label" || + importedDependency.Metadata != `{"origin":"import"}` { + t.Fatalf("Create(main) mutated caller input: issue=%#v dependency=%#v", importedIssue, importedDependency) + } + + beforeGuard := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + wrongAssignee := "different-owner" + _, err = operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + ExpectedAssignee: &wrongAssignee, + Patch: issueops.IssuePatch{ + Title: issueops.Field[string]{Set: true, Value: "must not persist"}, + }, + }) + if !errors.Is(err, issueops.ErrAssigneeMismatch) { + t.Fatalf("Update(assignee guard) error = %v, want ErrAssigneeMismatch", err) + } + expectedAssignee := "" + wrongStatus := issueops.StatusClosed + _, err = operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + ExpectedAssignee: &expectedAssignee, + ExpectedStatus: &wrongStatus, + Patch: issueops.IssuePatch{ + Title: issueops.Field[string]{Set: true, Value: "must still not persist"}, + }, + }) + if !errors.Is(err, issueops.ErrStatusMismatch) { + t.Fatalf("Update(status guard) error = %v, want ErrStatusMismatch", err) + } + staleCreateVersion := created.Issue.RowVersion + 1 + _, err = operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Claim: true, + ExpectedVersion: &staleCreateVersion, + }) + if !errors.Is(err, issueops.ErrVersionMismatch) { + t.Fatalf("Update(stale claim) error = %v, want ErrVersionMismatch", err) + } + afterGuard := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + if afterGuard != beforeGuard { + t.Fatalf("stale claim changed durable state: before=%+v after=%+v", beforeGuard, afterGuard) + } + + updated, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Claim: true, + ExpectedVersion: &created.Issue.RowVersion, + Patch: issueops.IssuePatch{ + Title: issueops.Field[string]{Set: true, Value: "claimed and moved"}, + Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: issueops.PersistenceModeEphemeral}, + }, + }) + if err != nil { + t.Fatalf("Update() error = %v", err) + } + if !updated.Changed || + !updated.Issue.Ephemeral || + updated.Issue.Assignee != "tester" || + len(updated.Issue.Labels) != 1 || + len(updated.Issue.Dependencies) != 1 { + t.Fatalf("Update() = %#v", updated) + } + beforeForeignClaim := readIssueMutationSnapshot(t, ctx, provider, updated.Issue.ID, true) + if _, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "other", IssueID: updated.Issue.ID, Claim: true}); !errors.Is(err, issueops.ErrAlreadyClaimed) { + t.Fatalf("Update(foreign claim) error = %v, want ErrAlreadyClaimed", err) + } + afterForeignClaim := readIssueMutationSnapshot(t, ctx, provider, updated.Issue.ID, true) + if afterForeignClaim != beforeForeignClaim { + t.Fatalf("foreign claim changed wisp state: before=%+v after=%+v", beforeForeignClaim, afterForeignClaim) + } + samePersistence, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: updated.Issue.ID, + Patch: issueops.IssuePatch{ + Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: issueops.PersistenceModeEphemeral}, + }, + }) + if err != nil || samePersistence.Changed { + t.Fatalf("Update(same persistence) = %#v, %v; want unchanged", samePersistence, err) + } + promoted, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: updated.Issue.ID, + Patch: issueops.IssuePatch{ + Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: issueops.PersistenceModePersistent}, + }, + }) + if err != nil || !promoted.Changed || promoted.Issue.Ephemeral || promoted.Issue.NoHistory { + t.Fatalf("Update(promote persistence) = %#v, %v", promoted, err) + } + if stored := readStoredIssue(t, ctx, provider, promoted.Issue.ID); stored.ID != promoted.Issue.ID { + t.Fatalf("promoted durable issue = %#v", stored) + } + parent, err := operations.Create(ctx, issueops.CreateRequest{Actor: "tester", Issue: &issueops.Issue{ID: "bd-life-parent", Title: "parent", IssueType: types.TypeEpic, Priority: 2}}) + if err != nil { + t.Fatalf("Create(parent) error = %v", err) + } + child, err := operations.Create(ctx, issueops.CreateRequest{Actor: "tester", Issue: &issueops.Issue{ID: "bd-life-parent.1", Title: "child", IssueType: types.TypeTask, Priority: 2}, ParentID: parent.Issue.ID}) + if err != nil { + t.Fatalf("Create(child) error = %v", err) + } + _, err = operations.Close(ctx, issueops.CloseRequest{Actor: "tester", IssueID: parent.Issue.ID, ExpectedVersion: &parent.Issue.RowVersion}) + if !errors.Is(err, issueops.ErrCloseOpenChildren) { + t.Fatalf("Close(parent with open child) error = %v, want ErrCloseOpenChildren", err) + } + closedChild, err := operations.Close(ctx, issueops.CloseRequest{Actor: "tester", IssueID: child.Issue.ID, Session: "session-life-child", ExpectedVersion: &child.Issue.RowVersion}) + if err != nil { + t.Fatalf("Close(child) error = %v", err) + } + if closedChild.Issue.ClosedBySession != "session-life-child" { + t.Fatalf("Close(child) ClosedBySession = %q, want session-life-child", closedChild.Issue.ClosedBySession) + } + movedClosedChild, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: closedChild.Issue.ID, Patch: issueops.IssuePatch{Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: issueops.PersistenceModeEphemeral}}}) + if err != nil { + t.Fatalf("Update(closed child persistence) error = %v", err) + } + if movedClosedChild.Issue.ClosedBySession != "session-life-child" { + t.Fatalf("Update(closed child persistence) ClosedBySession = %q, want session-life-child", movedClosedChild.Issue.ClosedBySession) + } + closedParent, err := operations.Close(ctx, issueops.CloseRequest{Actor: "tester", IssueID: parent.Issue.ID, ExpectedVersion: &parent.Issue.RowVersion}) + if err != nil || !closedParent.Changed { + t.Fatalf("Close(parent) = %#v, %v", closedParent, err) + } + staleVersion := closedParent.Issue.RowVersion + 1 + _, err = operations.Reopen(ctx, issueops.ReopenRequest{Actor: "tester", IssueID: parent.Issue.ID, ExpectedVersion: &staleVersion}) + if !errors.Is(err, issueops.ErrVersionMismatch) { + t.Fatalf("Reopen(stale) error = %v, want ErrVersionMismatch", err) + } + reopened, err := operations.Reopen(ctx, issueops.ReopenRequest{Actor: "tester", IssueID: parent.Issue.ID, ExpectedVersion: &closedParent.Issue.RowVersion}) + if err != nil || !reopened.Changed { + t.Fatalf("Reopen() = %#v, %v", reopened, err) + } + noOp, err := operations.Reopen(ctx, issueops.ReopenRequest{Actor: "tester", IssueID: parent.Issue.ID, ExpectedVersion: &reopened.Issue.RowVersion}) + if err != nil || noOp.Changed { + t.Fatalf("Reopen(no-op) = %#v, %v", noOp, err) + } + _ = closedChild + rollbackIssue := &issueops.Issue{ + ID: "bd-life-rollback", + Title: "rollback", + IssueType: types.TypeTask, + Priority: 2, + Labels: []string{"rollback-label"}, + } + rollbackDependency := issueops.CreateDependency{ + TargetID: "bd-life-missing", + Type: types.DepRelated, + Metadata: `{"rollback":true}`, + ThreadID: "rollback-thread", + } + _, err = operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: rollbackIssue, + Dependencies: []issueops.CreateDependency{rollbackDependency}, + }) + if err == nil { + t.Fatal("Create(rollback) error = nil, want dependency failure") + } + if rollbackIssue.Labels[0] != "rollback-label" || + rollbackDependency.Metadata != `{"rollback":true}` || + rollbackDependency.ThreadID != "rollback-thread" { + t.Fatalf("Create(rollback) mutated caller input: issue=%#v dependency=%#v", rollbackIssue, rollbackDependency) + } + _, err = RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (struct{}, error) { + _, err := uw.IssueUseCase().GetIssue(ctx, "bd-life-rollback") + return struct{}{}, err + }) + if !dberrors.IsNoRows(err) { + t.Fatalf("rollback issue lookup error = %v, want no rows", err) + } + assertNoDurableIssueRows(t, ctx, provider, rollbackIssue.ID) +} + +func assertNoDurableIssueRows(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, id string) { + t.Helper() + _, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (struct{}, error) { + for _, query := range []string{ + "SELECT COUNT(*) FROM issues WHERE id = ?", + "SELECT COUNT(*) FROM labels WHERE issue_id = ?", + "SELECT COUNT(*) FROM comments WHERE issue_id = ?", + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ?", + "SELECT COUNT(*) FROM events WHERE issue_id = ?", + } { + result, err := uw.RawSQLUseCase().Query(ctx, query, id) + if err != nil { + return struct{}{}, err + } + if len(result.Rows) != 1 || len(result.Rows[0]) != 1 || fmt.Sprint(result.Rows[0][0]) != "0" { + return struct{}{}, fmt.Errorf("rollback residue for %q: query %q returned %#v", id, query, result.Rows) + } + } + return struct{}{}, nil + }) + if err != nil { + t.Fatalf("assert rollback cleanup for %s: %v", id, err) + } +} + +type createIssueUseCaseStub struct { + domain.IssueUseCase + create func(context.Context, domain.CreateIssueParams, string) (domain.CreateIssueResult, error) +} +type createConfigUseCaseStub struct { + domain.ConfigUseCase + context domain.CreateContext + err error +} + +func (s createConfigUseCaseStub) LoadCreateContext(context.Context) (domain.CreateContext, error) { + return s.context, s.err +} + +type operationIssueUseCaseStub struct { + domain.IssueUseCase + getIssue func(context.Context, string) (*types.Issue, error) + getWisp func(context.Context, string) (*types.Issue, error) +} + +type hydrationLabelUseCaseStub struct { + domain.LabelUseCase +} + +func (hydrationLabelUseCaseStub) GetLabels(context.Context, string) ([]string, error) { + return []string{"complete"}, nil +} + +func (hydrationLabelUseCaseStub) GetWispLabels(context.Context, string) ([]string, error) { + return []string{"complete"}, nil +} + +type hydrationDependencyUseCaseStub struct { + domain.DependencyUseCase +} + +func (hydrationDependencyUseCaseStub) GetIssueDependencyRecords(_ context.Context, ids []string) (map[string][]*types.Dependency, error) { + return map[string][]*types.Dependency{ids[0]: {}}, nil +} + +func (hydrationDependencyUseCaseStub) GetWispDependencyRecords(_ context.Context, ids []string) (map[string][]*types.Dependency, error) { + return map[string][]*types.Dependency{ids[0]: {}}, nil +} + +type hydrationCommentUseCaseStub struct { + domain.CommentUseCase +} + +func (hydrationCommentUseCaseStub) GetCommentsForIssue(context.Context, string) ([]*types.Comment, error) { + return []*types.Comment{}, nil +} + +func (hydrationCommentUseCaseStub) GetCommentsForWisp(context.Context, string) ([]*types.Comment, error) { + return []*types.Comment{}, nil +} + +func (s operationIssueUseCaseStub) GetIssue(ctx context.Context, id string) (*types.Issue, error) { + return s.getIssue(ctx, id) +} +func (s operationIssueUseCaseStub) GetWisp(ctx context.Context, id string) (*types.Issue, error) { + return s.getWisp(ctx, id) +} + +func TestIssueOperationsCreateRejectsIncompleteUnitOfWork(t *testing.T) { + issueUseCase := createIssueUseCaseStub{ + create: func(_ context.Context, params domain.CreateIssueParams, _ string) (domain.CreateIssueResult, error) { + return domain.CreateIssueResult{Issue: &types.Issue{ID: params.Issue.ID, Title: params.Issue.Title}}, nil + }, + } + + t.Run("labels", func(t *testing.T) { + uw := &mockUnitOfWork{ + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{IssuePrefix: "bd"}}, + issueUseCase: issueUseCase, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + } + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + _, err = operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ID: "bd-incomplete-labels", Title: "missing labels", IssueType: types.TypeTask}, + }) + if err == nil || !strings.Contains(err.Error(), "hydrate issue labels") { + t.Fatalf("Create() error = %v, want missing-label capability context", err) + } + if uw.commitCount != 0 { + t.Fatalf("Create() commits = %d, want 0", uw.commitCount) + } + }) + + t.Run("dependencies", func(t *testing.T) { + uw := &mockUnitOfWork{ + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{IssuePrefix: "bd"}}, + issueUseCase: issueUseCase, + labelUseCase: hydrationLabelUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + } + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + _, err = operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ID: "bd-incomplete-dependencies", Title: "missing dependencies", IssueType: types.TypeTask}, + }) + if err == nil || !strings.Contains(err.Error(), "hydrate issue dependencies") { + t.Fatalf("Create() error = %v, want missing-dependency capability context", err) + } + if uw.commitCount != 0 { + t.Fatalf("Create() commits = %d, want 0", uw.commitCount) + } + }) + + t.Run("create comments", func(t *testing.T) { + uw := &mockUnitOfWork{ + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{IssuePrefix: "bd"}}, + issueUseCase: issueUseCase, + labelUseCase: hydrationLabelUseCaseStub{}, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + } + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + _, err = operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ID: "bd-incomplete-comments", Title: "missing comments", IssueType: types.TypeTask}, + }) + if err == nil || !strings.Contains(err.Error(), "hydrate issue comments") { + t.Fatalf("Create() error = %v, want missing-comment capability context", err) + } + if uw.commitCount != 0 { + t.Fatalf("Create() commits = %d, want 0", uw.commitCount) + } + }) +} + +func TestOperationIssueFallsBackOnlyAfterNotFoundWispRead(t *testing.T) { + durableCalls := 0 + uw := &mockUnitOfWork{issueUseCase: operationIssueUseCaseStub{ + getWisp: func(context.Context, string) (*types.Issue, error) { + return nil, storage.ErrNotFound + }, + getIssue: func(context.Context, string) (*types.Issue, error) { + durableCalls++ + return &types.Issue{ID: "bd-durable"}, nil + }, + }} + + issue, isWisp, err := operationIssue(context.Background(), uw, "bd-durable") + if err != nil { + t.Fatalf("operationIssue() error = %v", err) + } + if isWisp || issue.ID != "bd-durable" || durableCalls != 1 { + t.Fatalf("operationIssue() = (%#v, %t), durable calls = %d", issue, isWisp, durableCalls) + } +} + +func TestOperationIssueFallsBackToDurableAfterNoRowsWispRead(t *testing.T) { + durableCalls := 0 + uw := &mockUnitOfWork{issueUseCase: operationIssueUseCaseStub{ + getWisp: func(context.Context, string) (*types.Issue, error) { + return nil, sql.ErrNoRows + }, + getIssue: func(context.Context, string) (*types.Issue, error) { + durableCalls++ + return &types.Issue{ID: "bd-durable"}, nil + }, + }} + + issue, isWisp, err := operationIssue(context.Background(), uw, "bd-durable") + if err != nil { + t.Fatalf("operationIssue() error = %v", err) + } + if isWisp || issue.ID != "bd-durable" || durableCalls != 1 { + t.Fatalf("operationIssue() = (%#v, %t), durable calls = %d", issue, isWisp, durableCalls) + } +} + +func TestOperationIssueBothMissingMatchesPublicNotFound(t *testing.T) { + uw := &mockUnitOfWork{issueUseCase: operationIssueUseCaseStub{ + getWisp: func(context.Context, string) (*types.Issue, error) { return nil, sql.ErrNoRows }, + getIssue: func(context.Context, string) (*types.Issue, error) { return nil, sql.ErrNoRows }, + }} + + _, _, err := operationIssue(context.Background(), uw, "bd-missing") + if !errors.Is(err, issueops.ErrNotFound) { + t.Fatalf("operationIssue() error = %v, want ErrNotFound", err) + } +} + +func TestOperationIssuePropagatesWispReadFailure(t *testing.T) { + wispReadErr := errors.New("wisp read unavailable") + durableCalls := 0 + uw := &mockUnitOfWork{issueUseCase: operationIssueUseCaseStub{ + getWisp: func(context.Context, string) (*types.Issue, error) { + return nil, wispReadErr + }, + getIssue: func(context.Context, string) (*types.Issue, error) { + durableCalls++ + return &types.Issue{ID: "bd-durable"}, nil + }, + }} + + _, _, err := operationIssue(context.Background(), uw, "bd-durable") + if !errors.Is(err, wispReadErr) { + t.Fatalf("operationIssue() error = %v, want wisp read error", err) + } + if durableCalls != 0 { + t.Fatalf("durable reads = %d, want 0", durableCalls) + } +} + +func TestUpdateSpecClassifiesMetadataValidationAndClearsReplacement(t *testing.T) { + clearing, err := updateSpec(issueops.UpdateRequest{Patch: issueops.IssuePatch{ + Metadata: issueops.MetadataPatch{Replace: issueops.Field[json.RawMessage]{Set: true}}, + }}) + if err != nil { + t.Fatalf("updateSpec() clear replacement error = %v", err) + } + if got := string(clearing.Fields["metadata"].(json.RawMessage)); got != "{}" { + t.Fatalf("clear metadata = %q, want {}", got) + } + + _, err = updateSpec(issueops.UpdateRequest{Patch: issueops.IssuePatch{ + Metadata: issueops.MetadataPatch{Merge: issueops.Field[json.RawMessage]{Set: true, Value: json.RawMessage("[]")}}, + }}) + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("merge array error = %v, want ErrValidation", err) + } +} + +func TestUpdateSpecLowersPersistenceMode(t *testing.T) { + spec, err := updateSpec(issueops.UpdateRequest{Patch: issueops.IssuePatch{ + Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: issueops.PersistenceModeEphemeral}, + }}) + if err != nil { + t.Fatalf("updateSpec() error = %v", err) + } + if spec.Persistence == nil || *spec.Persistence != types.PersistenceModeEphemeral { + t.Fatalf("updateSpec().Persistence = %v, want ephemeral", spec.Persistence) + } +} +func (s createIssueUseCaseStub) CreateIssue(ctx context.Context, params domain.CreateIssueParams, actor string) (domain.CreateIssueResult, error) { + return s.create(ctx, params, actor) +} +func (createIssueUseCaseStub) GetWisp(context.Context, string) (*types.Issue, error) { + return nil, storage.ErrNotFound +} +func (createIssueUseCaseStub) GetIssue(_ context.Context, id string) (*types.Issue, error) { + return &types.Issue{ID: id}, nil +} + +type lifecycleIssueUseCaseStub struct { + domain.IssueUseCase + applyUpdate func(context.Context, string, domain.UpdateSpec, string) (*types.Issue, error) + getIssue func(context.Context, string) (*types.Issue, error) + getWisp func(context.Context, string) (*types.Issue, error) +} + +func (s lifecycleIssueUseCaseStub) ApplyUpdate(ctx context.Context, id string, spec domain.UpdateSpec, actor string) (*types.Issue, error) { + return s.applyUpdate(ctx, id, spec, actor) +} + +func (s lifecycleIssueUseCaseStub) GetIssue(ctx context.Context, id string) (*types.Issue, error) { + return s.getIssue(ctx, id) +} + +func (s lifecycleIssueUseCaseStub) GetWisp(ctx context.Context, id string) (*types.Issue, error) { + return s.getWisp(ctx, id) +} + +func TestIssueOperationsCloseMissingIssueReturnsPublicNotFoundBeforeVersionCheck(t *testing.T) { + calledApply := false + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{{ + issueUseCase: lifecycleIssueUseCaseStub{ + applyUpdate: func(context.Context, string, domain.UpdateSpec, string) (*types.Issue, error) { + calledApply = true + return nil, errors.New("version check ran before lookup") + }, + getWisp: func(context.Context, string) (*types.Issue, error) { return nil, storage.ErrNotFound }, + getIssue: func(context.Context, string) (*types.Issue, error) { return nil, storage.ErrNotFound }, + }, + }}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + + _, err = operations.Close(context.Background(), issueops.CloseRequest{Actor: "actor", IssueID: "bd-missing"}) + if !errors.Is(err, issueops.ErrNotFound) { + t.Fatalf("Close() error = %v, want ErrNotFound", err) + } + if calledApply { + t.Fatal("Close() checked version before resolving the issue") + } +} + +func TestIssueOperationsReopenMissingIssueReturnsPublicNotFoundBeforeVersionCheck(t *testing.T) { + calledApply := false + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{{ + issueUseCase: lifecycleIssueUseCaseStub{ + applyUpdate: func(context.Context, string, domain.UpdateSpec, string) (*types.Issue, error) { + calledApply = true + return nil, errors.New("version check ran before lookup") + }, + getWisp: func(context.Context, string) (*types.Issue, error) { return nil, storage.ErrNotFound }, + getIssue: func(context.Context, string) (*types.Issue, error) { return nil, storage.ErrNotFound }, + }, + }}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + + _, err = operations.Reopen(context.Background(), issueops.ReopenRequest{Actor: "actor", IssueID: "bd-missing"}) + if !errors.Is(err, issueops.ErrNotFound) { + t.Fatalf("Reopen() error = %v, want ErrNotFound", err) + } + if calledApply { + t.Fatal("Reopen() checked version before resolving the issue") + } +} + +func TestIssueOperationsCreateRetriesOnSerializationSQLStates(t *testing.T) { + for _, state := range []string{"40001", "40P01"} { + t.Run(state, func(t *testing.T) { + first := &mockUnitOfWork{ + commitErr: sqlStateError(state), + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{}}, + labelUseCase: hydrationLabelUseCaseStub{}, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + issueUseCase: createIssueUseCaseStub{create: func(_ context.Context, params domain.CreateIssueParams, _ string) (domain.CreateIssueResult, error) { + params.Issue.Labels[0] = "changed-by-rejected-attempt" + return domain.CreateIssueResult{Issue: &types.Issue{ID: "bd-first", Title: params.Issue.Title}}, nil + }}, + } + second := &mockUnitOfWork{ + configUseCase: createConfigUseCaseStub{context: domain.CreateContext{}}, + labelUseCase: hydrationLabelUseCaseStub{}, + dependencyUseCase: hydrationDependencyUseCaseStub{}, + commentUseCase: hydrationCommentUseCaseStub{}, + issueUseCase: createIssueUseCaseStub{create: func(_ context.Context, params domain.CreateIssueParams, _ string) (domain.CreateIssueResult, error) { + if got := params.Issue.Labels; len(got) != 1 || got[0] != "caller-label" { + t.Fatalf("retry labels = %#v, want pristine caller snapshot", got) + } + return domain.CreateIssueResult{Issue: &types.Issue{ID: "bd-second", Title: params.Issue.Title}}, nil + }}, + } + operations, err := NewIssueOperations(&mockUnitOfWorkProvider{uows: []*mockUnitOfWork{first, second}}) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + + result, err := operations.Create(context.Background(), issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{Title: "retry create", IssueType: types.TypeTask, Labels: []string{"caller-label"}}, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + if result.Issue == nil || result.Issue.ID != "bd-second" { + t.Fatalf("Create() result = %#v, want second-attempt result", result) + } + if first.commitCount != 1 || second.commitCount != 1 { + t.Fatalf("commit counts = (%d, %d), want (1, 1)", first.commitCount, second.commitCount) + } + }) + } +} diff --git a/internal/storage/uow/issue_operations_update_real_uow_test.go b/internal/storage/uow/issue_operations_update_real_uow_test.go new file mode 100644 index 000000000..c450a4a13 --- /dev/null +++ b/internal/storage/uow/issue_operations_update_real_uow_test.go @@ -0,0 +1,481 @@ +package uow + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage/dberrors" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +func TestIssueOperationsOwnerPatchPersists(t *testing.T) { + ctx := context.Background() + operations := newRealIssueOperations(t, ctx) + + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-owner-patch", + Title: "owner patch", + IssueType: types.TypeTask, + Priority: 2, + }, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + + updated, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Patch: issueops.IssuePatch{ + Owner: issueops.Field[string]{Set: true, Value: "updated-owner"}, + }, + }) + if err != nil { + t.Fatalf("Update(owner) error = %v", err) + } + if !updated.Changed { + t.Fatal("Update(owner).Changed = false, want true") + } + if updated.Issue == nil || updated.Issue.Owner != "updated-owner" { + t.Fatalf("Update(owner).Issue = %#v, want updated-owner", updated.Issue) + } +} + +func TestIssueOperationsRejectsInvalidCanonicalUpdatesWithoutMutation(t *testing.T) { + ctx := context.Background() + operations, provider := newRealIssueOperationsWithProvider(t, ctx) + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-invalid-update", + Title: "valid incumbent", + IssueType: types.TypeTask, + Priority: 2, + }, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + negativeEstimate := -1 + checks := []struct { + name string + patch issueops.IssuePatch + }{ + {"empty title", issueops.IssuePatch{Title: issueops.Field[string]{Set: true}}}, + {"overlong title", issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: strings.Repeat("x", 501)}}}, + {"negative priority", issueops.IssuePatch{Priority: issueops.Field[int]{Set: true, Value: -1}}}, + {"priority above maximum", issueops.IssuePatch{Priority: issueops.Field[int]{Set: true, Value: 5}}}, + {"negative estimated minutes", issueops.IssuePatch{EstimatedMinutes: issueops.Field[*int]{Set: true, Value: &negativeEstimate}}}, + } + + before := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + for _, check := range checks { + t.Run(check.name, func(t *testing.T) { + _, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Patch: check.patch, + }) + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("Update() error = %v, want ErrValidation", err) + } + after := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + if after != before { + t.Fatalf("invalid update changed durable state: before=%+v after=%+v", before, after) + } + stored := readStoredIssue(t, ctx, provider, created.Issue.ID) + if stored.Title != "valid incumbent" || stored.Priority != 2 || stored.EstimatedMinutes != nil { + t.Fatalf("invalid update persisted candidate state: %#v", stored) + } + }) + } +} + +func TestIssueOperationsCreateRejectsCrossTierIDCollisions(t *testing.T) { + ctx := context.Background() + operations, provider := newRealIssueOperationsWithProvider(t, ctx) + + durable, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-cross-tier-durable", + Title: "durable incumbent", + IssueType: types.TypeTask, + Priority: 2, + }, + }) + if err != nil { + t.Fatalf("Create(durable incumbent) error = %v", err) + } + durableBefore := readIssueMutationSnapshot(t, ctx, provider, durable.Issue.ID, false) + + _, err = operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: durable.Issue.ID, + Title: "wisp replacement", + IssueType: types.TypeTask, + Priority: 2, + Ephemeral: true, + }, + }) + if !errors.Is(err, issueops.ErrAlreadyExists) { + t.Fatalf("Create(wisp collision) error = %v, want ErrAlreadyExists", err) + } + durableAfter := readIssueMutationSnapshot(t, ctx, provider, durable.Issue.ID, false) + if durableAfter != durableBefore { + t.Fatalf("wisp collision changed durable incumbent: before=%+v after=%+v", durableBefore, durableAfter) + } + storedDurable := readStoredIssue(t, ctx, provider, durable.Issue.ID) + if storedDurable.Title != "durable incumbent" { + t.Fatalf("durable incumbent title = %q, want unchanged", storedDurable.Title) + } + assertStoredIssueMissing(t, ctx, provider, durable.Issue.ID, true) + + wisp, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-cross-tier-wisp", + Title: "wisp incumbent", + IssueType: types.TypeTask, + Priority: 2, + Ephemeral: true, + }, + }) + if err != nil { + t.Fatalf("Create(wisp incumbent) error = %v", err) + } + wispBefore := readIssueMutationSnapshot(t, ctx, provider, wisp.Issue.ID, true) + + _, err = operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: wisp.Issue.ID, + Title: "durable replacement", + IssueType: types.TypeTask, + Priority: 2, + }, + }) + if !errors.Is(err, issueops.ErrAlreadyExists) { + t.Fatalf("Create(durable collision) error = %v, want ErrAlreadyExists", err) + } + wispAfter := readIssueMutationSnapshot(t, ctx, provider, wisp.Issue.ID, true) + if wispAfter != wispBefore { + t.Fatalf("durable collision changed wisp incumbent: before=%+v after=%+v", wispBefore, wispAfter) + } + storedWisp := readStoredWisp(t, ctx, provider, wisp.Issue.ID) + if storedWisp.Title != "wisp incumbent" { + t.Fatalf("wisp incumbent title = %q, want unchanged", storedWisp.Title) + } + assertStoredIssueMissing(t, ctx, provider, wisp.Issue.ID, false) +} + +func TestIssueOperationsTypedIssueTypeUsesConfiguredTypes(t *testing.T) { + ctx := context.Background() + operations, provider := newRealIssueOperationsWithProvider(t, ctx) + + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-typed-update", + Title: "type patch", + IssueType: types.TypeTask, + Priority: 2, + }, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + beforeInvalidType := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + + _, err = operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Patch: issueops.IssuePatch{ + IssueType: issueops.Field[issueops.IssueType]{Set: true, Value: issueops.IssueType("not-configured")}, + }, + }) + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("Update(invalid typed issue type) error = %v, want ErrValidation", err) + } + stored := readStoredIssue(t, ctx, provider, created.Issue.ID) + if stored.IssueType != types.TypeTask || stored.RowVersion != created.Issue.RowVersion { + t.Fatalf("invalid IssueType persisted: %#v", stored) + } + afterInvalidType := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + if afterInvalidType != beforeInvalidType { + t.Fatalf("invalid IssueType changed persisted state: before=%+v after=%+v", beforeInvalidType, afterInvalidType) + } + + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if err := uw.ConfigUseCase().SetConfig(ctx, "types.custom", "research"); err != nil { + return "", err + } + return "configure custom type", nil + }); err != nil { + t.Fatalf("configure custom type: %v", err) + } + updated, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Patch: issueops.IssuePatch{ + IssueType: issueops.Field[issueops.IssueType]{Set: true, Value: issueops.IssueType("research")}, + }, + }) + if err != nil { + t.Fatalf("Update(custom typed issue type) error = %v", err) + } + if updated.Issue == nil || updated.Issue.IssueType != issueops.IssueType("research") { + t.Fatalf("Update(custom typed issue type).Issue = %#v, want research", updated.Issue) + } +} + +func TestIssueOperationsSamePublicFieldsLeaveRowAndEventsUntouched(t *testing.T) { + ctx := context.Background() + operations, provider := newRealIssueOperationsWithProvider(t, ctx) + minutes := 45 + externalRef := "external-noop" + dueAt := time.Date(2031, time.March, 2, 3, 4, 5, 0, time.UTC) + deferUntil := time.Date(2031, time.March, 1, 3, 4, 5, 0, time.UTC) + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-unchanged-update", + Title: "unchanged title", + Description: "unchanged description", + Design: "unchanged design", + AcceptanceCriteria: "unchanged acceptance", + Notes: "unchanged notes", + SpecID: "spec-noop", + AwaitID: "await-noop", + Status: issueops.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Owner: "unchanged-owner", + ClosedBySession: "session-noop", + EstimatedMinutes: &minutes, + ExternalRef: &externalRef, + DueAt: &dueAt, + DeferUntil: &deferUntil, + }, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + before := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + + updated, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Patch: issueops.IssuePatch{ + Title: issueops.Field[string]{Set: true, Value: "unchanged title"}, + Description: issueops.Field[string]{Set: true, Value: "unchanged description"}, + Design: issueops.Field[string]{Set: true, Value: "unchanged design"}, + AcceptanceCriteria: issueops.Field[string]{Set: true, Value: "unchanged acceptance"}, + Notes: issueops.Field[string]{Set: true, Value: "unchanged notes"}, + SpecID: issueops.Field[string]{Set: true, Value: "spec-noop"}, + AwaitID: issueops.Field[string]{Set: true, Value: "await-noop"}, + Status: issueops.Field[issueops.Status]{Set: true, Value: issueops.StatusOpen}, + Priority: issueops.Field[int]{Set: true, Value: 2}, + IssueType: issueops.Field[issueops.IssueType]{Set: true, Value: types.TypeTask}, + Assignee: issueops.Field[string]{Set: true, Value: ""}, + Owner: issueops.Field[string]{Set: true, Value: "unchanged-owner"}, + ClosedBySession: issueops.Field[string]{Set: true, Value: "session-noop"}, + EstimatedMinutes: issueops.Field[*int]{Set: true, Value: &minutes}, + ExternalRef: issueops.Field[*string]{Set: true, Value: &externalRef}, + DueAt: issueops.Field[*time.Time]{Set: true, Value: &dueAt}, + DeferUntil: issueops.Field[*time.Time]{Set: true, Value: &deferUntil}, + }, + }) + if err != nil { + t.Fatalf("Update(same public fields) error = %v", err) + } + if updated.Changed { + t.Fatalf("Update(same public fields).Changed = true, want false: %#v", updated.Issue) + } + after := readIssueMutationSnapshot(t, ctx, provider, created.Issue.ID, false) + if after != before { + t.Fatalf("same public fields changed durable state: before=%+v after=%+v", before, after) + } +} + +func TestIssueOperationsClaimMutationCountsWhenPatchRestoresPriorState(t *testing.T) { + ctx := context.Background() + operations := newRealIssueOperations(t, ctx) + startedAt := time.Date(2030, time.January, 2, 3, 4, 5, 0, time.UTC) + created, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "tester", + Issue: &issueops.Issue{ + ID: "bd-claim-restore", + Title: "claim then restore", + IssueType: types.TypeTask, + Priority: 2, + StartedAt: &startedAt, + }, + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + beforeRestore, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Patch: issueops.IssuePatch{ + Title: issueops.Field[string]{Set: true, Value: "claim then restore"}, + }, + }) + if err != nil { + t.Fatalf("Update(same title before claim) error = %v", err) + } + if beforeRestore.Changed { + t.Fatalf("Update(same title before claim).Changed = true, want false: %#v", beforeRestore.Issue) + } + + restored, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", + IssueID: created.Issue.ID, + Claim: true, + Patch: issueops.IssuePatch{ + Status: issueops.Field[issueops.Status]{Set: true, Value: issueops.StatusOpen}, + Assignee: issueops.Field[string]{Set: true, Value: ""}, + }, + }) + if err != nil { + t.Fatalf("Update(claim then restore) error = %v", err) + } + if !restored.Changed { + t.Fatal("Update(claim then restore).Changed = false, want true") + } + if restored.Issue == nil || restored.Issue.Status != issueops.StatusOpen || restored.Issue.Assignee != "" { + t.Fatalf("Update(claim then restore).Issue = %#v, want open and unassigned", restored.Issue) + } + if !semanticIssueEqual(beforeRestore.Issue, restored.Issue) { + t.Fatalf("claim then restore did not restore the public state: before=%#v after=%#v", beforeRestore.Issue, restored.Issue) + } + + claimed, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: created.Issue.ID, Claim: true}) + if err != nil { + t.Fatalf("Update(claim) error = %v", err) + } + if !claimed.Changed { + t.Fatal("Update(claim).Changed = false, want true") + } + alreadyClaimed, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: created.Issue.ID, Claim: true}) + if err != nil { + t.Fatalf("Update(already claimed) error = %v", err) + } + if alreadyClaimed.Changed { + t.Fatalf("Update(already claimed).Changed = true, want false: %#v", alreadyClaimed.Issue) + } +} + +type issueMutationSnapshot struct { + rowLock string + updatedAt string + events int +} + +func readIssueMutationSnapshot(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, id string, useWisp bool) issueMutationSnapshot { + t.Helper() + snapshot, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (issueMutationSnapshot, error) { + issueTable := "issues" + eventTable := "events" + if useWisp { + issueTable = "wisps" + eventTable = "wisp_events" + } + row, err := uw.RawSQLUseCase().Query(ctx, "SELECT CAST(row_lock AS CHAR), CAST(updated_at AS CHAR) FROM "+issueTable+" WHERE id = ?", id) + if err != nil { + return issueMutationSnapshot{}, err + } + if len(row.Rows) != 1 || len(row.Rows[0]) != 2 { + return issueMutationSnapshot{}, fmt.Errorf("unexpected issue snapshot rows: %#v", row.Rows) + } + events, err := uw.RawSQLUseCase().Query(ctx, "SELECT COUNT(*) FROM "+eventTable+" WHERE issue_id = ?", id) + if err != nil { + return issueMutationSnapshot{}, err + } + if len(events.Rows) != 1 || len(events.Rows[0]) != 1 { + return issueMutationSnapshot{}, fmt.Errorf("unexpected event count rows: %#v", events.Rows) + } + count, err := strconv.Atoi(fmt.Sprint(events.Rows[0][0])) + if err != nil { + return issueMutationSnapshot{}, fmt.Errorf("parse event count %v: %w", events.Rows[0][0], err) + } + return issueMutationSnapshot{ + rowLock: fmt.Sprint(row.Rows[0][0]), + updatedAt: fmt.Sprint(row.Rows[0][1]), + events: count, + }, nil + }) + if err != nil { + t.Fatalf("read mutation snapshot for %s: %v", id, err) + } + return snapshot +} + +func newRealIssueOperations(t *testing.T, ctx context.Context) issueops.Lifecycle { + t.Helper() + operations, _ := newRealIssueOperationsWithProvider(t, ctx) + return operations +} + +func newRealIssueOperationsWithProvider(t *testing.T, ctx context.Context) (issueops.Lifecycle, UnitOfWorkProvider) { + t.Helper() + provider := newTestUOWProvider(t) + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if err := uw.ConfigUseCase().SetConfig(ctx, "issue_prefix", "bd"); err != nil { + return "", err + } + return "initialize issue operations", nil + }); err != nil { + t.Fatalf("initialize issue operations: %v", err) + } + operations, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + return operations, provider +} + +func readStoredIssue(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, id string) *types.Issue { + t.Helper() + issue, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (*types.Issue, error) { + return uw.IssueUseCase().GetIssue(ctx, id) + }) + if err != nil { + t.Fatalf("read issue %s: %v", id, err) + } + return issue +} + +func readStoredWisp(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, id string) *types.Issue { + t.Helper() + issue, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (*types.Issue, error) { + return uw.IssueUseCase().GetWisp(ctx, id) + }) + if err != nil { + t.Fatalf("read wisp %s: %v", id, err) + } + return issue +} + +func assertStoredIssueMissing(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, id string, useWisp bool) { + t.Helper() + _, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (*types.Issue, error) { + if useWisp { + return uw.IssueUseCase().GetWisp(ctx, id) + } + return uw.IssueUseCase().GetIssue(ctx, id) + }) + if !dberrors.IsNoRows(err) { + t.Fatalf("read missing issue %s (wisp=%t) error = %v, want no rows", id, useWisp, err) + } +} diff --git a/internal/storage/uow/metadata_patch_dolt_test.go b/internal/storage/uow/metadata_patch_dolt_test.go new file mode 100644 index 000000000..ce9cc6f53 --- /dev/null +++ b/internal/storage/uow/metadata_patch_dolt_test.go @@ -0,0 +1,163 @@ +package uow + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +func TestIssueOperationsTypedMetadataPatchUpdateWithRealDolt(t *testing.T) { + ctx := context.Background() + operations := newMetadataPatchOperations(t, ctx) + + patch := func() issueops.MetadataPatch { + return issueops.MetadataPatch{ + Merge: issueops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"merged":{"source":"merge"},"overlap":"merged"}`)}, + Set: map[string]json.RawMessage{ + "nested": json.RawMessage(`{"enabled":true}`), + "number": json.RawMessage(`7`), + "bool": json.RawMessage(`true`), + "overlap": json.RawMessage(`"set"`), + }, + Unset: []string{"overlap", "remove"}, + } + } + + updatedID := createMetadataPatchIssue(t, ctx, operations, "bd-metadata-update") + updated, err := operations.Update(ctx, issueops.UpdateRequest{ + Actor: "tester", IssueID: updatedID, Patch: issueops.IssuePatch{Metadata: patch()}, + }) + if err != nil { + t.Fatalf("Update() error = %v", err) + } + if !updated.Changed { + t.Fatal("Update() Changed = false, want true") + } + assertTypedMetadata(t, updated.Issue.Metadata) +} + +func TestIssueOperationsMetadataPatchRejectsInvalidInputWithRealDolt(t *testing.T) { + ctx := context.Background() + operations := newMetadataPatchOperations(t, ctx) + + cases := []struct { + name string + call func(string) error + }{ + { + name: "update rejects invalid typed set JSON", + call: func(id string) error { + _, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: id, Patch: issueops.IssuePatch{ + Metadata: issueops.MetadataPatch{Set: map[string]json.RawMessage{"bad": json.RawMessage(`{`)}}, + }}) + return err + }, + }, + { + name: "update rejects invalid typed set key", + call: func(id string) error { + _, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: id, Patch: issueops.IssuePatch{ + Metadata: issueops.MetadataPatch{Set: map[string]json.RawMessage{"bad key": json.RawMessage(`true`)}}, + }}) + return err + }, + }, + { + name: "update rejects non-object merge", + call: func(id string) error { + _, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: id, Patch: issueops.IssuePatch{ + Metadata: issueops.MetadataPatch{Merge: issueops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`[1]`)}}, + }}) + return err + }, + }, + } + for i, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + id := createMetadataPatchIssue(t, ctx, operations, fmt.Sprintf("bd-metadata-invalid-%d", i)) + err := tc.call(id) + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("operation error = %v, want ErrValidation", err) + } + issue := readMetadataPatchIssue(t, ctx, operations, id) + if issue.Status != issueops.StatusOpen { + t.Fatalf("invalid operation changed status = %q, want open", issue.Status) + } + var metadata map[string]any + if err := json.Unmarshal(issue.Metadata, &metadata); err != nil { + t.Fatalf("unmarshal unchanged metadata: %v", err) + } + if len(metadata) != 4 || metadata["stable"] != true || metadata["keep"] != "yes" || metadata["remove"] != "gone" || metadata["overlap"] != "old" { + t.Fatalf("invalid operation changed metadata = %#v", metadata) + } + }) + } +} + +func newMetadataPatchOperations(t *testing.T, ctx context.Context) issueops.Lifecycle { + t.Helper() + provider := newTestUOWProvider(t) + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if err := uw.ConfigUseCase().SetConfig(ctx, "issue_prefix", "bd"); err != nil { + return "", err + } + return "initialize metadata patch fixture", nil + }); err != nil { + t.Fatalf("initialize metadata patch fixture: %v", err) + } + operations, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations() error = %v", err) + } + return operations +} + +func createMetadataPatchIssue(t *testing.T, ctx context.Context, operations issueops.Lifecycle, id string) string { + t.Helper() + created, err := operations.Create(ctx, issueops.CreateRequest{Actor: "tester", Issue: &issueops.Issue{ + ID: id, Title: id, IssueType: types.TypeTask, Priority: 2, Metadata: json.RawMessage(`{"keep":"yes","remove":"gone","overlap":"old","stable":true}`), + }}) + if err != nil { + t.Fatalf("Create(%q) error = %v", id, err) + } + return created.Issue.ID +} + +func readMetadataPatchIssue(t *testing.T, ctx context.Context, operations issueops.Lifecycle, id string) *issueops.Issue { + t.Helper() + issue, err := operations.Update(ctx, issueops.UpdateRequest{Actor: "tester", IssueID: id}) + if err != nil { + t.Fatalf("read issue %q: %v", id, err) + } + return issue.Issue +} + +func assertTypedMetadata(t *testing.T, raw json.RawMessage) { + t.Helper() + var metadata map[string]any + if err := json.Unmarshal(raw, &metadata); err != nil { + t.Fatalf("unmarshal metadata: %v", err) + } + if metadata["keep"] != "yes" || metadata["number"] != float64(7) || metadata["bool"] != true { + t.Fatalf("typed metadata = %#v", metadata) + } + nested, ok := metadata["nested"].(map[string]any) + if !ok || nested["enabled"] != true { + t.Fatalf("nested metadata = %#v", metadata["nested"]) + } + merged, ok := metadata["merged"].(map[string]any) + if !ok || merged["source"] != "merge" { + t.Fatalf("merged metadata = %#v", metadata["merged"]) + } + if _, ok := metadata["overlap"]; ok { + t.Fatalf("overlap survived unset: %#v", metadata) + } + if _, ok := metadata["remove"]; ok { + t.Fatalf("remove survived unset: %#v", metadata) + } +} diff --git a/internal/storage/uow/tx_test.go b/internal/storage/uow/tx_test.go index a0d00e84f..baa4bf7df 100644 --- a/internal/storage/uow/tx_test.go +++ b/internal/storage/uow/tx_test.go @@ -13,9 +13,14 @@ import ( // mockUnitOfWork implements UnitOfWork for testing type mockUnitOfWork struct { - commitErr error - commitCount int - closed bool + commitErr error + commitCount int + closed bool + configUseCase domain.ConfigUseCase + issueUseCase domain.IssueUseCase + dependencyUseCase domain.DependencyUseCase + labelUseCase domain.LabelUseCase + commentUseCase domain.CommentUseCase } func (m *mockUnitOfWork) Close(ctx context.Context) { @@ -29,23 +34,25 @@ func (m *mockUnitOfWork) Commit(ctx context.Context, message string) error { func (m *mockUnitOfWork) SwitchDatabase(ctx context.Context, database string) error { return nil } -func (m *mockUnitOfWork) ConfigUseCase() domain.ConfigUseCase { return nil } +func (m *mockUnitOfWork) ConfigUseCase() domain.ConfigUseCase { return m.configUseCase } func (m *mockUnitOfWork) DoltRemoteUseCase() domain.DoltRemoteUseCase { return nil } func (m *mockUnitOfWork) BootstrapUseCase() domain.BootstrapUseCase { return nil } -func (m *mockUnitOfWork) IssueUseCase() domain.IssueUseCase { return nil } -func (m *mockUnitOfWork) DependencyUseCase() domain.DependencyUseCase { return nil } -func (m *mockUnitOfWork) LabelUseCase() domain.LabelUseCase { return nil } -func (m *mockUnitOfWork) CommentUseCase() domain.CommentUseCase { return nil } +func (m *mockUnitOfWork) IssueUseCase() domain.IssueUseCase { return m.issueUseCase } +func (m *mockUnitOfWork) DependencyUseCase() domain.DependencyUseCase { return m.dependencyUseCase } +func (m *mockUnitOfWork) LabelUseCase() domain.LabelUseCase { return m.labelUseCase } +func (m *mockUnitOfWork) CommentUseCase() domain.CommentUseCase { return m.commentUseCase } func (m *mockUnitOfWork) RawSQLUseCase() domain.RawSQLUseCase { return nil } // mockUnitOfWorkProvider implements UnitOfWorkProvider for testing type mockUnitOfWorkProvider struct { - uows []*mockUnitOfWork - uowIndex int - newUOWErr error + uows []*mockUnitOfWork + uowIndex int + newUOWCalls int + newUOWErr error } func (m *mockUnitOfWorkProvider) NewUOW(ctx context.Context) (UnitOfWork, error) { + m.newUOWCalls++ if m.newUOWErr != nil { return nil, m.newUOWErr } @@ -65,6 +72,11 @@ func newMySQLError(code uint16) error { return &mysql.MySQLError{Number: code, Message: "test error"} } +type sqlStateError string + +func (e sqlStateError) Error() string { return "sqlstate " + string(e) } +func (e sqlStateError) SQLState() string { return string(e) } + func TestRunTx_Success(t *testing.T) { uw := &mockUnitOfWork{} provider := &mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}} @@ -166,6 +178,28 @@ func TestRunTx_RetriesOnLockWaitTimeout(t *testing.T) { } } +func TestRunTx_RetriesOnPostgresSerializationStates(t *testing.T) { + for _, state := range []string{"40001", "40P01"} { + t.Run(state, func(t *testing.T) { + first := &mockUnitOfWork{commitErr: sqlStateError(state)} + second := &mockUnitOfWork{} + provider := &mockUnitOfWorkProvider{uows: []*mockUnitOfWork{first, second}} + + var calls int32 + err := RunTx(context.Background(), provider, func(context.Context, UnitOfWork) (string, error) { + atomic.AddInt32(&calls, 1) + return "retry postgres serialization", nil + }) + if err != nil { + t.Fatalf("RunTx() error = %v", err) + } + if calls != 2 { + t.Fatalf("work calls = %d, want 2", calls) + } + }) + } +} + func TestRunTx_NothingToCommitIsSuccess(t *testing.T) { uw := &mockUnitOfWork{commitErr: errors.New("nothing to commit")} provider := &mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}} diff --git a/internal/telemetry/issue_operations.go b/internal/telemetry/issue_operations.go new file mode 100644 index 000000000..211d53a91 --- /dev/null +++ b/internal/telemetry/issue_operations.go @@ -0,0 +1,57 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// IssueLifecycle returns the inner store's lifecycle wrapped in this layer's +// instrumentation. It recurses instead of delegating: a blind delegation would +// return the inner lifecycle unspanned and untimed. +func (s *InstrumentedStorage) IssueLifecycle() (issueops.Lifecycle, error) { + inner, err := s.Unwrap().IssueLifecycle() + if err != nil { + return nil, err + } + return s.WrapIssueOperations(inner), nil +} + +// WrapIssueOperations instruments guarded public issue operations with this +// storage layer's existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapIssueOperations(inner issueops.Lifecycle) issueops.Lifecycle { + return &instrumentedIssueOperations{storage: s, inner: inner} +} + +type instrumentedIssueOperations struct { + storage *InstrumentedStorage + inner issueops.Lifecycle +} + +func (o *instrumentedIssueOperations) Create(ctx context.Context, request issueops.CreateRequest) (result issueops.CreateResult, err error) { + ctx, span, started := o.storage.op(ctx, "IssueOperations.Create") + result, err = o.inner.Create(ctx, request) + o.storage.done(ctx, span, started, err) + return result, err +} + +func (o *instrumentedIssueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (result issueops.UpdateResult, err error) { + ctx, span, started := o.storage.op(ctx, "IssueOperations.Update") + result, err = o.inner.Update(ctx, request) + o.storage.done(ctx, span, started, err) + return result, err +} + +func (o *instrumentedIssueOperations) Close(ctx context.Context, request issueops.CloseRequest) (result issueops.CloseResult, err error) { + ctx, span, started := o.storage.op(ctx, "IssueOperations.Close") + result, err = o.inner.Close(ctx, request) + o.storage.done(ctx, span, started, err) + return result, err +} + +func (o *instrumentedIssueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (result issueops.ReopenResult, err error) { + ctx, span, started := o.storage.op(ctx, "IssueOperations.Reopen") + result, err = o.inner.Reopen(ctx, request) + o.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/issue_operations_test.go b/internal/telemetry/issue_operations_test.go new file mode 100644 index 000000000..d7b741616 --- /dev/null +++ b/internal/telemetry/issue_operations_test.go @@ -0,0 +1,119 @@ +package telemetry + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/issueops" +) + +type fakeIssueOperations struct { + calls int + err error +} + +func (f *fakeIssueOperations) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { + f.calls++ + return issueops.CreateResult{}, f.err +} +func (f *fakeIssueOperations) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) { + f.calls++ + return issueops.UpdateResult{}, f.err +} +func (f *fakeIssueOperations) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) { + f.calls++ + return issueops.CloseResult{}, f.err +} +func (f *fakeIssueOperations) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { + f.calls++ + return issueops.ReopenResult{}, f.err +} + +// lifecycleDoltStore is a DoltStorage whose only real method is IssueLifecycle, +// so a test can see which lifecycle the instrumented layer recursed into. +type lifecycleDoltStore struct { + storage.DoltStorage + lifecycle issueops.Lifecycle + err error +} + +func (s *lifecycleDoltStore) IssueLifecycle() (issueops.Lifecycle, error) { + return s.lifecycle, s.err +} + +// TestInstrumentedStorageIssueLifecycleInstrumentsInner pins the recursion: +// delegating to the inner store would compile and return an unspanned, +// untimed lifecycle. +func TestInstrumentedStorageIssueLifecycleInstrumentsInner(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + inner := &fakeIssueOperations{} + wrapped := WrapStorage(&lifecycleDoltStore{lifecycle: inner}).(*InstrumentedStorage) + + lifecycle, err := wrapped.IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle() error = %v", err) + } + instrumented, ok := lifecycle.(*instrumentedIssueOperations) + if !ok { + t.Fatalf("IssueLifecycle() = %T, want *instrumentedIssueOperations", lifecycle) + } + if instrumented.inner != issueops.Lifecycle(inner) { + t.Fatalf("telemetry layer wraps %#v, want the inner store's lifecycle", instrumented.inner) + } +} + +func TestInstrumentedStorageIssueLifecyclePropagatesInnerError(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + want := errors.New("inner refused") + wrapped := WrapStorage(&lifecycleDoltStore{err: want}).(*InstrumentedStorage) + + lifecycle, err := wrapped.IssueLifecycle() + if !errors.Is(err, want) { + t.Fatalf("IssueLifecycle() error = %v, want %v", err, want) + } + if lifecycle != nil { + t.Fatalf("IssueLifecycle() = %T, want nil", lifecycle) + } +} + +func TestInstrumentedIssueOperationsForwardsEveryAttemptOnce(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + base := WrapStorage(&fakeDoltStore{}).(*InstrumentedStorage) + for _, test := range []struct { + name string + call func(issueops.Lifecycle) error + }{ + {"create", func(o issueops.Lifecycle) error { + _, e := o.Create(context.Background(), issueops.CreateRequest{}) + return e + }}, + {"update", func(o issueops.Lifecycle) error { + _, e := o.Update(context.Background(), issueops.UpdateRequest{}) + return e + }}, + {"close", func(o issueops.Lifecycle) error { + _, e := o.Close(context.Background(), issueops.CloseRequest{}) + return e + }}, + {"reopen", func(o issueops.Lifecycle) error { + _, e := o.Reopen(context.Background(), issueops.ReopenRequest{}) + return e + }}, + } { + t.Run(test.name+" success", func(t *testing.T) { + fake := &fakeIssueOperations{} + if err := test.call(base.WrapIssueOperations(fake)); err != nil || fake.calls != 1 { + t.Fatalf("err=%v calls=%d", err, fake.calls) + } + }) + t.Run(test.name+" error", func(t *testing.T) { + want := errors.New("underlying") + fake := &fakeIssueOperations{err: want} + if err := test.call(base.WrapIssueOperations(fake)); !errors.Is(err, want) || fake.calls != 1 { + t.Fatalf("err=%v calls=%d", err, fake.calls) + } + }) + } +} diff --git a/internal/telemetry/storage.go b/internal/telemetry/storage.go index 137abdbd7..6338c91ee 100644 --- a/internal/telemetry/storage.go +++ b/internal/telemetry/storage.go @@ -559,6 +559,14 @@ func (s *InstrumentedStorage) RunInTransaction(ctx context.Context, commitMsg st return err } +// RunInIssueLifecycleTransaction traces the required internal lifecycle lane. +func (s *InstrumentedStorage) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx storage.IssueLifecycleTransaction) error) error { + ctx, span, t := s.op(ctx, "RunInIssueLifecycleTransaction", attribute.String("db.commit_msg", commitMsg)) + err := s.inner.RunInIssueLifecycleTransaction(ctx, commitMsg, fn) + s.done(ctx, span, t, err) + return err +} + // ── Wisp queries ───────────────────────────────────────────────────────────── func (s *InstrumentedStorage) ListWisps(ctx context.Context, filter types.WispFilter) ([]*types.Issue, error) { diff --git a/internal/tracker/engine.go b/internal/tracker/engine.go index a133745b6..18f04a4be 100644 --- a/internal/tracker/engine.go +++ b/internal/tracker/engine.go @@ -94,7 +94,7 @@ type PushHooks struct { // integrations follow, eliminating duplication between Linear, GitLab, etc. type Engine struct { Tracker IssueTracker - Store storage.Storage + Store lifecycleStorage Actor string PullHooks *PullHooks PushHooks *PushHooks @@ -111,8 +111,13 @@ type Engine struct { warnings []string } +type lifecycleStorage interface { + storage.Storage + storage.IssueLifecycleStore +} + // NewEngine creates a new sync engine for the given tracker and storage. -func NewEngine(tracker IssueTracker, store storage.Storage, actor string) *Engine { +func NewEngine(tracker IssueTracker, store lifecycleStorage, actor string) *Engine { return &Engine{ Tracker: tracker, Store: store, @@ -503,13 +508,14 @@ func (e *Engine) doPull(ctx context.Context, opts SyncOptions, allowOverwriteIDs updates["metadata"] = raw } - if err := e.Store.RunInTransaction(ctx, fmt.Sprintf("bd: pull update %s", existing.ID), func(tx storage.Transaction) error { - if err := tx.UpdateIssue(ctx, existing.ID, updates, e.Actor); err != nil { - return err - } - return syncIssueLabels(ctx, tx, existing.ID, conv.Issue.Labels, e.Actor) + if err := e.Store.RunInIssueLifecycleTransaction(ctx, fmt.Sprintf("bd: pull update %s", existing.ID), func(tx storage.IssueLifecycleTransaction) error { + return applyPullIssueUpdate(ctx, tx, existing.ID, updates, conv.Issue.Labels, e.Actor) }); err != nil { e.warn("Failed to update %s: %v", existing.ID, err) + stats.Errors++ + if pulledIDs != nil { + pulledIDs[existing.ID] = true + } continue } stats.Updated++ @@ -550,6 +556,20 @@ func (e *Engine) doPull(ctx context.Context, opts SyncOptions, allowOverwriteIDs return stats, nil } +// applyPullIssueUpdate keeps a pulled update atomic with its labels. +func applyPullIssueUpdate(ctx context.Context, tx storage.IssueLifecycleTransaction, id string, updates map[string]interface{}, labels []string, actor string) error { + if err := applyPullIssueFields(ctx, tx, id, updates, actor); err != nil { + return err + } + return syncIssueLabels(ctx, tx, id, labels, actor) +} + +// applyPullIssueFields applies a pulled issue's fields while preserving the +// caller's control over related collections such as labels. +func applyPullIssueFields(ctx context.Context, tx storage.IssueLifecycleTransaction, id string, updates map[string]interface{}, actor string) error { + return tx.UpdateIssue(ctx, id, updates, actor) +} + func pullIssueEqual(local *types.Issue, remote *types.Issue, ref string) bool { if local == nil || remote == nil { return false @@ -1149,7 +1169,9 @@ func (e *Engine) resolveConflicts(opts SyncOptions, conflicts []Conflict, skipID } } -// reimportIssue fetches the external version and updates the local issue. +// reimportIssue fetches an external version and reapplies its scalar fields. +// It deliberately preserves local labels because conflict reimport has no +// authoritative label collection to synchronize. func (e *Engine) reimportIssue(ctx context.Context, c Conflict) { extIssue, err := e.Tracker.FetchIssue(ctx, c.ExternalIdentifier) if err != nil || extIssue == nil { @@ -1174,7 +1196,9 @@ func (e *Engine) reimportIssue(ctx context.Context, c Conflict) { } } - if err := e.Store.UpdateIssue(ctx, c.IssueID, updates, e.Actor); err != nil { + if err := e.Store.RunInIssueLifecycleTransaction(ctx, fmt.Sprintf("bd: reimport update %s", c.IssueID), func(tx storage.IssueLifecycleTransaction) error { + return applyPullIssueFields(ctx, tx, c.IssueID, updates, e.Actor) + }); err != nil { e.warn("Failed to update %s during reimport: %v", c.IssueID, err) } } diff --git a/internal/tracker/engine_external_ref_history_test.go b/internal/tracker/engine_external_ref_history_test.go index 7841c1f92..3153d8cb6 100644 --- a/internal/tracker/engine_external_ref_history_test.go +++ b/internal/tracker/engine_external_ref_history_test.go @@ -27,6 +27,7 @@ import ( // call the promoted methods. type historyQuerierStore struct { storage.Storage + storage.IssueLifecycleStore prevRef string prevFound bool diff --git a/internal/tracker/engine_pull_failure_test.go b/internal/tracker/engine_pull_failure_test.go new file mode 100644 index 000000000..4b3d70d97 --- /dev/null +++ b/internal/tracker/engine_pull_failure_test.go @@ -0,0 +1,218 @@ +package tracker + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +type pullTestTransaction struct { + storage.Transaction + issue *types.Issue + addLabelErr error +} + +func (t *pullTestTransaction) UpdateIssue(_ context.Context, _ string, updates map[string]interface{}, _ string) error { + if title, ok := updates["title"].(string); ok { + t.issue.Title = title + } + if status, ok := updates["status"]; ok { + switch value := status.(type) { + case types.Status: + t.issue.Status = value + case string: + t.issue.Status = types.Status(value) + } + } + return nil +} + +func (t *pullTestTransaction) ReopenIssueWithResult(_ context.Context, _ string, _ string, _ string) (bool, error) { + t.issue.Status = types.StatusOpen + t.issue.ClosedAt = nil + return true, nil +} + +func (t *pullTestTransaction) GetIssue(_ context.Context, _ string) (*types.Issue, error) { + return t.issue, nil +} + +func (t *pullTestTransaction) GetLabels(context.Context, string) ([]string, error) { + return append([]string(nil), t.issue.Labels...), nil +} +func (t *pullTestTransaction) AddLabel(_ context.Context, _ string, label string, _ string) error { + if t.addLabelErr != nil { + return t.addLabelErr + } + for _, existing := range t.issue.Labels { + if existing == label { + return nil + } + } + t.issue.Labels = append(t.issue.Labels, label) + return nil +} +func (t *pullTestTransaction) RemoveLabel(_ context.Context, _ string, label string, _ string) error { + for i, existing := range t.issue.Labels { + if existing == label { + t.issue.Labels = append(t.issue.Labels[:i], t.issue.Labels[i+1:]...) + break + } + } + return nil +} + +type pullFailureStore struct { + *pureTestStore + tx *pullTestTransaction + commits int +} + +func (s *pullFailureStore) RunInTransaction(_ context.Context, _ string, fn func(storage.Transaction) error) error { + before := *s.tx.issue + if err := fn(s.tx); err != nil { + *s.tx.issue = before + return err + } + s.commits++ + return nil +} + +func (s *pullFailureStore) RunInIssueLifecycleTransaction(_ context.Context, _ string, fn func(storage.IssueLifecycleTransaction) error) error { + before := *s.tx.issue + if err := fn(s.tx); err != nil { + *s.tx.issue = before + return err + } + s.commits++ + return nil +} + +func (s *pullFailureStore) GetIssueByExternalRef(_ context.Context, ref string) (*types.Issue, error) { + for _, issue := range s.issues { + if issue.ExternalRef != nil && *issue.ExternalRef == ref { + return issue, nil + } + } + return nil, nil +} + +func TestEngineSyncFailedPullIsNotPushed(t *testing.T) { + remoteUpdated := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + for _, test := range []struct { + name string + localID string + identifier string + externalRef string + localUpdated time.Time + }{ + { + name: "create-eligible", + localID: "pull-failure-create", + identifier: "EXT-CREATE", + localUpdated: remoteUpdated, + }, + { + name: "update-eligible", + localID: "pull-failure-update", + identifier: "EXT-UPDATE", + externalRef: "https://test.test/EXT-UPDATE", + localUpdated: remoteUpdated.Add(time.Hour), + }, + } { + t.Run(test.name, func(t *testing.T) { + ctx := context.Background() + local := &types.Issue{ + ID: test.localID, + Title: "local", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + UpdatedAt: test.localUpdated, + } + if test.externalRef != "" { + ref := test.externalRef + local.ExternalRef = &ref + } + store := &pullFailureStore{ + pureTestStore: newPureTestStore(local), + tx: &pullTestTransaction{ + issue: local, addLabelErr: errors.New("label write failed"), + }, + } + mock := newMockTracker("test") + mock.issues = []TrackerIssue{{ + ID: test.identifier, Identifier: test.identifier, Title: "remote", UpdatedAt: remoteUpdated, + }} + mock.fieldMapper = &mockMapper{issueToBeads: func(*TrackerIssue) *IssueConversion { + return &IssueConversion{Issue: &types.Issue{ + ID: test.localID, Title: "remote", Status: types.StatusClosed, + Priority: 2, IssueType: types.TypeTask, Labels: []string{"remote"}, + }} + }} + + result, err := NewEngine(mock, store, "sync").Sync(ctx, SyncOptions{Pull: true, Push: true}) + if err != nil { + t.Fatalf("Sync: %v", err) + } + if result.PullStats.Errors != 1 || result.PullStats.Created != 0 || result.PullStats.Updated != 0 { + t.Fatalf("PullStats = %+v, want one error and no create/update", result.PullStats) + } + if result.PushStats.Created != 0 || result.PushStats.Updated != 0 || len(mock.created) != 0 || len(mock.updated) != 0 { + t.Fatalf("%s failed pull was pushed: PushStats=%+v create calls=%d update calls=%d", + test.name, result.PushStats, len(mock.created), len(mock.updated)) + } + if store.commits != 0 || local.Status != types.StatusOpen || + local.Title != "local" || len(local.Labels) != 0 || !local.UpdatedAt.Equal(test.localUpdated) { + t.Fatalf("%s failed pull committed state: commits=%d issue=%+v", test.name, store.commits, local) + } + if test.externalRef == "" { + if local.ExternalRef != nil { + t.Fatalf("create-eligible failed pull left external_ref %q", *local.ExternalRef) + } + } else if local.ExternalRef == nil || *local.ExternalRef != test.externalRef { + t.Fatalf("update-eligible failed pull changed external_ref to %v", local.ExternalRef) + } + }) + } +} + +func TestReimportIssuePreservesLabels(t *testing.T) { + ctx := context.Background() + local := &types.Issue{ + ID: "reimport-labels", + Title: "local", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Labels: []string{"keep-local-label"}, + } + store := &pullFailureStore{ + pureTestStore: newPureTestStore(local), + tx: &pullTestTransaction{issue: local}, + } + mock := newMockTracker("test") + mock.issues = []TrackerIssue{{ID: "EXT-2", Identifier: "EXT-2", Title: "remote"}} + mock.fieldMapper = &mockMapper{issueToBeads: func(*TrackerIssue) *IssueConversion { + return &IssueConversion{Issue: &types.Issue{ + Title: "remote", Status: types.StatusClosed, Priority: 1, IssueType: types.TypeTask, + }} + }} + + engine := NewEngine(mock, store, "sync") + engine.reimportIssue(ctx, Conflict{IssueID: local.ID, ExternalIdentifier: "EXT-2"}) + + if store.commits != 1 { + t.Fatalf("reimport transaction commits = %d, want 1", store.commits) + } + if local.Status != types.StatusClosed || local.Title != "remote" { + t.Fatalf("reimport result = %+v", local) + } + if len(local.Labels) != 1 || local.Labels[0] != "keep-local-label" { + t.Fatalf("reimport changed local labels: %v", local.Labels) + } +} diff --git a/internal/tracker/engine_test.go b/internal/tracker/engine_test.go index 9665704d6..05bfd8198 100644 --- a/internal/tracker/engine_test.go +++ b/internal/tracker/engine_test.go @@ -226,6 +226,80 @@ func TestEnginePullUpdatesLabelsOnExistingIssue(t *testing.T) { } } +func TestEnginePullClosesExistingIssueAndSyncsLabels(t *testing.T) { + ctx := context.Background() + store := newTestStore(t) + defer store.Close() + + extRef := "https://test.test/EXT-closed" + issue := &types.Issue{ + ID: "bd-closed-boundary", + Title: "Local title", + Status: types.StatusOpen, + IssueType: types.TypeTask, + Priority: 2, + Labels: []string{"old-label"}, + ExternalRef: &extRef, + UpdatedAt: time.Now().UTC().Add(-time.Hour), + } + if err := store.CreateIssue(ctx, issue, "test-actor"); err != nil { + t.Fatalf("CreateIssue() error: %v", err) + } + + tracker := newMockTracker("test") + tracker.issues = []TrackerIssue{{ + ID: "EXT-closed", + Identifier: "EXT-closed", + URL: extRef, + Title: "Remote done title", + Labels: []string{"remote-a", "remote-b"}, + UpdatedAt: time.Now().UTC(), + }} + tracker.fieldMapper = &mockMapper{issueToBeads: func(ti *TrackerIssue) *IssueConversion { + return &IssueConversion{Issue: &types.Issue{ + ID: "bd-closed-boundary", + Title: ti.Title, + Status: types.StatusClosed, + IssueType: types.TypeTask, + Priority: 2, + Labels: append([]string(nil), ti.Labels...), + }} + }} + + result, err := NewEngine(tracker, store, "test-actor").Sync(ctx, SyncOptions{Pull: true}) + if err != nil { + t.Fatalf("Sync() error: %v", err) + } + if result.PullStats.Updated != 1 || result.PullStats.Errors != 0 { + t.Fatalf("PullStats = %+v, want one successful update", result.PullStats) + } + + updated, err := store.GetIssue(ctx, issue.ID) + if err != nil { + t.Fatalf("GetIssue() error: %v", err) + } + if updated.Status != types.StatusClosed || updated.ClosedAt == nil || updated.Title != "Remote done title" { + t.Fatalf("updated issue = %+v, want closed issue with remote title", updated) + } + labels, err := store.GetLabels(ctx, issue.ID) + if err != nil { + t.Fatalf("GetLabels() error: %v", err) + } + if !equalNormalizedStrings(labels, []string{"remote-a", "remote-b"}) { + t.Fatalf("labels = %v, want [remote-a remote-b]", labels) + } + events, err := store.GetEvents(ctx, issue.ID, 20) + if err != nil { + t.Fatalf("GetEvents() error: %v", err) + } + for _, event := range events { + if event.EventType == types.EventClosed { + return + } + } + t.Fatalf("events = %+v, want closed lifecycle event", events) +} + func TestEnginePullDryRunTreatsLabelOnlyChangeAsUpdate(t *testing.T) { ctx := context.Background() store := newTestStore(t) diff --git a/internal/tracker/test_helpers_pure_test.go b/internal/tracker/test_helpers_pure_test.go index df609f510..f152597b7 100644 --- a/internal/tracker/test_helpers_pure_test.go +++ b/internal/tracker/test_helpers_pure_test.go @@ -221,6 +221,7 @@ func (m *mockMapper) IssueToBeads(ti *TrackerIssue) *IssueConversion { type pureTestStore struct { storage.Storage + storage.IssueLifecycleStore issues []*types.Issue localMetadata map[string]string } diff --git a/internal/types/storage_class_test.go b/internal/types/storage_class_test.go index 4a7c39929..d9d8dabcf 100644 --- a/internal/types/storage_class_test.go +++ b/internal/types/storage_class_test.go @@ -121,8 +121,8 @@ func TestIssueValidateStorageClass(t *testing.T) { } } -// C2.4: storage_class appears in JSONL for non-versioned records and is -// omitted when versioned (unset). +// storage_class appears in JSONL for non-versioned records and is omitted when +// versioned (unset). func TestStorageClassJSONRoundTrip(t *testing.T) { unversioned := validBaseIssue() unversioned.StorageClass = StorageClassUnversioned @@ -151,3 +151,151 @@ func TestStorageClassJSONRoundTrip(t *testing.T) { t.Errorf("versioned (unset) record must omit storage_class, got: %s", data) } } + +func TestPersistenceModeValuesAndValidation(t *testing.T) { + valid := []PersistenceMode{ + PersistenceModePersistent, + PersistenceModeEphemeral, + PersistenceModeNoHistory, + } + for _, mode := range valid { + if !mode.IsValid() { + t.Errorf("PersistenceMode(%q).IsValid() = false, want true", mode) + } + } + for _, mode := range []PersistenceMode{"", "durable", "wisp"} { + if mode.IsValid() { + t.Errorf("PersistenceMode(%q).IsValid() = true, want false", mode) + } + } +} + +func TestNormalizePersistenceMode(t *testing.T) { + cases := []struct { + current Issue + mode PersistenceMode + wantEphemeral, wantNoHistory bool + wantStorageClass StorageClass + }{ + {Issue{}, PersistenceModePersistent, false, false, ""}, + {Issue{StorageClass: StorageClassVersioned}, PersistenceModePersistent, false, false, StorageClassVersioned}, + {Issue{}, PersistenceModeEphemeral, true, false, ""}, + {Issue{}, PersistenceModeNoHistory, false, true, ""}, + {Issue{StorageClass: StorageClassVersioned}, PersistenceModeEphemeral, true, false, ""}, + {Issue{StorageClass: StorageClassVersioned}, PersistenceModeNoHistory, false, true, ""}, + {Issue{Ephemeral: true, StorageClass: StorageClassEphemeral}, PersistenceModeEphemeral, true, false, StorageClassEphemeral}, + {Issue{NoHistory: true, StorageClass: StorageClassEphemeral}, PersistenceModeNoHistory, false, true, StorageClassEphemeral}, + {Issue{Ephemeral: true, StorageClass: StorageClassEphemeral}, PersistenceModeNoHistory, false, true, StorageClassEphemeral}, + {Issue{NoHistory: true, StorageClass: StorageClassEphemeral}, PersistenceModeEphemeral, true, false, StorageClassEphemeral}, + {Issue{Ephemeral: true, StorageClass: StorageClassEphemeral}, PersistenceModePersistent, false, false, ""}, + {Issue{NoHistory: true, StorageClass: StorageClassEphemeral}, PersistenceModePersistent, false, false, ""}, + {Issue{StorageClass: StorageClassUnversioned}, PersistenceModePersistent, false, false, StorageClassUnversioned}, + {Issue{Ephemeral: true}, PersistenceModeEphemeral, true, false, ""}, + {Issue{NoHistory: true}, PersistenceModeNoHistory, false, true, ""}, + {Issue{Ephemeral: true}, PersistenceModeNoHistory, false, true, ""}, + {Issue{NoHistory: true}, PersistenceModeEphemeral, true, false, ""}, + } + for _, tc := range cases { + ephemeral, noHistory, storageClass, err := NormalizePersistenceMode(tc.current, tc.mode) + if err != nil { + t.Errorf("NormalizePersistenceMode(%q): %v", tc.mode, err) + continue + } + if ephemeral != tc.wantEphemeral || noHistory != tc.wantNoHistory || storageClass != tc.wantStorageClass { + t.Errorf("NormalizePersistenceMode(%q) = (%t, %t, %q), want (%t, %t, %q)", tc.mode, ephemeral, noHistory, storageClass, tc.wantEphemeral, tc.wantNoHistory, tc.wantStorageClass) + } + } +} + +func TestNormalizePersistenceModeReturnsValidIssueStates(t *testing.T) { + for _, target := range []PersistenceMode{PersistenceModeEphemeral, PersistenceModeNoHistory} { + current := validBaseIssue() + current.StorageClass = StorageClassVersioned + + ephemeral, noHistory, storageClass, err := NormalizePersistenceMode(current, target) + if err != nil { + t.Fatalf("NormalizePersistenceMode(versioned, %q): %v", target, err) + } + current.Ephemeral = ephemeral + current.NoHistory = noHistory + current.StorageClass = storageClass + if err := current.Validate(); err != nil { + t.Errorf("normalized versioned -> %q state is invalid: %v", target, err) + } + } + + for _, current := range []Issue{ + func() Issue { + issue := validBaseIssue() + issue.Ephemeral = true + issue.StorageClass = StorageClassEphemeral + return issue + }(), + func() Issue { + issue := validBaseIssue() + issue.NoHistory = true + issue.StorageClass = StorageClassEphemeral + return issue + }(), + } { + ephemeral, noHistory, storageClass, err := NormalizePersistenceMode(current, PersistenceModePersistent) + if err != nil { + t.Fatalf("NormalizePersistenceMode(wisp, persistent): %v", err) + } + current.Ephemeral = ephemeral + current.NoHistory = noHistory + current.StorageClass = storageClass + if err := current.Validate(); err != nil { + t.Errorf("normalized wisp promotion is invalid: %v", err) + } + } +} + +func TestNormalizePersistenceModeRejectsIncoherentWispFlags(t *testing.T) { + current := Issue{Ephemeral: true, NoHistory: true} + for _, target := range []PersistenceMode{ + PersistenceModePersistent, + PersistenceModeEphemeral, + PersistenceModeNoHistory, + } { + if _, _, _, err := NormalizePersistenceMode(current, target); err == nil { + t.Errorf("NormalizePersistenceMode(incoherent, %q) succeeded, want error", target) + } + } +} + +func TestNormalizePersistenceModeRejectsPlaneClassIncoherence(t *testing.T) { + cases := []struct { + name string + current Issue + target PersistenceMode + }{ + {"ephemeral with explicit versioned", Issue{Ephemeral: true, StorageClass: StorageClassVersioned}, PersistenceModeEphemeral}, + {"no history with explicit versioned", Issue{NoHistory: true, StorageClass: StorageClassVersioned}, PersistenceModeNoHistory}, + {"ephemeral with unversioned", Issue{Ephemeral: true, StorageClass: StorageClassUnversioned}, PersistenceModeEphemeral}, + {"no history with unversioned", Issue{NoHistory: true, StorageClass: StorageClassUnversioned}, PersistenceModeNoHistory}, + {"durable with explicit ephemeral", Issue{StorageClass: StorageClassEphemeral}, PersistenceModePersistent}, + } + for _, tc := range cases { + if _, _, _, err := NormalizePersistenceMode(tc.current, tc.target); err == nil { + t.Errorf("%s: NormalizePersistenceMode succeeded, want error", tc.name) + } + } +} + +func TestNormalizePersistenceModeRejectsUnsetAndUnknown(t *testing.T) { + for _, mode := range []PersistenceMode{"", "durable"} { + if _, _, _, err := NormalizePersistenceMode(Issue{}, mode); err == nil { + t.Errorf("NormalizePersistenceMode(%q) succeeded, want error", mode) + } + } +} + +func TestNormalizePersistenceModeRejectsUnversionedDemotion(t *testing.T) { + current := Issue{StorageClass: StorageClassUnversioned} + for _, target := range []PersistenceMode{PersistenceModeEphemeral, PersistenceModeNoHistory} { + if _, _, _, err := NormalizePersistenceMode(current, target); err == nil { + t.Errorf("NormalizePersistenceMode(unversioned, %q) succeeded, want error", target) + } + } +} diff --git a/internal/types/types.go b/internal/types/types.go index aa47847cc..e2be357b2 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -123,11 +123,12 @@ type Issue struct { NoHistory bool `json:"no_history,omitempty"` // If true, stored in wisps table but NOT GC-eligible WispType WispType `json:"wisp_type,omitempty"` // Classification for TTL-based compaction (gt-9br) - // StorageClass declares the record's history/replication contract - // (Protocol v0.1 §C, bd-7vb13). Empty means unset: effective class is - // ephemeral for wisp-plane records (Ephemeral/NoHistory), else versioned - // (C1.2) — see EffectiveStorageClass. Omitted from JSONL when versioned - // (C2.4). Set at create, immutable except via promotion (C1.3/C4). + // StorageClass is the create-selected marker for the record's history and + // replication contract. Persistence plane transitions preserve it except + // where coherence requires normalizing explicit versioned to empty on + // demotion or explicit ephemeral to empty on promotion. When the marker is + // empty, the effective class follows the plane: ephemeral for Ephemeral or + // NoHistory rows and versioned otherwise. StorageClass StorageClass `json:"storage_class,omitempty"` // NOTE: RepliesTo, RelatesTo, DuplicateOf, SupersededBy moved to dependencies table // per Decision 004 (Edge Schema Consolidation). Use dependency API instead. @@ -263,13 +264,13 @@ func (w hashFieldWriter) flag(b bool, label string) { w.h.Write([]byte{0}) } -// MaxFieldLen is the maximum length (in characters) of the assignee, owner, and -// label fields, matching their VARCHAR(255) columns. +// MaxFieldLen is the maximum length (in characters) of common bounded text +// fields, matching their VARCHAR(255) columns. const MaxFieldLen = 255 -// ErrFieldTooLong is returned when assignee, owner, or a label exceeds -// MaxFieldLen characters. Callers can errors.Is it instead of matching a raw -// backend "data too long" string. +// ErrFieldTooLong is returned when a bounded text field exceeds MaxFieldLen +// characters. Callers can errors.Is it instead of matching a raw backend "data +// too long" string. var ErrFieldTooLong = errors.New("field exceeds maximum length") // CheckFieldLen returns ErrFieldTooLong (wrapped with context) when val exceeds @@ -283,6 +284,35 @@ func CheckFieldLen(name, val string) error { return nil } +// ValidateIssueTitle checks the canonical issue-title requirements. The title +// must be nonempty and at most 500 bytes. +func ValidateIssueTitle(title string) error { + if len(title) == 0 { + return fmt.Errorf("title is required") + } + if len(title) > 500 { + return fmt.Errorf("title must be 500 characters or less (got %d)", len(title)) + } + return nil +} + +// ValidateIssuePriority checks that priority is in the canonical P0-P4 range. +func ValidateIssuePriority(priority int) error { + if priority < 0 || priority > 4 { + return fmt.Errorf("priority must be between 0 and 4 (got %d)", priority) + } + return nil +} + +// ValidateIssueEstimatedMinutes checks that a supplied estimate is +// nonnegative. A nil estimate is valid. +func ValidateIssueEstimatedMinutes(estimatedMinutes *int) error { + if estimatedMinutes != nil && *estimatedMinutes < 0 { + return fmt.Errorf("estimated_minutes cannot be negative") + } + return nil +} + // Validate checks if the issue has valid field values (built-in statuses only) func (i *Issue) Validate() error { return i.ValidateWithCustomStatuses(nil) @@ -297,14 +327,11 @@ func (i *Issue) ValidateWithCustomStatuses(customStatuses []string) error { // ValidateWithCustom checks if the issue has valid field values, // allowing custom statuses and types in addition to built-in ones. func (i *Issue) ValidateWithCustom(customStatuses, customTypes []string) error { - if len(i.Title) == 0 { - return fmt.Errorf("title is required") + if err := ValidateIssueTitle(i.Title); err != nil { + return err } - if len(i.Title) > 500 { - return fmt.Errorf("title must be 500 characters or less (got %d)", len(i.Title)) - } - if i.Priority < 0 || i.Priority > 4 { - return fmt.Errorf("priority must be between 0 and 4 (got %d)", i.Priority) + if err := ValidateIssuePriority(i.Priority); err != nil { + return err } if !i.Status.IsValidWithCustom(customStatuses) { return fmt.Errorf("invalid status: %s", i.Status) @@ -312,8 +339,8 @@ func (i *Issue) ValidateWithCustom(customStatuses, customTypes []string) error { if !i.IssueType.IsValidWithCustom(customTypes) { return fmt.Errorf("invalid issue type: %s", i.IssueType) } - if i.EstimatedMinutes != nil && *i.EstimatedMinutes < 0 { - return fmt.Errorf("estimated_minutes cannot be negative") + if err := ValidateIssueEstimatedMinutes(i.EstimatedMinutes); err != nil { + return err } // Enforce closed_at invariant: closed_at should be set if and only if status is closed if i.Status == StatusClosed && i.ClosedAt == nil { @@ -335,8 +362,7 @@ func (i *Issue) ValidateWithCustom(customStatuses, customTypes []string) error { // Storage class must be a known value, and a declared class must agree // with the wisp-plane flags: wisp-plane records are ephemeral-class by // construction, and a durable class on one (or ephemeral class off one) - // would silently promise semantics the row's plane doesn't deliver - // (Protocol v0.1 §C1.3/C2.1). + // would silently promise semantics the row's plane does not deliver. if !i.StorageClass.IsValid() { return fmt.Errorf("invalid storage class %q (must be %s)", i.StorageClass, ValidStorageClassNames()) } @@ -365,14 +391,11 @@ func (i *Issue) ValidateWithCustom(customStatuses, customTypes []string) error { // since the source repo already validated them when the issue was created. // This implements "trust the chain below you" from the HOP federation model. func (i *Issue) ValidateForImport(customStatuses []string) error { - if len(i.Title) == 0 { - return fmt.Errorf("title is required") + if err := ValidateIssueTitle(i.Title); err != nil { + return err } - if len(i.Title) > 500 { - return fmt.Errorf("title must be 500 characters or less (got %d)", len(i.Title)) - } - if i.Priority < 0 || i.Priority > 4 { - return fmt.Errorf("priority must be between 0 and 4 (got %d)", i.Priority) + if err := ValidateIssuePriority(i.Priority); err != nil { + return err } if !i.Status.IsValidWithCustom(customStatuses) { return fmt.Errorf("invalid status: %s", i.Status) @@ -385,8 +408,8 @@ func (i *Issue) ValidateForImport(customStatuses []string) error { } else if i.IssueType != "" && !i.IssueType.IsValid() { // Non-built-in type - trust it (child repo already validated) } - if i.EstimatedMinutes != nil && *i.EstimatedMinutes < 0 { - return fmt.Errorf("estimated_minutes cannot be negative") + if err := ValidateIssueEstimatedMinutes(i.EstimatedMinutes); err != nil { + return err } // Enforce closed_at invariant if i.Status == StatusClosed && i.ClosedAt == nil { @@ -830,37 +853,116 @@ func ValidWispTypeNames() string { return joinNamesWithOr(validWispTypes) } -// StorageClass declares how a record's history and replication are priced -// (Protocol v0.1 §C, bd-7vb13). The class is a semantic contract, not a table -// or backend (C1.4): ephemeral happens to live in the dolt_ignore'd wisps -// plane today, and unversioned's replication leg is tracked separately -// (bd-1quyq) — the class marker must not imply either mechanism. +// StorageClass is the create-selected marker for a record's history and +// replication contract. Persistence plane transitions preserve the marker +// except for normalization required by demotion or promotion. The effective +// class can change with the plane when the marker is empty. type StorageClass string const ( - // StorageClassVersioned is the default (C1.2): durable, replicated with - // history, mergeable. Serialized as the empty string — the storage_class - // field is omitted when versioned (C2.4), so every pre-v0.1 record is a - // valid versioned record unchanged. + // StorageClassVersioned is the default durable, replicated-with-history + // class. It serializes as the empty storage_class value. StorageClassVersioned StorageClass = "versioned" // StorageClassUnversioned is durable and interchanged with no revision- - // history promise: only current state is retained and replicated (C2.2). + // history promise: only current state is retained and replicated. StorageClassUnversioned StorageClass = "unversioned" // StorageClassEphemeral is operational state that is never exported and - // never replicated (C2.1) — typically TTL-bounded, though not always: + // never replicated — typically TTL-bounded, though not always: // no-history rows are class-ephemeral yet TTL-exempt. The existing // wisp/lease planes have this character. StorageClassEphemeral StorageClass = "ephemeral" ) +// PersistenceMode selects an issue's storage plane and retention behavior. +// Unlike StorageClass, it has no unset value; callers represent omission +// separately from an explicit requested mode. +type PersistenceMode string + +const ( + // PersistenceModePersistent selects persistent storage. Existing + // unversioned records remain unversioned when this mode is selected. + PersistenceModePersistent PersistenceMode = "persistent" + // PersistenceModeEphemeral selects ephemeral storage. + PersistenceModeEphemeral PersistenceMode = "ephemeral" + // PersistenceModeNoHistory selects ephemeral storage without history. + PersistenceModeNoHistory PersistenceMode = "no_history" +) + +var validPersistenceModes = []PersistenceMode{ + PersistenceModePersistent, + PersistenceModeEphemeral, + PersistenceModeNoHistory, +} + +// IsValid reports whether a persistence mode is a known explicit value. +// Empty is invalid because it would be indistinguishable from an omitted mode. +func (m PersistenceMode) IsValid() bool { + return slices.Contains(validPersistenceModes, m) +} + +// NormalizePersistenceMode maps a requested mode from current to its exact +// persistence fields without mutating an issue. The returned values are +// Ephemeral, NoHistory, and StorageClass, respectively. Plane and retention +// changes preserve the create-selected class. Promotion clears an explicit +// ephemeral class marker to select normalized versioned storage. An +// unversioned record may remain persistent but cannot move to a wisp mode. +func NormalizePersistenceMode(current Issue, mode PersistenceMode) (bool, bool, StorageClass, error) { + if !mode.IsValid() { + return false, false, "", fmt.Errorf("invalid persistence mode %q", mode) + } + if current.Ephemeral && current.NoHistory { + return false, false, "", fmt.Errorf("ephemeral and no_history are mutually exclusive") + } + if !current.StorageClass.IsValid() { + return false, false, "", fmt.Errorf("invalid storage class %q", current.StorageClass) + } + wispPlane := current.Ephemeral || current.NoHistory + if wispPlane && current.StorageClass != "" && current.StorageClass != StorageClassEphemeral { + return false, false, "", fmt.Errorf("storage class %q conflicts with ephemeral/no_history", current.StorageClass) + } + if !wispPlane && current.StorageClass == StorageClassEphemeral { + return false, false, "", fmt.Errorf("storage class ephemeral requires ephemeral or no_history") + } + if current.StorageClass == StorageClassUnversioned && mode != PersistenceModePersistent { + return false, false, "", fmt.Errorf("cannot move unversioned record to persistence mode %q", mode) + } + if persistenceMode(current) == mode { + return current.Ephemeral, current.NoHistory, current.StorageClass, nil + } + + switch mode { + case PersistenceModePersistent: + storageClass := current.StorageClass + if storageClass == StorageClassEphemeral { + storageClass = "" + } + return false, false, storageClass, nil + case PersistenceModeEphemeral: + storageClass := current.StorageClass + if storageClass == StorageClassVersioned { + storageClass = "" + } + return true, false, storageClass, nil + case PersistenceModeNoHistory: + storageClass := current.StorageClass + if storageClass == StorageClassVersioned { + storageClass = "" + } + return false, true, storageClass, nil + default: + return false, false, "", fmt.Errorf("invalid persistence mode %q", mode) + } +} + // validStorageClasses is the canonical value list; IsValid, // ParseStorageClass, and ValidStorageClassNames all derive from it. var validStorageClasses = []StorageClass{ StorageClassVersioned, StorageClassUnversioned, StorageClassEphemeral, } -// IsValid reports whether the storage class value is valid. Empty is valid -// and means "unset": the effective class defaults per C1.2/C1.3. +// IsValid reports whether the storage class value is valid. Empty is valid: +// its effective class is ephemeral for Ephemeral or NoHistory rows and +// versioned otherwise. func (s StorageClass) IsValid() bool { if s == "" { return true @@ -885,8 +987,8 @@ func ParseStorageClass(v string) (StorageClass, error) { } // Normalize maps the explicit versioned spelling to unset: the two are -// semantically identical (C1.2) and the marker is omitted when versioned -// (C2.4) — in storage cells and JSONL alike. Both insert stacks call this so +// semantically identical and the marker is omitted when versioned in storage +// cells and serialized records alike. Both insert stacks call this so // the database never persists the literal "versioned". func (s StorageClass) Normalize() StorageClass { if s == StorageClassVersioned { @@ -895,9 +997,9 @@ func (s StorageClass) Normalize() StorageClass { return s } -// EffectiveStorageClass resolves the record's class per C1.2/C1.3: an -// explicit declaration wins; otherwise wisp-plane records (Ephemeral or -// NoHistory) are ephemeral and everything else is versioned. +// EffectiveStorageClass resolves the record's class: an explicit declaration +// wins; otherwise wisp-plane records (Ephemeral or NoHistory) are ephemeral +// and everything else is versioned. func (i *Issue) EffectiveStorageClass() StorageClass { if i.StorageClass != "" { return i.StorageClass @@ -908,6 +1010,16 @@ func (i *Issue) EffectiveStorageClass() StorageClass { return StorageClassVersioned } +func persistenceMode(i Issue) PersistenceMode { + if i.NoHistory { + return PersistenceModeNoHistory + } + if i.Ephemeral { + return PersistenceModeEphemeral + } + return PersistenceModePersistent +} + // joinNamesWithOr formats a value list as "a, b, or c" for error messages. func joinNamesWithOr[T ~string](names []T) string { strs := make([]string, len(names)) diff --git a/issue_lifecycle_external_test.go b/issue_lifecycle_external_test.go new file mode 100644 index 000000000..967613302 --- /dev/null +++ b/issue_lifecycle_external_test.go @@ -0,0 +1,123 @@ +package beads_test + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads" + "github.com/steveyegge/beads/internal/hooks" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/dolt" + "github.com/steveyegge/beads/internal/telemetry" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// TestIssueLifecycleLayersHooksOutsideTelemetry pins the decorator order the +// accessor produces against the order cmd/bd assembles the chain in +// (storage_chain.go: telemetry first, hooks outermost). Each decorator layers +// itself onto the inner result, so the lifecycle comes back stacked the same +// way the store is. +func TestIssueLifecycleLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + lifecycle, err := storage.NewHookFiringStore(instrumented, nil).IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle() error = %v", err) + } + if got := reflect.TypeOf(lifecycle).String(); got != "*storage.hookIssueOperations" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +// TestIssueLifecycleExposesTypedUnsupportedError pins the typed error a backend +// returns when it cannot serve guarded mutations, reachable through the public +// alias without importing internal/storage. +func TestIssueLifecycleExposesTypedUnsupportedError(t *testing.T) { + lifecycle, err := (*dolt.DoltStore)(nil).IssueLifecycle() + if lifecycle != nil { + t.Fatalf("IssueLifecycle() lifecycle = %T, want nil", lifecycle) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("IssueLifecycle() error = %v, want *beads.ErrUnsupported", err) + } +} + +func TestHookDecoratedIssueOperationsCreateFiresReverseDependencyUpdate(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("hook script execution is not supported on Windows") + } + skipIfNoDoltServer(t) + ctx := t.Context() + root := t.TempDir() + store, err := beads.Open(ctx, filepath.Join(root, "store")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil { + t.Fatal(err) + } + source := &types.Issue{ID: "test-hook-source", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, source, "seed"); err != nil { + t.Fatal(err) + } + rawStore, ok := store.(storage.DoltStorage) + if !ok { + t.Fatalf("opened store = %T, want DoltStorage", store) + } + hooksDir := filepath.Join(root, "hooks") + if err := os.Mkdir(hooksDir, 0o755); err != nil { + t.Fatal(err) + } + output := filepath.Join(root, "events") + script := fmt.Sprintf("#!/bin/sh\nprintf '%%s %%s\\n' \"$1\" \"$2\" >> %q\n", output) + for _, name := range []string{hooks.HookOnCreate, hooks.HookOnUpdate} { + if err := os.WriteFile(filepath.Join(hooksDir, name), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + } + operations, err := storage.NewHookFiringStore(rawStore, hooks.NewRunner(hooksDir)).IssueLifecycle() + if err != nil { + t.Fatal(err) + } + result, err := operations.Create(ctx, issueops.CreateRequest{ + Actor: "writer", + ForceIDPrefix: true, + Issue: &types.Issue{Title: "created", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, + Dependencies: []issueops.CreateDependency{{TargetID: source.ID, Type: types.DepRelatesTo, Reverse: true, Metadata: `{"key":"value"}`, ThreadID: "thread"}}, + }) + if err != nil { + t.Fatal(err) + } + if len(result.Issue.Dependencies) != 0 { + t.Fatalf("create result dependencies = %#v, want no outgoing reverse dependency", result.Issue.Dependencies) + } + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + data, _ := os.ReadFile(output) + events := string(data) + if strings.Contains(events, result.Issue.ID+" create") && strings.Contains(events, source.ID+" update") { + return + } + time.Sleep(10 * time.Millisecond) + } + data, err := os.ReadFile(output) + if err != nil { + t.Fatalf("read hook events: %v", err) + } + t.Fatalf("hook events = %q, want create for %s and update for %s", data, result.Issue.ID, source.ID) +} diff --git a/issueops/errors.go b/issueops/errors.go new file mode 100644 index 000000000..f5c5d7db6 --- /dev/null +++ b/issueops/errors.go @@ -0,0 +1,124 @@ +package issueops + +import ( + "errors" + "fmt" +) + +// ErrAlreadyClaimed is returned when attempting to claim an issue that is already +// claimed by another user. The error message contains the current assignee. +var ErrAlreadyClaimed = errors.New("issue already claimed") + +// ErrNotClaimable is returned when attempting to claim an issue that is not in a +// claimable state, such as closed, deferred, or already in progress without the +// same actor owning the claim. +var ErrNotClaimable = errors.New("issue not claimable") + +// ErrAssigneeMismatch is returned by UnclaimIssueIfAssignee when the issue's +// current assignee does not match the expected assignee (including when the +// issue is no longer assigned at all). The caller's view of the claim was +// stale; the issue is left untouched. +var ErrAssigneeMismatch = errors.New("assignee mismatch") + +// ErrNotFound is returned when a requested entity does not exist in the database. +var ErrNotFound = errors.New("not found") + +// ErrValidation classifies deterministic request-validation failures. +var ErrValidation = errors.New("validation failed") + +// ErrNotInitialized is returned when the database has not been initialized +// (e.g., issue_prefix config is missing). +var ErrNotInitialized = errors.New("database not initialized") + +// ErrPrefixMismatch is returned when an issue ID does not match the configured prefix. +var ErrPrefixMismatch = errors.New("prefix mismatch") + +// ErrCloseBlocked is returned by CloseIssueChecked when an issue cannot be +// closed because it is still blocked (is_blocked=1: an open blocking dependency +// or an open blocking gate). Bypass with CloseIssueOptions.Force. +var ErrCloseBlocked = errors.New("cannot close blocked issue") + +// ErrCloseOpenChildren is returned when an unforced close finds open +// parent-child dependents. +var ErrCloseOpenChildren = errors.New("cannot close issue with open children") + +// CloseOpenChildrenError reports the issue and open-child count that refused a +// guarded close. +type CloseOpenChildrenError struct { + IssueID string + OpenChildren int +} + +func (e *CloseOpenChildrenError) Error() string { + return fmt.Sprintf("cannot close %s: %d open child issue(s); close children first or use --force to override", e.IssueID, e.OpenChildren) +} + +// Unwrap makes CloseOpenChildrenError match ErrCloseOpenChildren. +func (e *CloseOpenChildrenError) Unwrap() error { + return ErrCloseOpenChildren +} + +// ErrAlreadyExists is returned when a create operation is given an ID that is +// already occupied. The issue and wisp tables share one ID space. +var ErrAlreadyExists = errors.New("issue already exists") + +// ErrVersionMismatch is returned by a *Checked op given an ExpectedVersion that +// no longer matches the row's current version (row_lock) — an optimistic +// concurrency failure. Callers errors.Is it to distinguish a lost-update +// precondition from other errors. +var ErrVersionMismatch = errors.New("version mismatch") + +// ErrStatusMismatch is returned by UpdateIssueChecked given an ExpectedStatus +// that no longer matches the issue's current status. The caller's view of the +// issue was stale; the issue is left untouched. The assignee analog is +// ErrAssigneeMismatch, shared with UnclaimIssueIfAssignee. +var ErrStatusMismatch = errors.New("status mismatch") + +// ErrSelfDependency is returned when a dependency edge would point an issue at +// itself. It is the static prefix of the formatted message, wrapped so callers +// can errors.Is it while the human-readable text is preserved byte-for-byte. +var ErrSelfDependency = errors.New("cannot add self-dependency") + +// ErrDependencyCycle is returned when adding a dependency edge would introduce a +// scheduling cycle. It is scoped to the dependency-add family — the single and +// bulk add paths (add/addBulk) and the dolt cross-tier check — so callers can +// errors.Is any dependency-add cycle rejection. The whole-graph construction +// paths (ApplyIssueGraph/ApplyWispGraph) are a separate family and deliberately +// do not carry this sentinel yet. +var ErrDependencyCycle = errors.New("adding dependency would create a cycle") + +// DependencyTypeConflictError is returned when an edge already exists between +// the same pair with a DIFFERENT type. Its message is byte-identical to the +// embedded issueops path (internal/storage/issueops/dependencies.go) so +// `bd dep add` surfaces the same user-facing retype error on the domain/db seam +// as on the embedded store. It is a typed error so the use-case can pass it +// through unwrapped instead of burying it under an "add dep: insert:" prefix. +type DependencyTypeConflictError struct { + IssueID string + DependsOnID string + ExistingType string + RequestedType string +} + +func (e *DependencyTypeConflictError) Error() string { + return fmt.Sprintf("dependency %s -> %s already exists with type %q (requested %q); remove it first with 'bd dep remove' then re-add", + e.IssueID, e.DependsOnID, e.ExistingType, e.RequestedType) +} + +// DependencyHierarchyConflictError is returned when a blocking dependency +// would gate an issue on one of its own ancestors or descendants. Either shape +// can never clear under the parent-child close/blocking semantics. +type DependencyHierarchyConflictError struct { + IssueID string + BlockerID string + BlockerIsAncestor bool +} + +func (e *DependencyHierarchyConflictError) Error() string { + if e.BlockerIsAncestor { + return fmt.Sprintf("%s cannot be blocked by its ancestor %s: %s cannot close until its descendants finish, so the gate would never clear", + e.IssueID, e.BlockerID, e.BlockerID) + } + return fmt.Sprintf("%s cannot be blocked by its descendant %s: blocked status cascades to descendants, so %s would inherit the block and never close", + e.IssueID, e.BlockerID, e.BlockerID) +} diff --git a/issueops/issueops.go b/issueops/issueops.go new file mode 100644 index 000000000..7b27a7069 --- /dev/null +++ b/issueops/issueops.go @@ -0,0 +1,328 @@ +// Package issueops declares the public values used for guarded issue mutations. +package issueops + +import ( + "context" + "encoding/json" + "time" + + "github.com/steveyegge/beads/internal/types" +) + +// Issue is the canonical Beads issue model. +type Issue = types.Issue + +// Status is an issue lifecycle status. +type Status = types.Status + +// IssueType classifies an issue. +type IssueType = types.IssueType + +// PersistenceMode selects the complete persistence state for an issue. +type PersistenceMode = types.PersistenceMode + +// Status values accepted by issue operations. +const ( + StatusOpen = types.StatusOpen + StatusInProgress = types.StatusInProgress + StatusBlocked = types.StatusBlocked + StatusDeferred = types.StatusDeferred + StatusClosed = types.StatusClosed + StatusPinned = types.StatusPinned + StatusHooked = types.StatusHooked +) + +// Persistence mode values accepted by issue operations. +const ( + PersistenceModePersistent = types.PersistenceModePersistent + PersistenceModeEphemeral = types.PersistenceModeEphemeral + PersistenceModeNoHistory = types.PersistenceModeNoHistory +) + +// Waits-for gate values accepted by issue operations. +const ( + WaitsForAllChildren = types.WaitsForAllChildren + WaitsForAnyChildren = types.WaitsForAnyChildren +) + +// Field distinguishes an omitted value from an explicitly supplied zero value. +type Field[T any] struct { + // Set reports whether Value was supplied. + Set bool + // Value is the supplied value, including a zero or nil value. + Value T +} + +// LabelPatch describes ordered label replacement and incremental edits. +// Operations apply Replace, then Add, then Remove, so removal wins when the +// same label appears in more than one edit. +type LabelPatch struct { + // Add contains labels to add after any replacement. + Add []string + // Remove contains labels to remove after replacement and addition. + Remove []string + // Replace supplies the starting complete label set when Set is true. + Replace Field[[]string] +} + +// MetadataPatch describes metadata replacement or ordered incremental edits. +// Replace is mutually exclusive with Merge, Set, and Unset. Without Replace, +// operations apply Merge, then Set keys in deterministic order, then Unset, so +// unsetting a key wins over setting or merging that key. +type MetadataPatch struct { + // Replace replaces the complete metadata document when Set is true. A nil or + // empty Value clears metadata; a nonempty Value must be valid JSON. + Replace Field[json.RawMessage] + // Merge merges a metadata document into the current value. A nil or empty + // Value is invalid; a nonempty Value must be a JSON object. + Merge Field[json.RawMessage] + // Set writes individual metadata keys in deterministic key order. + Set map[string]json.RawMessage + // Unset removes individual metadata keys after all other edits. + Unset []string +} + +// IssuePatch describes fields that can change on an issue. +type IssuePatch struct { + Title Field[string] + Description Field[string] + Design Field[string] + AcceptanceCriteria Field[string] + // Notes replaces the notes and is mutually exclusive with AppendNotes. + Notes Field[string] + // AppendNotes appends to the notes and is mutually exclusive with Notes. + AppendNotes Field[string] + SpecID Field[string] + AwaitID Field[string] + // Status sets the issue's status, including across the configured + // done/non-done category boundary. Close and Reopen remain the operations + // that carry the full lifecycle policy. + Status Field[Status] + Priority Field[int] + IssueType Field[IssueType] + Assignee Field[string] + Owner Field[string] + ClosedBySession Field[string] + EstimatedMinutes Field[*int] + ExternalRef Field[*string] + DueAt Field[*time.Time] + DeferUntil Field[*time.Time] + // Persistence selects the complete persistence state. It is unchanged when + // unset; a set value must be a known PersistenceMode. A same current mode is + // a representation-preserving no-op. Every aggregate move is atomic. + // Persistent preserves an existing durable unversioned class; promotion + // from a wisp selects normalized versioned storage. Ephemeral and NoHistory + // select wisp retention modes, never durable unversioned storage. Command + // adapters translate their own flag spelling before constructing this + // request. + Persistence Field[PersistenceMode] + // ParentID is unchanged when unset. A set empty value removes all outgoing + // parent-child edges. A set nonempty value atomically replaces all parents + // with exactly that target and does not inherit labels. + ParentID Field[string] + Labels LabelPatch + Metadata MetadataPatch +} + +// CreateDependency describes a dependency created with an issue. +type CreateDependency struct { + TargetID string + Type types.DependencyType + // Reverse writes the dependency from TargetID to the new issue. + Reverse bool + Metadata string + // ThreadID associates this dependency with a discussion thread. + ThreadID string +} + +// WaitsFor describes the typed metadata for a DepWaitsFor dependency. It +// records a readiness primitive; it does not define scheduling or execution +// policy. +type WaitsFor struct { + // SpawnerID is required and identifies the dependency target whose children + // are observed. + SpawnerID string + // Gate selects the readiness condition. Empty defaults to + // WaitsForAllChildren; otherwise only the exported waits-for gate constants + // are valid. + Gate string +} + +// CreateRequest describes one atomic issue creation. +type CreateRequest struct { + Actor string + // Issue is included in the request's single deep snapshot at method entry; + // every transaction attempt clones that same entry snapshot. Create accepts + // its ID, content, workflow, assignment, timestamps, scheduling, + // external-reference, metadata, wisp, storage-class, marker, gate, source, + // molecule, work-type, and event fields using the canonical create rules. It + // ignores ContentHash, RowVersion, lease state, compaction state, routing + // overrides, hydration flags, and derived fields. Labels are authoritative. + // Issue.Comments and Issue.Dependencies must be empty; supply edges through + // the request's own Dependencies field. + Issue *Issue + // ParentID creates a typed DepParentChild edge. It must not duplicate an + // explicit edge in Dependencies. + ParentID string + // InheritLabelsFromParent copies the parent's labels at creation. + InheritLabelsFromParent bool + // Dependencies is the authoritative set of explicit edges created with the + // issue. Duplicate source-target pairs are rejected. A different type for an + // existing pair is rejected with DependencyTypeConflictError rather than + // silently retyping the edge. + Dependencies []CreateDependency + // WaitsFor creates a typed DepWaitsFor edge. It must not duplicate an + // explicit edge in Dependencies. + WaitsFor *WaitsFor + // ForceIDPrefix permits an explicit ID outside the configured prefix. + ForceIDPrefix bool +} + +// UpdateRequest describes an issue update. +type UpdateRequest struct { + Actor, IssueID string + Patch IssuePatch + // Claim atomically claims the issue for Actor. It first sets Assignee to + // Actor and Status to StatusInProgress, then applies Patch; a set + // Patch.Assignee or Patch.Status overrides the corresponding claim value. + // An issue is eligible when its status is built-in StatusOpen or a configured + // active status and it is unassigned, assigned to Actor, or assigned to a + // configured pool. StatusInProgress assigned to the same Actor is an + // idempotent success. A foreign assignment returns ErrAlreadyClaimed; an + // ineligible status returns ErrNotClaimable. + // ExpectedAssignee and ExpectedStatus must be nil when Claim is true because + // the claim has its own compare-and-set eligibility rules. + Claim bool + // ForceAssigneeTransfer bypasses only a genuine transfer away from a foreign + // live in-progress owner. Reasserting the exact current foreign assignee is + // idempotent and needs no force. Assignees configured as claim.pools aliases + // are transferable without force. The zero value enforces the fence. It has + // no effect with Claim or an omitted Patch.Assignee and must be false with + // ExpectedAssignee. It never bypasses other guards. + ForceAssigneeTransfer bool + // ExpectedVersion requires the current row version to match before the claim + // and patch. It is an independent precondition and may be combined with Claim. + ExpectedVersion *int64 + // ExpectedAssignee requires the current assignee to match. A match authorizes + // the requested Patch.Assignee transfer: this compare-and-set replaces the + // ordinary anti-steal fence. It must be nil with Claim, and + // ForceAssigneeTransfer must be false when it is non-nil. + ExpectedAssignee *string + // ExpectedStatus requires the current status to match. It must be nil when + // Claim is true. + ExpectedStatus *Status +} + +// CloseRequest describes an issue closure. +type CloseRequest struct { + Actor string + IssueID string + Reason string + Session string + // Force bypasses only blocker and open-child close policy. It never bypasses + // validation, ExpectedVersion, or lifecycle rules. + Force bool + // ExpectedVersion requires the current row version to match and is checked + // before an idempotent close. + ExpectedVersion *int64 +} + +// ReopenRequest describes an issue reopening. +type ReopenRequest struct { + Actor string + IssueID string + // Reason records why literal closed and configured done statuses move to + // open. Non-done statuses are unchanged. + Reason string + // ExpectedVersion requires the current row version to match and is checked + // before a non-done no-op. + ExpectedVersion *int64 +} + +// CreateResult reports the created issue as a detached snapshot with labels, +// dependencies, and persisted comments. +type CreateResult struct { + // Issue is a detached snapshot with labels, dependencies, and persisted + // comments. + Issue *Issue +} + +// UpdateResult reports the post-update issue as a detached post-state snapshot +// with labels and dependency records. Comments are omitted. +type UpdateResult struct { + // Issue is a detached post-state snapshot with labels and dependency records. + // Comments are omitted. + Issue *Issue + // Changed reports whether the request persisted a semantic mutation. It is + // false for same-value patches and no-op updates. + Changed bool +} + +// CloseResult reports the post-close issue as a detached post-state snapshot +// with labels and dependency records. Comments are omitted. +type CloseResult struct { + // Issue is a detached post-state snapshot with labels and dependency records. + // Comments are omitted. + Issue *Issue + // Changed reports whether closing persisted a semantic mutation. It is false + // for an idempotent re-close. + Changed bool + // OpenChildren is the number of open children observed by a forced close. + // It is reported even for an idempotent re-close. + OpenChildren int +} + +// ReopenResult reports the post-reopen issue as a detached post-state snapshot +// with labels and dependency records. Comments are omitted. +type ReopenResult struct { + // Issue is a detached post-state snapshot with labels and dependency records. + // Comments are omitted. + Issue *Issue + // Changed reports whether reopening persisted a semantic mutation. It is + // false when non-done statuses are unchanged. + Changed bool +} + +// Lifecycle describes guarded issue mutations. A new capability gets a new +// role interface and its own accessor; never append a method here. +// Deterministic request validation failures match ErrValidation; when a +// more-specific validation sentinel applies, it remains matchable too. +// Implementations never mutate +// caller-owned request values. Callers must not concurrently mutate +// request-owned mutable values until the call returns; snapshotting does not +// make Go data races safe. Implementations snapshot all request inputs once at +// method entry, deep-cloning caller-owned mutable values into that snapshot. +// They deep-clone that snapshot before every transaction attempt, including +// retries, and apply validation, defaulting, and normalization only to +// attempt-local clones. Result values are unspecified when error is non-nil. +// Refusals and deterministic validation failures leave persistent state +// unchanged. Other operational or commit-finalization errors can have an +// indeterminate durable outcome; callers must reread state before retrying. +type Lifecycle interface { + // Create validates and commits the complete request as one atomic mutation. + // It is create-only across issues and wisps: an occupied ID returns + // ErrAlreadyExists and leaves persistent state unchanged. A refusal or + // validation error also leaves no partial persistent state. + Create(context.Context, CreateRequest) (CreateResult, error) + // Update validates guards and commits the complete request as one atomic + // mutation. A refusal or validation error leaves persistent state unchanged. + Update(context.Context, UpdateRequest) (UpdateResult, error) + // Close validates guards and commits the complete request as one atomic + // mutation. It moves the issue to literal StatusClosed, including from a + // configured done status. ExpectedVersion is checked first, including for an + // idempotent close. An unforced close with open children returns + // CloseOpenChildrenError without mutation. Force bypasses blocker and + // open-child policy and reports OpenChildren, including for an idempotent + // re-close. A refusal or validation error leaves persistent state unchanged. + Close(context.Context, CloseRequest) (CloseResult, error) + // Reopen validates guards and commits the complete request as one atomic + // mutation. It moves literal StatusClosed and configured done statuses to + // StatusOpen; non-done statuses unchanged. A refusal or validation error + // leaves persistent state unchanged. + Reopen(context.Context, ReopenRequest) (ReopenResult, error) +} + +// ErrFieldTooLong preserves the canonical model sentinel identity for a value +// that exceeds its field's maximum length. The rest of the operation error +// vocabulary is declared in errors.go. +var ErrFieldTooLong = types.ErrFieldTooLong diff --git a/issueops/issueops_external_test.go b/issueops/issueops_external_test.go new file mode 100644 index 000000000..470447277 --- /dev/null +++ b/issueops/issueops_external_test.go @@ -0,0 +1,229 @@ +package issueops_test + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + + "github.com/steveyegge/beads" + "github.com/steveyegge/beads/issueops" +) + +func TestPublicDeclarationsHaveUsefulZeroValues(t *testing.T) { + var _ issueops.Lifecycle = operationsProbe{} + var create issueops.CreateRequest + var update issueops.UpdateRequest + var closeRequest issueops.CloseRequest + var reopen issueops.ReopenRequest + if create.Issue != nil || update.ExpectedVersion != nil || closeRequest.ExpectedVersion != nil || reopen.ExpectedVersion != nil { + t.Fatal("zero-value request unexpectedly carries a value") + } +} + +func TestFieldDistinguishesOmittedFromExplicitZero(t *testing.T) { + var omitted issueops.Field[int] + explicit := issueops.Field[int]{Set: true, Value: 0} + if omitted.Set || !explicit.Set || explicit.Value != 0 { + t.Fatalf("field semantics lost: %#v %#v", omitted, explicit) + } + + clear := issueops.Field[*string]{Set: true, Value: nil} + if !clear.Set || clear.Value != nil { + t.Fatalf("explicit pointer clear lost: %#v", clear) + } +} + +func TestPatchesRepresentExplicitEmptyReplacements(t *testing.T) { + labels := issueops.LabelPatch{ + Replace: issueops.Field[[]string]{Set: true, Value: []string{}}, + } + if !labels.Replace.Set || labels.Replace.Value == nil || len(labels.Replace.Value) != 0 { + t.Fatalf("explicit empty label replacement lost: %#v", labels.Replace) + } + + metadata := issueops.MetadataPatch{ + Replace: issueops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{}`)}, + } + if !metadata.Replace.Set || string(metadata.Replace.Value) != `{}` { + t.Fatalf("explicit empty metadata replacement lost: %#v", metadata.Replace) + } +} + +func TestPersistencePatchHasOneTypedMode(t *testing.T) { + patchType := reflect.TypeFor[issueops.IssuePatch]() + if _, found := patchType.FieldByName("Ephemeral"); found { + t.Fatal("IssuePatch still exposes independent Ephemeral") + } + if _, found := patchType.FieldByName("NoHistory"); found { + t.Fatal("IssuePatch still exposes independent NoHistory") + } + persistence, found := patchType.FieldByName("Persistence") + if !found { + t.Fatal("IssuePatch.Persistence is missing") + } + if persistence.Type != reflect.TypeFor[issueops.Field[issueops.PersistenceMode]]() { + t.Fatalf("IssuePatch.Persistence type = %v, want Field[PersistenceMode]", persistence.Type) + } +} + +func TestPublicPersistenceModeValues(t *testing.T) { + cases := []struct { + got issueops.PersistenceMode + want string + }{ + {issueops.PersistenceModePersistent, "persistent"}, + {issueops.PersistenceModeEphemeral, "ephemeral"}, + {issueops.PersistenceModeNoHistory, "no_history"}, + } + for _, tc := range cases { + if string(tc.got) != tc.want { + t.Errorf("persistence mode = %q, want %q", tc.got, tc.want) + } + } +} + +func TestClaimRequestSupportsPostClaimPatch(t *testing.T) { + version := int64(7) + request := issueops.UpdateRequest{ + Actor: "worker", + IssueID: "bd-123", + Claim: true, + ExpectedVersion: &version, + Patch: issueops.IssuePatch{ + Status: issueops.Field[issueops.Status]{Set: true, Value: issueops.StatusBlocked}, + Assignee: issueops.Field[string]{Set: true, Value: "dispatcher"}, + }, + } + if !request.Claim || request.Patch.Status.Value != issueops.StatusBlocked || request.Patch.Assignee.Value != "dispatcher" || *request.ExpectedVersion != version { + t.Fatalf("claim request lost its explicit post-claim patch or version guard: %#v", request) + } +} + +func TestForceAssigneeTransferHasSafeZeroValue(t *testing.T) { + var guarded issueops.UpdateRequest + forced := issueops.UpdateRequest{ForceAssigneeTransfer: true} + if guarded.ForceAssigneeTransfer || !forced.ForceAssigneeTransfer { + t.Fatalf("force-assignee-transfer declaration lost bool zero-value semantics: %#v %#v", guarded, forced) + } +} + +func TestPublicConstantsKeepCanonicalValues(t *testing.T) { + statuses := []struct { + got issueops.Status + want beads.Status + }{ + {issueops.StatusOpen, beads.StatusOpen}, + {issueops.StatusInProgress, beads.StatusInProgress}, + {issueops.StatusBlocked, beads.StatusBlocked}, + {issueops.StatusDeferred, beads.StatusDeferred}, + {issueops.StatusClosed, beads.StatusClosed}, + } + for _, check := range statuses { + if check.got != check.want { + t.Fatalf("status constant = %q, want %q", check.got, check.want) + } + } + + for name, got := range map[string]string{ + "pinned": string(issueops.StatusPinned), + "hooked": string(issueops.StatusHooked), + "all-children": issueops.WaitsForAllChildren, + "any-children": issueops.WaitsForAnyChildren, + } { + if got != name { + t.Errorf("public constant = %q, want %q", got, name) + } + } +} + +func TestPublicErrorsKeepCanonicalIdentity(t *testing.T) { + checks := []struct { + name string + got, want error + }{ + {"not found", issueops.ErrNotFound, beads.ErrNotFound}, + {"field too long", issueops.ErrFieldTooLong, beads.ErrFieldTooLong}, + {"already claimed", issueops.ErrAlreadyClaimed, beads.ErrAlreadyClaimed}, + {"not claimable", issueops.ErrNotClaimable, beads.ErrNotClaimable}, + {"close blocked", issueops.ErrCloseBlocked, beads.ErrCloseBlocked}, + {"version mismatch", issueops.ErrVersionMismatch, beads.ErrVersionMismatch}, + {"self dependency", issueops.ErrSelfDependency, beads.ErrSelfDependency}, + {"dependency cycle", issueops.ErrDependencyCycle, beads.ErrDependencyCycle}, + } + for _, check := range checks { + if !errors.Is(check.got, check.want) { + t.Errorf("%s error identity lost: %v", check.name, check.got) + } + } + + for name, err := range map[string]error{ + "validation": issueops.ErrValidation, + "not initialized": issueops.ErrNotInitialized, + "prefix mismatch": issueops.ErrPrefixMismatch, + "assignee mismatch": issueops.ErrAssigneeMismatch, + "status mismatch": issueops.ErrStatusMismatch, + "already exists": issueops.ErrAlreadyExists, + } { + if err == nil { + t.Errorf("%s sentinel is nil", name) + } + } + + classified := errors.Join(issueops.ErrValidation, issueops.ErrPrefixMismatch) + if !errors.Is(classified, issueops.ErrValidation) { + t.Error("deterministic validation failure lost ErrValidation classification") + } + if !errors.Is(classified, issueops.ErrPrefixMismatch) { + t.Error("deterministic validation failure lost its specific classification") + } +} + +func TestOpenChildrenCloseContractShape(t *testing.T) { + err := &issueops.CloseOpenChildrenError{ + IssueID: "bd-parent", + OpenChildren: 3, + } + if !errors.Is(err, issueops.ErrCloseOpenChildren) { + t.Fatalf("CloseOpenChildrenError does not match ErrCloseOpenChildren: %v", err) + } + if got := err.Error(); !strings.Contains(got, "bd-parent") || !strings.Contains(got, "3") { + t.Errorf("CloseOpenChildrenError = %q, want issue and count", got) + } + + result := issueops.CloseResult{OpenChildren: 3} + if result.OpenChildren != 3 { + t.Fatalf("CloseResult.OpenChildren = %d, want 3", result.OpenChildren) + } +} + +func TestPublicDependencyConflictTypesRemainCanonical(t *testing.T) { + var typeConflict error = &issueops.DependencyTypeConflictError{} + var hierarchyConflict error = &issueops.DependencyHierarchyConflictError{} + if typeConflict == nil || hierarchyConflict == nil { + t.Fatal("dependency conflict aliases lost their error implementations") + } + if reflect.TypeFor[*issueops.DependencyTypeConflictError]() != reflect.TypeFor[*beads.DependencyTypeConflictError]() { + t.Error("DependencyTypeConflictError lost canonical type identity") + } + if reflect.TypeFor[*issueops.DependencyHierarchyConflictError]() != reflect.TypeFor[*beads.DependencyHierarchyConflictError]() { + t.Error("DependencyHierarchyConflictError lost canonical type identity") + } +} + +type operationsProbe struct{} + +func (operationsProbe) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { + return issueops.CreateResult{}, nil +} +func (operationsProbe) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) { + return issueops.UpdateResult{}, nil +} +func (operationsProbe) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) { + return issueops.CloseResult{}, nil +} +func (operationsProbe) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { + return issueops.ReopenResult{}, nil +}