fix(delete): honor cascade policy in proxied-server delete (bd-paurh) (#5371)

* fix(delete): honor cascade policy in proxied-server delete (bd-paurh)

Proxied `bd delete` passed Cascade:true unconditionally and refused
--cascade outright, so `bd delete <gate> --force` (wh-gate-sweep's
delivery-ledger purge) destroyed the gated bead and everything
downstream of it. Bring proxied delete to classic (embedded) parity by
implementing the documented-but-unimplemented EnforceCascadePolicy in
domain deleteMany:

- Cascade=true                -> delete all transitive dependents
- Cascade=false, Force=false  -> refuse with *DeleteBlockedError (classic
  message, blocking dependents on result.OrphanedIssues), before any
  mutation
- Cascade=false, Force=true   -> orphan external dependents, delete only
  the named IDs, dep links to/from them cleaned up
- EnforceCascadePolicy=false  -> legacy behavior preserved exactly for
  the wisp/mol/gc/purge proxied paths and single-ID wrappers

CLI: accept --cascade in proxied mode, thread cascade/force through
preview and delete with EnforceCascadePolicy:true, render classic-style
messaging (cascade warning only when requested; refusal says how to
proceed), and add JSON fields (cascade, would_orphan, error,
orphaned_issues) without removing any.

Tests: domain unit tests for all four policy combos; proxied delete
integration reworked to pin refusal/cascade/orphan parity plus a new
force-orphan integration test; output contract tests extended; the
bd-04vav characterization subtest flipped from pinning the divergent
blast radius (targetSurvives=false) to asserting parity
(wantProxied = wantClassic) — the acceptance test of this fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(delete): emit one JSON doc on blocked --json preview (bd-paurh)

Review follow-up from #5371 (lion): the blocked refusal in --json mode
emitted the preview payload (error key included) and then
jsonStdoutError's second doc on top — two JSON documents on stdout.
Return exitError directly when blocked+jsonOutput; integration test pins
the single-doc contract. Also documents the deliberate wisp-as-named-
target divergence from embedded on EnforceCascadePolicy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y9gMLK4xKXja9VbiH3NxV1

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Steve Yegge 2026-08-06 03:15:55 -07:00 • committed by GitHub
commit b5fc63786f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 487 additions and 61 deletions

View file

@ -156,11 +156,11 @@ func runPruneSweep(t *testing.T, r cascadeRunner) pruneSweepOutcome {
}
// TestProxiedServerCascadeParity is the delete/prune/purge half of bd-04vav:
// proxied `bd delete` ALWAYS cascades (--cascade is refused outright), so the
// question the wheelhouse needs answered is not "is there a flag" but "does the
// cascade reach anything classic mode would have left alone" — on the two
// shapes it actually runs: wh-gate-sweep's gate purge, and the wisp-decay
// close+purge pair.
// since bd-paurh, proxied `bd delete` honors the classic cascade policy
// (default refuse, --cascade sweep, --force orphan), so the question the
// wheelhouse needs answered is "does a delete reach anything classic mode
// would have left alone" — on the two shapes it actually runs:
// wh-gate-sweep's gate purge, and the wisp-decay close+purge pair.
//
// Both scenarios are replayed against a classic embedded workspace and a
// proxied one and the outcomes compared, so a divergence is reported as a
@ -170,24 +170,13 @@ func TestProxiedServerCascadeParity(t *testing.T) {
t.Parallel()
bd := buildEmbeddedBD(t)
// KNOWN DIVERGENCE — DATA LOSS. Read this before changing anything below.
//
// Proxied `bd delete <gate> --force` deletes the bead the gate was gating,
// and everything downstream of THAT, because the proxied route passes
// Cascade:true unconditionally while classic cascades only under an explicit
// --cascade (which proxied refuses outright). On wh-gate-sweep's fixture the
// cascade is not a nuance: the sweep's third step is `bd delete <gate>
// --force`, and `bd gate create --blocks <target>` makes the gated bead a
// DEPENDENT of the gate, so on the proxied plane that step destroys the work
// it just unblocked. It is a cutover blocker for the shared-server
// constellation, not a wart.
//
// This subtest CHARACTERIZES the defect rather than asserting the fix: the
// classic half pins the behavior that is correct, and the proxied half pins
// exactly today's damage, so the suite stays honest and green while the
// divergence is open — and fails the moment the blast radius CHANGES, in
// either direction. Whoever fixes proxied delete's cascade flips
// wantProxied to match wantClassic and deletes this paragraph.
// This subtest is the acceptance test for bd-paurh: wh-gate-sweep's third
// step is `bd delete <gate> --force`, and `bd gate create --blocks <target>`
// makes the gated bead a DEPENDENT of the gate. Under the old proxied
// unconditional Cascade:true, that step destroyed the work it had just
// unblocked (plus everything downstream). With embedded parity, --force
// without --cascade orphans dependents: the gate goes, the gated target and
// its sibling stay — identical to classic.
t.Run("gate_delivery_ledger", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "cgp")
@ -203,19 +192,15 @@ func TestProxiedServerCascadeParity(t *testing.T) {
t.Errorf("classic gate delivery-ledger delete: got %#v, want %#v", classic, wantClassic)
}
wantProxied := gateDeliveryLedgerOutcome{
gateGone: true, targetSurvives: false, siblingSurvives: false,
}
wantProxied := wantClassic
if proxied != wantProxied {
t.Errorf("proxied gate delivery-ledger delete: got %#v, want %#v "+
"(the known unconditional-cascade divergence; if this now matches classic, "+
"the defect is fixed — make wantProxied equal wantClassic)", proxied, wantProxied)
"(bd-paurh parity: `delete <gate> --force` must orphan the gated bead, "+
"never cascade into it)", proxied, wantProxied)
}
if proxied != classic {
t.Logf("KNOWN DIVERGENCE (bd-04vav): proxied delete cascades where classic does not.\n"+
" proxied: %#v\n classic: %#v\n"+
" wh-gate-sweep's `bd delete <gate> --force` would destroy the gated bead "+
"and its dependents on the proxied plane.", proxied, classic)
t.Errorf("gate delivery ledger differs across modes:\n proxied: %#v\n classic: %#v",
proxied, classic)
}
})

View file

@ -122,15 +122,20 @@ func TestGatherDeleteInput(t *testing.T) {
}
})
t.Run("rejects cascade without accessing a store", func(t *testing.T) {
t.Run("accepts cascade and projects it (embedded parity, bd-paurh)", func(t *testing.T) {
cmd := newCommand(t)
if err := cmd.Flags().Set("cascade", "true"); err != nil {
t.Fatalf("set cascade: %v", err)
}
jsonOutput, quietFlag = false, false
_, err := gatherDeleteInput(cmd, []string{"bd-target"})
if err == nil || !strings.Contains(err.Error(), "--cascade") {
t.Fatalf("gatherDeleteInput() error = %v, want --cascade rejection", err)
got, err := gatherDeleteInput(cmd, []string{"bd-target"})
if err != nil {
t.Fatalf("gatherDeleteInput() with --cascade: %v", err)
}
want := &deleteInput{ids: []string{"bd-target"}, cascade: true}
if !reflect.DeepEqual(got, want) {
t.Errorf("gatherDeleteInput(): got %#v, want %#v", got, want)
}
})
}

View file

@ -5,6 +5,7 @@ package main
import (
"context"
"encoding/json"
"io"
"reflect"
"strings"
"sync"
@ -30,7 +31,16 @@ func TestProxiedServerDelete(t *testing.T) {
t.Fatalf("read HEAD before preview: %v", err)
}
preview := bdProxiedDeleteJSON(t, bd, p.dir, "--json", target.ID)
// Embedded parity (bd-paurh): with external dependents and neither
// --cascade nor --force, delete refuses and tells the caller how to
// proceed instead of silently cascading.
refusal := bdProxiedDeleteFail(t, bd, p.dir, target.ID)
if !strings.Contains(refusal, "has dependents not in deletion set") ||
!strings.Contains(refusal, "--cascade") || !strings.Contains(refusal, "--force") {
t.Errorf("bare delete with dependents: got %q, want refusal naming --cascade/--force", refusal)
}
preview := bdProxiedDeleteJSON(t, bd, p.dir, "--json", "--cascade", target.ID)
previewWant := map[string]any{
"schema_version": float64(1),
"would_delete": float64(3),
@ -41,6 +51,8 @@ func TestProxiedServerDelete(t *testing.T) {
"not_found": nil,
"connected": []any{survivor.ID},
"dry_run": false,
"cascade": true,
"would_orphan": float64(0),
}
if !deleteJSONEqual(preview, previewWant) {
t.Errorf("preview JSON: got %#v, want %#v", preview, previewWant)
@ -56,7 +68,7 @@ func TestProxiedServerDelete(t *testing.T) {
t.Errorf("preview advanced HEAD: before=%s after=%s", headBefore, headAfterPreview)
}
deleted := bdProxiedDeleteJSON(t, bd, p.dir, "--json", target.ID, "--force")
deleted := bdProxiedDeleteJSON(t, bd, p.dir, "--json", "--cascade", target.ID, "--force")
deletedWant := map[string]any{
"schema_version": float64(1),
"deleted": []any{target.ID},
@ -65,6 +77,7 @@ func TestProxiedServerDelete(t *testing.T) {
"labels_removed": float64(1),
"events_removed": float64(4),
"references_updated": float64(1),
"orphaned_issues": nil,
}
if !deleteJSONEqual(deleted, deletedWant) {
t.Errorf("delete JSON: got %#v, want %#v", deleted, deletedWant)
@ -117,6 +130,89 @@ func deleteJSONEqual(got, want map[string]any) bool {
return reflect.DeepEqual(got, want)
}
// TestProxiedServerDeleteForceOrphans pins the embedded-parity --force
// semantics (bd-paurh): without --cascade, --force deletes ONLY the named IDs,
// orphans external dependents, and cleans up the dependency links touching the
// deleted rows.
func TestProxiedServerDeleteForceOrphans(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := newSharedProxiedProject(t, bd, "delfo")
target := bdProxiedCreate(t, bd, p.dir, "Orphan target", "--type", "task")
dependent := bdProxiedCreate(t, bd, p.dir, "Orphaned dependent", "--type", "task", "--deps", "depends-on:"+target.ID)
descendant := bdProxiedCreate(t, bd, p.dir, "Orphan descendant", "--type", "task", "--parent", dependent.ID)
deleted := bdProxiedDeleteJSON(t, bd, p.dir, "--json", target.ID, "--force")
if got, want := deleted["deleted_count"], float64(1); got != want {
t.Errorf("deleted_count: got %v, want %v (force without cascade must delete only the named ID)", got, want)
}
if got, want := deleted["orphaned_issues"], []any{dependent.ID}; !reflect.DeepEqual(got, want) {
t.Errorf("orphaned_issues: got %#v, want %#v", got, want)
}
db := openProxiedDB(t, p)
ctx := context.Background()
assertRowAbsent(t, db, "issues", target.ID)
assertRowExists(t, db, "issues", dependent.ID)
assertRowExists(t, db, "issues", descendant.ID)
var depRows int
if err := db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ? OR depends_on_issue_id = ?",
target.ID, target.ID).Scan(&depRows); err != nil {
t.Fatalf("count dependency rows touching deleted id: %v", err)
}
if depRows != 0 {
t.Errorf("dependency links touching deleted %s: got %d, want 0 (orphan cleanup)", target.ID, depRows)
}
var survivingDeps int
if err := db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ?", descendant.ID).Scan(&survivingDeps); err != nil {
t.Fatalf("count surviving dependency rows: %v", err)
}
if survivingDeps != 1 {
t.Errorf("descendant->dependent link: got %d rows, want 1 (untouched)", survivingDeps)
}
}
// The blocked refusal in --json mode must put exactly ONE JSON document on
// stdout — the preview payload, carrying the refusal in its "error" key. The
// jsonStdoutError doc used to be emitted on top of it (#5371 review).
func TestProxiedServerDeleteBlockedJSONSingleDoc(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := newSharedProxiedProject(t, bd, "delete-blocked-json")
target := bdProxiedCreate(t, bd, p.dir, "Blocked target", "--type", "task")
bdProxiedCreate(t, bd, p.dir, "External dependent", "--type", "task", "--deps", "depends-on:"+target.ID)
stdout, stderr, err := bdProxiedDeleteRaw(t, bd, p.dir, "--json", target.ID)
if err == nil {
t.Fatalf("blocked --json delete should fail; stdout:\n%s\nstderr:\n%s", stdout, stderr)
}
start := strings.Index(stdout, "{")
if start < 0 {
t.Fatalf("no JSON object in blocked --json output:\n%s", stdout)
}
dec := json.NewDecoder(strings.NewReader(stdout[start:]))
var payload map[string]any
if err := dec.Decode(&payload); err != nil {
t.Fatalf("parse blocked --json payload: %v\nraw: %s", err, stdout[start:])
}
errMsg, _ := payload["error"].(string)
if !strings.Contains(errMsg, "has dependents not in deletion set") {
t.Errorf("blocked --json payload error: got %q, want the dependents refusal", errMsg)
}
var extra any
if decErr := dec.Decode(&extra); decErr != io.EOF {
t.Errorf("blocked --json emitted more than one JSON doc (second decode: err=%v doc=%v)\nraw: %s",
decErr, extra, stdout[start:])
}
}
func TestProxiedServerDeleteWisp(t *testing.T) {
requireSharedProxiedServer(t)
bd := buildEmbeddedBD(t)

View file

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"sort"
"strings"
@ -15,6 +16,7 @@ import (
type deleteInput struct {
ids []string
cascade bool
force bool
dryRun bool
jsonOutput bool
@ -22,10 +24,6 @@ type deleteInput struct {
}
func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error) {
if cmd.Flags().Changed("cascade") {
return nil, fmt.Errorf("--cascade is not supported in proxied-server mode (delete always cascades)")
}
in := &deleteInput{}
in.ids = append(in.ids, args...)
@ -38,6 +36,7 @@ func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error)
}
in.ids = uniqueStrings(in.ids)
in.cascade, _ = cmd.Flags().GetBool("cascade")
in.force, _ = cmd.Flags().GetBool("force")
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.jsonOutput = jsonOutput
@ -76,7 +75,9 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
res, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: in.ids,
Cascade: true,
Cascade: in.cascade,
Force: true, // this path only runs under --force
EnforceCascadePolicy: true,
UpdateTextReferences: true,
}, actor)
if err != nil {
@ -99,6 +100,10 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
type deletePreviewResult struct {
preview domain.DeletePreview
res domain.DeleteIssuesResult
// blocked carries the embedded-parity refusal (external dependents, no
// --cascade / --force) so the preview can render it the way classic does —
// preview first, then the refusal explaining how to proceed.
blocked *domain.DeleteBlockedError
}
func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) error {
@ -114,11 +119,17 @@ func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) error {
}
res, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: in.ids,
Cascade: true,
DryRun: true,
IDs: in.ids,
Cascade: in.cascade,
Force: in.force,
EnforceCascadePolicy: true,
DryRun: true,
}, actor)
if err != nil {
var blocked *domain.DeleteBlockedError
if errors.As(err, &blocked) {
return deletePreviewResult{preview: preview, res: res, blocked: blocked}, nil
}
return deletePreviewResult{}, fmt.Errorf("preview counts: %w", err)
}
@ -128,14 +139,27 @@ func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) error {
return HandleErrorRespectJSON("%v", err)
}
return outputDeleteProxiedPreview(in, result)
if err := outputDeleteProxiedPreview(in, result); err != nil {
return err
}
if result.blocked != nil {
// Classic parity: render the preview, then fail with the refusal
// (which itself says how to proceed). In JSON mode the preview payload
// above already carries the refusal in its "error" key — emitting
// jsonStdoutError too would put two JSON docs on stdout.
if in.jsonOutput {
return &exitError{Code: 1}
}
return HandleErrorRespectJSON("%v", result.blocked)
}
return nil
}
// outputDeleteProxiedPreview is the proxied-server preview output boundary.
// JSON takes precedence over quiet, but neither mode may serialize issue payloads.
func outputDeleteProxiedPreview(in *deleteInput, result deletePreviewResult) error {
if in.jsonOutput {
return outputJSON(map[string]any{
payload := map[string]any{
"would_delete": result.res.DeletedCount,
"dependencies_removed": result.res.DependenciesCount,
"labels_removed": result.res.LabelsCount,
@ -144,16 +168,22 @@ func outputDeleteProxiedPreview(in *deleteInput, result deletePreviewResult) err
"not_found": result.preview.NotFound,
"connected": sortedKeys(result.preview.ConnectedIssues),
"dry_run": in.dryRun,
})
"cascade": in.cascade,
"would_orphan": len(result.res.OrphanedIssues),
}
if result.blocked != nil {
payload["error"] = result.blocked.Error()
}
return outputJSON(payload)
}
if in.quiet {
return nil
}
renderDeletePreview(in, result.preview, result.res)
renderDeletePreview(in, result.preview, result.res, result.blocked)
return nil
}
func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res domain.DeleteIssuesResult) {
func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res domain.DeleteIssuesResult, blocked *domain.DeleteBlockedError) {
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
fmt.Printf("\nIssues to delete (%d):\n", len(in.ids))
for _, id := range in.ids {
@ -163,12 +193,22 @@ func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res doma
}
fmt.Printf(" %s: %s\n", id, title)
}
fmt.Printf("\nCascade is always enabled — dependent issues will be removed.\n")
if in.cascade {
fmt.Printf("\n%s Cascade mode enabled - will also delete all dependent issues\n", ui.RenderWarn("⚠"))
}
if blocked != nil {
fmt.Printf("\n%s\n", ui.RenderFail(blocked.Error()))
return
}
fmt.Printf("\nWould remove:\n")
fmt.Printf(" %d issue(s) total\n", res.DeletedCount)
fmt.Printf(" %d dependency link(s)\n", res.DependenciesCount)
fmt.Printf(" %d label(s)\n", res.LabelsCount)
fmt.Printf(" %d event(s)\n", res.EventsCount)
if len(res.OrphanedIssues) > 0 {
fmt.Printf(" Would orphan %d issue(s): %s\n",
len(res.OrphanedIssues), strings.Join(res.OrphanedIssues, ", "))
}
if len(preview.ConnectedIssues) > 0 {
fmt.Printf("\nConnected issues (text references may be rewritten):\n")
@ -187,8 +227,11 @@ func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res doma
return
}
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
fmt.Printf("To proceed, run: %s\n",
ui.RenderWarn("bd delete "+strings.Join(in.ids, " ")+" --force"))
proceed := "bd delete " + strings.Join(in.ids, " ") + " --force"
if in.cascade {
proceed = "bd delete " + strings.Join(in.ids, " ") + " --cascade --force"
}
fmt.Printf("To proceed, run: %s\n", ui.RenderWarn(proceed))
}
func renderDeleteProxiedResult(in *deleteInput, res domain.DeleteIssuesResult) {
@ -200,6 +243,7 @@ func renderDeleteProxiedResult(in *deleteInput, res domain.DeleteIssuesResult) {
"labels_removed": res.LabelsCount,
"events_removed": res.EventsCount,
"references_updated": res.ReferencesUpdated,
"orphaned_issues": res.OrphanedIssues,
})
return
}
@ -208,6 +252,10 @@ func renderDeleteProxiedResult(in *deleteInput, res domain.DeleteIssuesResult) {
fmt.Printf(" Removed %d label(s)\n", res.LabelsCount)
fmt.Printf(" Removed %d event(s)\n", res.EventsCount)
fmt.Printf(" Updated text references in %d issue(s)\n", res.ReferencesUpdated)
if len(res.OrphanedIssues) > 0 {
fmt.Printf(" %s Orphaned %d issue(s): %s\n",
ui.RenderWarn("⚠"), len(res.OrphanedIssues), strings.Join(res.OrphanedIssues, ", "))
}
}
func sortedKeys[V any](m map[string]V) []string {

View file

@ -101,6 +101,8 @@ func TestOutputDeleteProxiedPreviewExactContracts(t *testing.T) {
"not_found": nil,
"connected": []any{"bd-alpha", "bd-zulu"},
"dry_run": true,
"cascade": false,
"would_orphan": float64(0),
}
if !reflect.DeepEqual(got, want) {
t.Errorf("preview JSON: got %#v, want %#v", got, want)
@ -122,6 +124,50 @@ func TestOutputDeleteProxiedPreviewExactContracts(t *testing.T) {
if strings.Index(out, "bd-alpha: Alpha") > strings.Index(out, "bd-zulu: Zulu") {
t.Errorf("prose connected issue order is not sorted:\n%s", out)
}
if strings.Contains(out, "Cascade") {
t.Errorf("prose preview without --cascade must not mention cascade:\n%s", out)
}
})
t.Run("prose warns about cascade only when cascade was requested and proceed hint carries the flag", func(t *testing.T) {
in := &deleteInput{ids: []string{"bd-target"}, cascade: true}
out := captureStdout(t, func() error { return outputDeleteProxiedPreview(in, result) })
for _, required := range []string{
"Cascade mode enabled - will also delete all dependent issues",
"bd delete bd-target --cascade --force",
} {
if !strings.Contains(out, required) {
t.Errorf("cascade preview missing %q:\n%s", required, out)
}
}
})
t.Run("refusal renders the blocking error instead of counts, JSON carries it as error", func(t *testing.T) {
blockedResult := result
blockedResult.res = domain.DeleteIssuesResult{OrphanedIssues: []string{"bd-dependent"}}
blockedResult.blocked = &domain.DeleteBlockedError{IssueID: "bd-target", Dependents: []string{"bd-dependent"}}
in := &deleteInput{ids: []string{"bd-target"}}
out := captureStdout(t, func() error { return outputDeleteProxiedPreview(in, blockedResult) })
if !strings.Contains(out, "has dependents not in deletion set; use --cascade to delete them or --force to orphan them") {
t.Errorf("refusal prose missing classic message:\n%s", out)
}
if strings.Contains(out, "Would remove:") {
t.Errorf("refusal prose must not render counts:\n%s", out)
}
in = &deleteInput{ids: []string{"bd-target"}, jsonOutput: true}
jsonOut := captureStdout(t, func() error { return outputDeleteProxiedPreview(in, blockedResult) })
var got map[string]any
if err := json.Unmarshal([]byte(jsonOut), &got); err != nil {
t.Fatalf("parse refusal JSON: %v\nraw: %s", err, jsonOut)
}
if errMsg, _ := got["error"].(string); !strings.Contains(errMsg, "has dependents not in deletion set") {
t.Errorf("refusal JSON error field: got %#v", got["error"])
}
if got["would_orphan"] != float64(1) {
t.Errorf("refusal JSON would_orphan: got %#v, want 1", got["would_orphan"])
}
})
}
@ -146,6 +192,7 @@ func TestRenderDeleteProxiedResultExactContracts(t *testing.T) {
"labels_removed": float64(2),
"events_removed": float64(5),
"references_updated": float64(1),
"orphaned_issues": nil,
}
if !reflect.DeepEqual(got, want) {
t.Errorf("final JSON: got %#v, want %#v", got, want)
@ -165,5 +212,34 @@ func TestRenderDeleteProxiedResultExactContracts(t *testing.T) {
t.Errorf("final prose missing %q:\n%s", required, out)
}
}
if strings.Contains(out, "Orphaned") {
t.Errorf("final prose without orphans must not warn about orphans:\n%s", out)
}
})
t.Run("orphaned issues surface in JSON and prose (force without cascade)", func(t *testing.T) {
orphanRes := res
orphanRes.OrphanedIssues = []string{"bd-orphan-a", "bd-orphan-b"}
in := &deleteInput{ids: []string{"bd-target"}, jsonOutput: true}
out := captureStdout(t, func() error {
renderDeleteProxiedResult(in, orphanRes)
return nil
})
var got map[string]any
if err := json.Unmarshal([]byte(out), &got); err != nil {
t.Fatalf("parse orphan JSON: %v\nraw: %s", err, out)
}
if want := []any{"bd-orphan-a", "bd-orphan-b"}; !reflect.DeepEqual(got["orphaned_issues"], want) {
t.Errorf("orphaned_issues: got %#v, want %#v", got["orphaned_issues"], want)
}
prose := captureStdout(t, func() error {
renderDeleteProxiedResult(&deleteInput{}, orphanRes)
return nil
})
if !strings.Contains(prose, "Orphaned 2 issue(s): bd-orphan-a, bd-orphan-b") {
t.Errorf("orphan prose missing warning:\n%s", prose)
}
})
}

View file

@ -22,6 +22,12 @@ func (s *testSuite) TestIssueUseCase_Delete() {
s.Run("MixedIssueAndWispMutatesCorrectTables", s.iucDeleteIssuesMixedIssueAndWispMutatesCorrectTables)
s.Run("UpdateTextReferencesFalseLeavesRefs", s.iucDeleteSkipsRefsWhenFlagOff)
})
s.Run("CascadePolicy", func() {
s.Run("LegacyDefaultIgnoresForceAndFollowsCascadeAlone", s.iucCascadePolicyLegacy)
s.Run("EnforcedCascadeDeletesTransitiveDependents", s.iucCascadePolicyCascade)
s.Run("EnforcedRefusesOnExternalDependents", s.iucCascadePolicyRefuses)
s.Run("EnforcedForceOrphansExternalDependents", s.iucCascadePolicyForceOrphans)
})
s.Run("DeleteWisp", func() {
s.Run("DispatchesToWispsTable", s.iucDeleteWispDispatches)
s.Run("CleansAuxiliaryTablesAndCascadesAcrossDependencyTypes", s.iucDeleteWispCleansAuxiliaryTablesAndCascadesAcrossDependencyTypes)
@ -251,6 +257,117 @@ func (s *testSuite) iucDeleteSkipsRefsWhenFlagOff() {
s.Equal(original, survived.Description, "description must be untouched when flag is off")
}
// seedDependentChain seeds root <- mid <- leaf (mid depends on root, leaf on
// mid) for the cascade-policy combos.
func (s *testSuite) seedDependentChain(root, mid, leaf string) {
for _, id := range []string{root, mid, leaf} {
s.seedOpenIssue(id)
}
s.Require().NoError(s.depRepo().Insert(s.Ctx(),
newDep(mid, root, types.DepBlocks), "tester", domain.DepInsertOpts{}))
s.Require().NoError(s.depRepo().Insert(s.Ctx(),
newDep(leaf, mid, types.DepBlocks), "tester", domain.DepInsertOpts{}))
}
func (s *testSuite) issueRowCount(id string) int {
var rows int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM issues WHERE id = ?", id).Scan(&rows))
return rows
}
// iucCascadePolicyLegacy pins the EnforceCascadePolicy=false path EXACTLY as
// it behaved before bd-paurh: Cascade alone decides expansion and Force is
// ignored — no refusal, no orphan reporting. Other proxied callers (wisp/mol/
// gc/purge) rely on this.
func (s *testSuite) iucCascadePolicyLegacy() {
s.seedDependentChain("bd-iuc-cpl-root", "bd-iuc-cpl-mid", "bd-iuc-cpl-leaf")
res, err := s.issueUseCase().DeleteIssues(s.Ctx(), domain.DeleteIssuesParams{
IDs: []string{"bd-iuc-cpl-root"},
// Cascade=false, Force=false, EnforceCascadePolicy=false
}, "tester")
s.Require().NoError(err, "legacy path must not refuse on external dependents")
s.Equal(1, res.DeletedCount, "legacy non-cascade deletes only the named ID")
s.Empty(res.OrphanedIssues, "legacy path reports no orphans")
s.Equal(0, s.issueRowCount("bd-iuc-cpl-root"))
s.Equal(1, s.issueRowCount("bd-iuc-cpl-mid"), "dependent silently kept (legacy)")
s.Equal(1, s.issueRowCount("bd-iuc-cpl-leaf"))
}
func (s *testSuite) iucCascadePolicyCascade() {
s.seedDependentChain("bd-iuc-cpc-root", "bd-iuc-cpc-mid", "bd-iuc-cpc-leaf")
res, err := s.issueUseCase().DeleteIssues(s.Ctx(), domain.DeleteIssuesParams{
IDs: []string{"bd-iuc-cpc-root"},
Cascade: true,
EnforceCascadePolicy: true,
}, "tester")
s.Require().NoError(err)
s.Equal(3, res.DeletedCount, "cascade sweeps all transitive dependents")
s.Empty(res.OrphanedIssues, "cascade path reports no orphans")
for _, id := range []string{"bd-iuc-cpc-root", "bd-iuc-cpc-mid", "bd-iuc-cpc-leaf"} {
s.Equal(0, s.issueRowCount(id), "%s should be deleted", id)
}
}
func (s *testSuite) iucCascadePolicyRefuses() {
s.seedDependentChain("bd-iuc-cpr-root", "bd-iuc-cpr-mid", "bd-iuc-cpr-leaf")
res, err := s.issueUseCase().DeleteIssues(s.Ctx(), domain.DeleteIssuesParams{
IDs: []string{"bd-iuc-cpr-root"},
EnforceCascadePolicy: true,
}, "tester")
s.Require().Error(err)
var blocked *domain.DeleteBlockedError
s.Require().ErrorAs(err, &blocked, "refusal must be a typed DeleteBlockedError")
s.Equal("bd-iuc-cpr-root", blocked.IssueID)
s.Equal([]string{"bd-iuc-cpr-mid"}, blocked.Dependents, "only the DIRECT external dependent blocks")
s.Contains(err.Error(), "use --cascade to delete them or --force to orphan them",
"refusal must say how to proceed (classic parity)")
s.Equal([]string{"bd-iuc-cpr-mid"}, res.OrphanedIssues,
"blocking dependents are reported on the result alongside the error")
s.Equal(0, res.DeletedCount)
for _, id := range []string{"bd-iuc-cpr-root", "bd-iuc-cpr-mid", "bd-iuc-cpr-leaf"} {
s.Equal(1, s.issueRowCount(id), "%s must survive a refused delete", id)
}
var depRows int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM dependencies WHERE depends_on_issue_id = ?",
"bd-iuc-cpr-root").Scan(&depRows))
s.Equal(1, depRows, "dependency links must survive a refused delete")
}
func (s *testSuite) iucCascadePolicyForceOrphans() {
s.seedDependentChain("bd-iuc-cpf-root", "bd-iuc-cpf-mid", "bd-iuc-cpf-leaf")
res, err := s.issueUseCase().DeleteIssues(s.Ctx(), domain.DeleteIssuesParams{
IDs: []string{"bd-iuc-cpf-root"},
Force: true,
EnforceCascadePolicy: true,
}, "tester")
s.Require().NoError(err)
s.Equal(1, res.DeletedCount, "force without cascade deletes only the named IDs")
s.Equal([]string{"bd-iuc-cpf-mid"}, res.OrphanedIssues,
"the direct external dependent is reported as orphaned")
s.Equal(0, s.issueRowCount("bd-iuc-cpf-root"))
s.Equal(1, s.issueRowCount("bd-iuc-cpf-mid"), "orphaned dependent survives")
s.Equal(1, s.issueRowCount("bd-iuc-cpf-leaf"), "transitive dependent survives")
var depRows int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ? OR depends_on_issue_id = ?",
"bd-iuc-cpf-root", "bd-iuc-cpf-root").Scan(&depRows))
s.Equal(0, depRows, "dependency links to/from the deleted ID are cleaned up")
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND depends_on_issue_id = ?",
"bd-iuc-cpf-leaf", "bd-iuc-cpf-mid").Scan(&depRows))
s.Equal(1, depRows, "links between survivors are untouched")
}
func (s *testSuite) iucDeleteWispDispatches() {
s.seedOpenWisp("bd-iuc-delw-1")
s.seedOpenIssue("bd-iuc-delw-1")

View file

@ -110,13 +110,17 @@ type DeleteIssuesParams struct {
UpdateTextReferences bool
// EnforceCascadePolicy selects embedded-parity dependent handling
// (issueops.DeleteIssuesInTx). When false — the legacy default used by the
// proxied-server delete command, which always cascades — deletion expands to
// all transitive dependents regardless of Cascade/Force. When true,
// Cascade/Force choose the behavior:
// (issueops.DeleteIssuesInTx). When false — the legacy default kept for the
// wisp/mol/gc/purge proxied paths and the single-ID convenience wrappers —
// cascade expansion follows params.Cascade alone and Force is ignored. When
// true, Cascade/Force choose the behavior:
// Cascade=true → delete all transitive dependents
// Cascade=false, Force=false → refuse if any external dependent exists
// (*DeleteBlockedError, naming the blockers)
// Cascade=false, Force=true → orphan external dependents (delete only IDs)
// One deliberate divergence from embedded: a wisp NAMED in IDs counts like
// any other issue here and can trip the refusal, where embedded partitions
// wisps out before the dependent check. Strictly safer; kept on purpose.
EnforceCascadePolicy bool
Force bool
}

View file

@ -4,11 +4,28 @@ import (
"context"
"fmt"
"regexp"
"sort"
"github.com/steveyegge/beads/internal/storage/dberrors"
"github.com/steveyegge/beads/internal/types"
)
// DeleteBlockedError is the refusal returned by deleteMany when
// EnforceCascadePolicy is on, Cascade and Force are both off, and an issue in
// the deletion set has dependents outside it. The message mirrors classic
// (embedded) delete's refusal so both planes speak the same language.
type DeleteBlockedError struct {
// IssueID is the first issue in the requested deletion set (request order)
// found to have external dependents.
IssueID string
// Dependents are that issue's dependents outside the deletion set, sorted.
Dependents []string
}
func (e *DeleteBlockedError) Error() string {
return fmt.Sprintf("issue %s has dependents not in deletion set; use --cascade to delete them or --force to orphan them", e.IssueID)
}
func (u *issueUseCaseImpl) DeleteIssue(ctx context.Context, id, actor string) (DeleteIssuesResult, error) {
if id == "" {
return DeleteIssuesResult{}, fmt.Errorf("DeleteIssue: id must not be empty")
@ -52,13 +69,41 @@ func (u *issueUseCaseImpl) deleteMany(ctx context.Context, params DeleteIssuesPa
return DeleteIssuesResult{}, nil
}
result := DeleteIssuesResult{}
allIDs := params.IDs
if params.Cascade {
switch {
case params.Cascade:
expanded, err := u.issueRepo.FindAllDependents(ctx, params.IDs)
if err != nil {
return DeleteIssuesResult{}, fmt.Errorf("delete: cascade expansion: %w", err)
}
allIDs = expanded
case params.EnforceCascadePolicy:
// Embedded-parity dependent handling (see DeleteIssuesParams): without
// Cascade, an external dependent either blocks the delete (no Force) or
// is orphaned (Force), never silently swept.
externalBySource, err := u.externalDependents(ctx, params.IDs)
if err != nil {
return DeleteIssuesResult{}, err
}
if params.Force {
orphanSet := map[string]bool{}
for _, deps := range externalBySource {
for _, dep := range deps {
orphanSet[dep] = true
}
}
result.OrphanedIssues = sortedStringSet(orphanSet)
} else {
for _, id := range params.IDs {
if deps := externalBySource[id]; len(deps) > 0 {
sort.Strings(deps)
result.OrphanedIssues = deps
return result, &DeleteBlockedError{IssueID: id, Dependents: deps}
}
}
}
}
if len(allIDs) == 0 {
return DeleteIssuesResult{}, nil
@ -69,8 +114,6 @@ func (u *issueUseCaseImpl) deleteMany(ctx context.Context, params DeleteIssuesPa
return DeleteIssuesResult{}, fmt.Errorf("delete: partition: %w", err)
}
result := DeleteIssuesResult{}
depIssue, err := u.depRepo.CountAllForIDs(ctx, regularIDs, DepCountsOpts{})
if err != nil {
return DeleteIssuesResult{}, fmt.Errorf("delete: count deps: %w", err)
@ -168,6 +211,58 @@ func (u *issueUseCaseImpl) deleteMany(ctx context.Context, params DeleteIssuesPa
return result, nil
}
// externalDependents finds the direct dependents of each id in ids that are
// not themselves in ids, across both the issue and wisp dependency tables.
// The result maps deletion-set id -> external dependent ids (unsorted).
func (u *issueUseCaseImpl) externalDependents(ctx context.Context, ids []string) (map[string][]string, error) {
idSet := make(map[string]bool, len(ids))
for _, id := range ids {
idSet[id] = true
}
issueRes, err := u.depRepo.ListByIssueIDs(ctx, ids, DepListOpts{Direction: DepDirectionIn})
if err != nil {
return nil, fmt.Errorf("delete: list dependents: %w", err)
}
wispRes, err := u.depRepo.ListByIssueIDs(ctx, ids, DepListOpts{Direction: DepDirectionIn, UseWispsTable: true})
if err != nil && !dberrors.IsTableNotExist(err) {
return nil, fmt.Errorf("delete: list wisp dependents: %w", err)
}
out := map[string][]string{}
seen := map[string]map[string]bool{}
for _, res := range []DepBulkResult{issueRes, wispRes} {
for target, deps := range res.Incoming {
for _, d := range deps {
if d.IssueID == "" || idSet[d.IssueID] {
continue
}
if seen[target] == nil {
seen[target] = map[string]bool{}
}
if seen[target][d.IssueID] {
continue
}
seen[target][d.IssueID] = true
out[target] = append(out[target], d.IssueID)
}
}
}
return out, nil
}
func sortedStringSet(set map[string]bool) []string {
if len(set) == 0 {
return nil
}
out := make([]string, 0, len(set))
for id := range set {
out = append(out, id)
}
sort.Strings(out)
return out
}
func (u *issueUseCaseImpl) previewDelete(ctx context.Context, ids []string) (DeletePreview, error) {
preview := DeletePreview{
Issues: map[string]*types.Issue{},