beads/cmd/bd/wisp_proxied_server.go
gascity-eddie[bot] b17005ad14
fix(wisp gc): apply the --age test to cascade children (follow-up to #5219) (#7599)
* fix(wisp gc): apply the --age test to cascade children

`bd mol wisp gc --age` promised, in its own help text, that a wisp counts as
abandoned when it "has not been updated within --age AND is not closed".
Parents were held to that contract; children reached through the cascade were
not. A child was deleted purely because something it transitively depended on
was old, so `--age` meant nothing for children at all.

Raising the threshold is not a workaround: with `--age 720h`, a step created a
moment ago is still destroyed when its parent is older than 720 hours.

Observed blast radius: a molecule slung seconds earlier went down with all nine
of its steps — 43 beads in a single run — and the agent's hook emptied
instantly. Two rigs of three were hit; the third survived only because a stop
order reached it first.

Steps already picked up have been covered by `isProtectedWisp` since #4430, but
a freshly created step is still `open`, and `open` maps to CategoryActive, which
that guard deliberately does not protect. This closes the remaining path.

Tests: cascade deletion of a stale parent no longer takes a fresh child, and
raising --age does not save one either.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(wisp gc): stop re-cascading at delete time; pin the age contract in the proxied test

The integration test update Steve asked for surfaced that the selection fix
alone was incomplete: findAbandonedWisps now respects --age for cascade
children, but both delete paths re-derived the cascade at delete time and
swept fresh children past that filter anyway:

- embedded path: deleteBatch was called with cascade=true
- proxied-server path: DeleteIssuesParams{Cascade: true} re-expanded via
  FindAllDependents in the domain layer

Both now delete exactly the set findAbandonedWisps selected — the selection
is the single place the --age contract lives.

Test cascade_sweeps_dependent_step_wisps is reshaped per review into
cascade_respects_age_for_dependent_step_wisps: a second child backdated past
the threshold IS swept (cascade still collects genuinely abandoned children),
the fresh child is absent from deleted AND still present in the wisps table
(the table-level check is what caught the delete-time re-cascade).

Verified against the shared dolt container (BEADS_TEST_PROXIED_SERVER=1):
TestProxiedServerWispGC all four subtests pass; TestWispGC* unit tests pass.

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

* fix(wisp gc): age cascade children with wispIsAbandoned

Adopting #5219 onto main, which landed two changes after this PR was
written:

- #7246 (fixes #7236) moved the parents' age check onto
  wispIsAbandoned, so --age 0s still collects a wisp whose DATETIME(0)
  updated_at rounded up to half a second into the future. The PR's child
  check kept the raw now.Sub(updated_at) <= threshold skip, which
  re-opens #7236 for cascade children: under --age 0s a step closed in
  the same second as the gc was left behind, orphaned, while its
  abandoned parent was deleted. Children now take the parents'
  predicate, so "the same --age contract as parents" holds; positive
  thresholds behave exactly as before.
  TestWispGCCascadeChildAgesAtStoragePrecision pins it at storage
  precision and fails on the raw comparison.
- #5735 had already turned the delete-time cascade off on both gc
  routes (GH#4394), so the PR's second commit now carries only its
  proxied-test reshape. Main's delete-site comments gain that commit's
  reason alongside GH#4394: a cascade there would also sweep fresh
  children past the --age filter.

Also lists the PR's new wisp_gc_cascade_age_test.go in cmd/bd/BUILD.bazel,
which gazelle requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: mayor <6847071@gmail.com>
Co-authored-by: AB <6847071@gmail.com>

* docs(wisp gc): document the cascade's age policy; test it with a closed child

Review fixes for #5219, apply-fixes iteration 1.

- The 'bd mol wisp gc' help and the CHANGELOG now say what happens to
  the dependents of an abandoned wisp. They are deleted with it only if
  they meet --age themselves and are not live work, closed ones included
  even without --all. A dependent that is too young is spared, and both
  delete routes drop its edge to the deleted wisp, so an open one is
  collected once it ages out and a closed one is left for --all,
  --closed or bd purge: without --all the parent scan skips closed
  wisps.
- A comment by the child loop in findAbandonedWisps says dependents are
  exempt from the parent scan's not-closed clause, so a change that
  aligns the two loops does not quietly leave an abandoned molecule's
  finished steps behind.
- TestWispGCCascadeRespectsAge and the proxied subtest
  cascade_respects_age_for_dependent_step_wisps close their stale child.
  An open one was collected by the parent scan, so both passed with the
  cascade disabled. With the child closed, a mutant that skips every
  cascade child fails both.

docs/CLI_REFERENCE.md and docs/cli-reference/ are not regenerated: they
are built from the v1.2.2 pin in docs/cli-docs.pin.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: mayor <6847071@gmail.com>
Co-authored-by: AB <6847071@gmail.com>

---------

Co-authored-by: mayor <6847071@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-16 09:49:28 +00:00

335 lines
10 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/steveyegge/beads/internal/formula"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
)
func runWispCreateProxiedServer(ctx context.Context, in wispCreateInput) error {
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
// Explicit commit point, like the `transact` in cloneSubgraph the direct
// route reaches through spawnMoleculeWithOptions (GH#4995). The wisp tables
// are dolt_ignored, so the commit this preserves is whatever tracked rows
// the spawn touches — the class membership is what matters here, not the
// size of the commit.
ctx = explicitCommitPointContext(ctx)
vars, err := parseVarFlags(in.varFlags)
if err != nil {
return HandleError("%v", err)
}
var formulaSubgraph *TemplateSubgraph
var formulaProtoID string
if sg, err := resolveAndCookFormulaWithVars(in.protoArg, nil, vars); err == nil {
formulaSubgraph = sg
formulaProtoID = sg.Root.ID
} else if errors.Is(err, formula.ErrVarValidation) || errors.Is(err, formula.ErrValidation) {
// in.protoArg IS a formula; either the formula itself does not
// validate, or the --var values it was given fail enum/pattern/
// required-empty constraints. Report that directly
// instead of falling through to the proto-ID lookup below, which
// would otherwise mask this as "not found as formula or proto".
return HandleError("%v", err)
}
if formulaSubgraph == nil {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
protoID, err := utils.ResolvePartialID(ctx, r, in.protoArg)
if err != nil {
uw.Close(ctx)
return HandleErrorWithHint(fmt.Sprintf("'%s' not found as formula or proto", in.protoArg), "run 'bd formula list' to see available formulas")
}
protoIssue, err := r.GetIssue(ctx, protoID)
if err != nil {
uw.Close(ctx)
return HandleError("loading proto %s: %v", protoID, err)
}
if !isProtoIssue(protoIssue) {
uw.Close(ctx)
return HandleError("%s is not a proto (missing '%s' label)", protoID, MoleculeLabel)
}
sg, err := loadTemplateSubgraph(ctx, r, protoID)
uw.Close(ctx)
if err != nil {
return HandleError("loading proto: %v", err)
}
formulaSubgraph = sg
formulaProtoID = protoID
}
subgraph := formulaSubgraph
protoID := formulaProtoID
vars = applyVariableDefaults(vars, subgraph)
if err := checkRequiredVars(subgraph, vars); err != nil {
return handleVarErrorWithHint(err, firstMissingVar(subgraph, vars))
}
if in.dryRun {
renderWispCreateDryRun(protoID, subgraph, vars, in.rootOnly)
return nil
}
result, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*InstantiateResult, string, error) {
w := newUOWMolWriter(uw)
spawnResult, err := cloneSubgraphInto(ctx, w, subgraph, CloneOptions{
Vars: vars,
Actor: currentActor(),
Ephemeral: true,
Prefix: types.IDPrefixWisp,
RootOnly: in.rootOnly,
})
if err != nil {
return nil, "", fmt.Errorf("creating wisp: %w", err)
}
return spawnResult, fmt.Sprintf("bd: wisp create %s", protoID), nil
})
if err != nil {
return HandleError("%v", err)
}
return renderWispCreateResult(result)
}
func runWispListProxiedServer(ctx context.Context, showAll bool, typeFilter string) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
issues, err := r.SearchIssues(ctx, "", wispListFilter(typeFilter))
if err != nil {
return HandleError("listing wisps: %v", err)
}
return renderWispListResult(buildWispListResult(issues, showAll))
}
func runWispGCProxiedServer(ctx context.Context, dryRun bool, ageThreshold time.Duration, cleanAll, closedMode, force bool, excludeTypes []types.IssueType) error {
CheckReadonly("wisp gc")
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
if closedMode {
return runWispPurgeClosedProxiedServer(ctx, dryRun, force, excludeTypes)
}
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
abandoned, err := findAbandonedWisps(ctx, r, cleanAll, ageThreshold, excludeTypes)
uw.Close(ctx)
if err != nil && abandoned == nil {
return HandleError("%v", err)
}
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: cascade expansion incomplete: %v\n", err)
}
if len(abandoned) == 0 {
if jsonOutput {
return outputJSON(WispGCResult{CleanedIDs: []string{}, CleanedCount: 0, DryRun: dryRun})
}
fmt.Println("No abandoned wisps found")
return nil
}
if dryRun {
if jsonOutput {
ids := make([]string, len(abandoned))
for i, o := range abandoned {
ids[i] = o.ID
}
return outputJSON(WispGCResult{CleanedIDs: ids, Candidates: len(abandoned), CleanedCount: 0, DryRun: true})
}
fmt.Printf("Dry run: would clean %d abandoned wisp(s):\n\n", len(abandoned))
for _, issue := range abandoned {
age := formatTimeAgo(issue.UpdatedAt)
fmt.Printf(" %s: %s (last updated: %s)\n", issue.ID, issue.Title, age)
}
fmt.Printf("\nRun without --dry-run to delete these wisps.\n")
return nil
}
ids := make([]string, len(abandoned))
for i, issue := range abandoned {
ids[i] = issue.ID
}
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
// Cascade must stay OFF: findAbandonedWisps already expanded dependents
// and kept only unprotected ones that meet --age; a cascade here
// re-expands to ALL transitive dependents, bypassing that protection
// (GH#4394) and sweeping fresh children past the --age filter.
// Mirrors runWispGC in wisp.go.
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: ids,
Cascade: false,
UpdateTextReferences: true,
}, currentActor())
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}
return res, fmt.Sprintf("bd: wisp gc %d", res.DeletedCount), nil
})
if err != nil {
return HandleError("%v", err)
}
return renderWispGCDeleteResult(ids, res)
}
func renderWispGCDeleteResult(ids []string, res domain.DeleteIssuesResult) error {
if jsonOutput {
return outputJSON(map[string]interface{}{
"deleted": ids,
"deleted_count": res.DeletedCount,
"dependencies_removed": res.DependenciesCount,
"labels_removed": res.LabelsCount,
"events_removed": res.EventsCount,
"references_updated": res.ReferencesUpdated,
"orphaned_issues": res.OrphanedIssues,
})
}
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), res.DeletedCount)
fmt.Printf(" Removed %d dependency link(s)\n", res.DependenciesCount)
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, ", "))
}
return nil
}
func runWispPurgeClosedProxiedServer(ctx context.Context, dryRun, force bool, excludeTypes []types.IssueType) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
statusClosed := types.StatusClosed
ephemeralTrue := true
filter := types.IssueFilter{
Status: &statusClosed,
Ephemeral: &ephemeralTrue,
ExcludeTypes: excludeTypes,
Limit: 5000,
}
closedIssues, err := r.SearchIssues(ctx, "", filter)
if err != nil {
uw.Close(ctx)
return HandleError("listing closed wisps: %v", err)
}
pinnedCount := 0
infraCount := 0
filtered := make([]*types.Issue, 0, len(closedIssues))
for _, issue := range closedIssues {
if issue.Pinned {
pinnedCount++
continue
}
if r.IsInfraTypeCtx(ctx, issue.IssueType) {
infraCount++
continue
}
filtered = append(filtered, issue)
}
closedIssues = filtered
uw.Close(ctx)
if pinnedCount > 0 && !jsonOutput {
fmt.Printf("Skipping %d pinned issue(s) (protected from cleanup)\n", pinnedCount)
}
if infraCount > 0 && !jsonOutput {
fmt.Printf("Skipping %d configured infra issue(s) protected from GC\n", infraCount)
}
if len(closedIssues) == 0 {
if jsonOutput {
return outputJSON(map[string]interface{}{
"deleted_count": 0,
"message": "No closed wisps to delete",
})
}
fmt.Println("No closed wisps to delete")
return nil
}
ids := make([]string, len(closedIssues))
for i, issue := range closedIssues {
ids[i] = issue.ID
}
if !force && !dryRun {
if jsonOutput {
return outputJSON(map[string]interface{}{
"candidates": len(ids),
"dry_run": true,
})
}
fmt.Printf("Found %d closed wisp(s) to delete\n", len(ids))
fmt.Printf("\nUse --force to proceed, or --dry-run for detailed preview.\n")
return nil
}
if dryRun {
if jsonOutput {
return outputJSON(map[string]interface{}{
"candidates": len(ids),
"dry_run": true,
})
}
fmt.Printf("Found %d closed wisp(s)\n", len(ids))
fmt.Println("DRY RUN - no changes will be made")
return nil
}
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
// Cascade must stay OFF: the closed set above is already the complete
// purge candidate list, so cascade can only add NON-closed dependents
// (live molecule steps) to the batch — the patrol self-destruct bug.
// Mirrors runWispPurgeClosed in wisp.go.
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: ids,
Cascade: false,
UpdateTextReferences: true,
}, currentActor())
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}
return res, fmt.Sprintf("bd: wisp gc --closed %d", res.DeletedCount), nil
})
if err != nil {
return HandleError("%v", err)
}
return renderWispGCDeleteResult(ids, res)
}