beads/cmd/bd/mol_burn.go
Julian Knutsen 5126de8c1a
perf(bd): no git subprocesses on read-only commands (in-process repo discovery, lazy actor, backup probe) (#7400)
* perf(git): locate the repository in-process instead of running git rev-parse

Every bd invocation resolved the process-wide git context (beads directory
discovery reads it) with `git rev-parse --git-dir --git-common-dir
--show-toplevel`: one git subprocess per bd call before any work. Tools that
call bd hundreds of times (gascity's doctor issues ~250 bd calls per run)
paid it on every call.

On Linux, initGitContext now first runs discoverGitInProcess, which mirrors
Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir
check, filesystem-boundary stop) and produces byte-for-byte what rev-parse
prints for ordinary repositories (top and subdirectories), linked worktrees
(absolute or relative gitfile, symlinked targets), submodules (core.worktree
pointing back at the gitfile's directory), nested repositories and no
repository. Both answers feed one shared normalization
(gitContextFromRevParse), so downstream values are unchanged.

It declines, and git runs exactly as before, whenever it cannot prove the
answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES /
GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS
/ GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile
or git directory, a cwd inside a git directory; repository config with
core.worktree (other than the submodule shape), core.bare, extensions,
include directives, a format version above 1 or unmodeled syntax; any path
not owned by the effective uid (safe.directory is git's to evaluate), or
root under sudo. darwin and windows keep the subprocess (case folding and
ownership semantics).

Tests compare discoverGitFrom with real `git rev-parse` output across those
layouts, pin every decline case, and check the resulting cached context
equals the subprocess-derived one.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(cli): resolve the git user.name actor fallback only when needed

PersistentPreRunE assigned `actor = getActorWithGit()` for every command,
which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs
`git config user.name`: the second git subprocess of every bd call, paid
by read-only commands that never consult the actor.

The pre-run now calls deferActorGitFallback, which marks an empty actor as
pending; currentActor (and getActorWithGit, getActor) resolve it on first
use with the unchanged priority order and store it in the global and the
CommandContext copy, as the eager assignment did. Command code reads the
actor through currentActor() instead of the raw global (a mechanical
rewrite of every read site the compiler reported; writes, the flag binding
and the pre-run config binding keep the raw variable). setActor cancels a
pending fallback. The telemetry span's bd.actor attribute is still set, but
only for a recording span, so a noop span does not force the lookup.

With the in-process repository discovery from the previous commit, a
read-only `bd list` / `bd show` now starts no git process at startup, in
the main checkout and in a linked worktree; a write asks git for user.name
once (bd create previously asked once, now still once) and records the same
value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs
(embedded and proxied-server workspaces, main checkout and worktree).

TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim;
TestDeferredActorGitFallback pins the deferral semantics.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(git): decline in-process discovery on any config line git might read differently

Review follow-ups to the in-process repository discovery.

- The repository config scanner was looser than git: a config starting with
  a UTF-8 BOM followed by `[core] worktree = /other` made git report /other
  while discovery returned the cwd repository, and `[ core ]` or `!!! = x`
  (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now
  skips a leading BOM exactly as git does and accepts only a narrow grammar:
  blank/comment lines, `[section]` / `[section "sub"]` headers at column 0,
  and `key` / `key = value` lines inside a section, with values free of
  backslashes and unbalanced quotes. Any other line declines to git.
- Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd,
  which trusts $PWD when it names the same inode (bind-mount aliases).
- Resolve relative gitfile and commondir targets without filepath.Join's
  lexical Clean, so "link/.." resolves physically like git's realpath.
- A mount-boundary stop reports its own reason in the not-a-repository
  error.
- Tests: every decline case (BOM + core.worktree, malformed headers and
  keys, keys before a section, escapes, continuations, bare repositories,
  a commondir inside .git, ...) now also checks that what startup derives
  equals git's answer; BOM and CRLF/comment configs are equivalence cases;
  the no-repository case must be answered in-process instead of skipping;
  a $PWD alias test pins the getcwd walk.
- The exec-count test drops every GIT_* variable except the config-file
  selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make
  it fail spuriously.
- Comment the two places that touch the raw actor before the deferral.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(backup): decide embedded auto-backup's git-remote probe without git

In an embedded workspace whose backup.enabled is unset, maybeAutoBackup
asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads
included. That built a RepoContext (`git -C .beads rev-parse
--git-common-dir`) and ran `git remote`: two git processes per read even
after the startup calls were gone. The throttle cannot short-circuit it:
without a remote no backup ever runs, so there is no backup state to
throttle on.

Both probes are now answered in-process when provable, and the subprocess
remains the fallback, so the decision and every warning/notice downstream
of it are unchanged:

- internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the
  discovery walk from the given directory, git's spelling).
- primeHasGitRemote uses git.HasRemoteInProcess in the same directory
  primeGitCmd would run git in (primeGitDir, factored out). It answers only
  when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or
  /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global
  (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own --
  is absent or within scanGitConfig's grammar and include-free, no
  GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and
  no legacy .git/remotes or .git/branches entries exist. A remote seen only
  in a system-config candidate declines. Remote names outside
  [A-Za-z0-9._-] decline.

Tests compare HasRemoteInProcess with `git remote` (no remote, local,
worktree, submodule, remote.pushDefault only, global remote, no repo) and
pin the declines (global include, malformed global, command-line config);
CommonDirInProcess is compared with `git -C dir rev-parse
--git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with
backup.enabled at its default, with and without a git remote, and still
expects zero git processes for list/show.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 20:08:24 +00:00

414 lines
12 KiB
Go

package main
import (
"context"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
)
var molBurnCmd = &cobra.Command{
Use: "burn <molecule-id> [molecule-id...]",
Short: "Delete a molecule without creating a digest",
Long: `Burn a molecule, deleting it without creating a digest.
Unlike squash (which creates a permanent digest before deletion), burn
completely removes the molecule with no trace. Use this for:
- Abandoned patrol cycles
- Crashed or failed workflows
- Test/debug molecules you don't want to preserve
The burn operation differs based on molecule phase:
- Wisp (ephemeral): Direct delete
- Mol (persistent): Cascade delete (syncs to remotes)
CAUTION: This is a destructive operation. The molecule's data will be
permanently lost. If you want to preserve a summary, use 'bd mol squash'.
Example:
bd mol burn bd-abc123 # Delete molecule with no trace
bd mol burn bd-abc123 --dry-run # Preview what would be deleted
bd mol burn bd-abc123 --force # Skip confirmation
bd mol burn bd-a1 bd-b2 bd-c3 # Batch delete multiple wisps`,
Args: cobra.MinimumNArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: runMolBurn,
}
// BurnResult holds the result of a burn operation
type BurnResult struct {
MoleculeID string `json:"molecule_id"`
DeletedIDs []string `json:"deleted_ids"`
DeletedCount int `json:"deleted_count"`
}
// BatchBurnResult holds aggregated results when burning multiple molecules
type BatchBurnResult struct {
Results []BurnResult `json:"results"`
TotalDeleted int `json:"total_deleted"`
FailedCount int `json:"failed_count"`
}
func runMolBurn(cmd *cobra.Command, args []string) error {
CheckReadonly("mol burn")
evt := metrics.NewCommandEvent("mol-burn")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
dryRun, _ := cmd.Flags().GetBool("dry-run")
force, _ := cmd.Flags().GetBool("force")
if yes, _ := cmd.Flags().GetBool("yes"); yes {
force = true
}
if usesProxiedServer() {
return runMolBurnProxiedServer(rootCtx, args, dryRun, force)
}
ctx := rootCtx
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
if len(args) == 1 {
return burnSingleMolecule(ctx, args[0], dryRun, force)
}
return burnMultipleMolecules(ctx, args, dryRun, force)
}
func burnSingleMolecule(ctx context.Context, moleculeID string, dryRun, force bool) error {
resolvedID, err := utils.ResolvePartialID(ctx, store, moleculeID)
if err != nil {
return HandleErrorRespectJSON("resolving molecule ID %s: %v", moleculeID, err)
}
rootIssue, err := store.GetIssue(ctx, resolvedID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
if rootIssue.Ephemeral {
return burnWispMolecule(ctx, resolvedID, dryRun, force)
}
return burnPersistentMolecule(ctx, resolvedID, dryRun, force)
}
func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, force bool) error {
var wispIDs []string
var persistentIDs []string
var failedResolve []string
// First pass: resolve and categorize all IDs
for _, moleculeID := range moleculeIDs {
resolvedID, err := utils.ResolvePartialID(ctx, store, moleculeID)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to resolve %s: %v\n", moleculeID, err)
}
failedResolve = append(failedResolve, moleculeID)
continue
}
issue, err := store.GetIssue(ctx, resolvedID)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to load %s: %v\n", resolvedID, err)
}
failedResolve = append(failedResolve, moleculeID)
continue
}
if issue.Ephemeral {
wispIDs = append(wispIDs, resolvedID)
} else {
persistentIDs = append(persistentIDs, resolvedID)
}
}
if len(wispIDs) == 0 && len(persistentIDs) == 0 {
if jsonOutput {
return outputJSON(BatchBurnResult{FailedCount: len(failedResolve)})
}
fmt.Println("No valid molecules to burn")
return nil
}
if dryRun {
if !jsonOutput {
fmt.Printf("\nDry run: would burn %d wisp(s) and %d persistent molecule(s)\n", len(wispIDs), len(persistentIDs))
if len(wispIDs) > 0 {
fmt.Printf("\nWisps to delete:\n")
for _, id := range wispIDs {
fmt.Printf(" - %s\n", id)
}
}
if len(persistentIDs) > 0 {
fmt.Printf("\nPersistent molecules to delete:\n")
for _, id := range persistentIDs {
fmt.Printf(" - %s\n", id)
}
}
if len(failedResolve) > 0 {
fmt.Printf("\nFailed to resolve (%d):\n", len(failedResolve))
for _, id := range failedResolve {
fmt.Printf(" - %s\n", id)
}
}
}
return nil
}
if !force && !jsonOutput {
fmt.Printf("About to burn %d wisp(s) and %d persistent molecule(s)\n", len(wispIDs), len(persistentIDs))
fmt.Printf("This will permanently delete all molecule data with no digest.\n")
fmt.Printf("\nContinue? [y/N] ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
fmt.Println("Canceled.")
return nil
}
}
batchResult := BatchBurnResult{
Results: make([]BurnResult, 0),
FailedCount: len(failedResolve),
}
// Batch delete all wisps in one call
if len(wispIDs) > 0 {
result, err := burnWisps(ctx, store, wispIDs, currentActor())
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Error burning wisps: %v\n", err)
}
} else {
batchResult.TotalDeleted += result.DeletedCount
batchResult.Results = append(batchResult.Results, *result)
}
}
// Handle persistent molecules individually (they need subgraph loading)
for _, id := range persistentIDs {
subgraph, err := loadTemplateSubgraph(ctx, store, id)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to load subgraph for %s: %v\n", id, err)
}
batchResult.FailedCount++
continue
}
var issueIDs []string
for _, issue := range subgraph.Issues {
issueIDs = append(issueIDs, issue.ID)
}
if err := deleteBatch(nil, issueIDs, true, false, false, false, false, nil, "mol burn"); err != nil {
return HandleErrorRespectJSON("%v", err)
}
batchResult.TotalDeleted += len(issueIDs)
batchResult.Results = append(batchResult.Results, BurnResult{
MoleculeID: id,
DeletedIDs: issueIDs,
DeletedCount: len(issueIDs),
})
}
if jsonOutput {
return outputJSON(batchResult)
}
fmt.Printf("%s Burned %d molecule(s): %d issues deleted\n", ui.RenderPass("✓"), len(wispIDs)+len(persistentIDs), batchResult.TotalDeleted)
if batchResult.FailedCount > 0 {
fmt.Printf(" %d failed\n", batchResult.FailedCount)
}
return nil
}
func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool) error {
subgraph, err := loadTemplateSubgraph(ctx, store, resolvedID)
if err != nil {
return HandleErrorRespectJSON("loading wisp molecule: %v", err)
}
var wispIDs []string
for _, issue := range subgraph.Issues {
if issue.Ephemeral {
wispIDs = append(wispIDs, issue.ID)
}
}
if len(wispIDs) == 0 {
if jsonOutput {
return outputJSON(BurnResult{
MoleculeID: resolvedID,
DeletedCount: 0,
})
}
fmt.Printf("No wisp issues found for molecule %s\n", resolvedID)
return nil
}
if dryRun {
fmt.Printf("\nDry run: would burn wisp %s\n\n", resolvedID)
fmt.Printf("Root: %s\n", subgraph.Root.Title)
fmt.Printf("\nWisp issues to delete (%d total):\n", len(wispIDs))
for _, issue := range subgraph.Issues {
if !issue.Ephemeral {
continue
}
status := string(issue.Status)
if issue.ID == subgraph.Root.ID {
fmt.Printf(" - [%s] %s (%s) [ROOT]\n", status, issue.Title, issue.ID)
} else {
fmt.Printf(" - [%s] %s (%s)\n", status, issue.Title, issue.ID)
}
}
fmt.Printf("\nNo digest will be created (use 'bd mol squash' to create one).\n")
return nil
}
if !force && !jsonOutput {
fmt.Printf("About to burn wisp %s (%d issues)\n", resolvedID, len(wispIDs))
fmt.Printf("This will permanently delete all wisp data with no digest.\n")
fmt.Printf("Use 'bd mol squash' instead if you want to preserve a summary.\n")
fmt.Printf("\nContinue? [y/N] ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
fmt.Println("Canceled.")
return nil
}
}
result, err := burnWisps(ctx, store, wispIDs, currentActor())
if err != nil {
return HandleErrorRespectJSON("burning wisp: %v", err)
}
result.MoleculeID = resolvedID
if jsonOutput {
return outputJSON(result)
}
fmt.Printf("%s Burned wisp: %d issues deleted\n", ui.RenderPass("✓"), result.DeletedCount)
fmt.Printf(" Ephemeral: %s\n", resolvedID)
fmt.Printf(" No digest created.\n")
return nil
}
func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, force bool) error {
subgraph, err := loadTemplateSubgraph(ctx, store, resolvedID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
var issueIDs []string
for _, issue := range subgraph.Issues {
issueIDs = append(issueIDs, issue.ID)
}
if len(issueIDs) == 0 {
if jsonOutput {
return outputJSON(BurnResult{
MoleculeID: resolvedID,
DeletedCount: 0,
})
}
fmt.Printf("No issues found for molecule %s\n", resolvedID)
return nil
}
if dryRun {
fmt.Printf("\nDry run: would burn mol %s\n\n", resolvedID)
fmt.Printf("Root: %s\n", subgraph.Root.Title)
fmt.Printf("\nIssues to delete (%d total):\n", len(issueIDs))
for _, issue := range subgraph.Issues {
status := string(issue.Status)
if issue.ID == subgraph.Root.ID {
fmt.Printf(" - [%s] %s (%s) [ROOT]\n", status, issue.Title, issue.ID)
} else {
fmt.Printf(" - [%s] %s (%s)\n", status, issue.Title, issue.ID)
}
}
fmt.Printf("\nNote: Persistent mol - deletions sync to remotes.\n")
fmt.Printf("No digest will be created (use 'bd mol squash' to create one).\n")
return nil
}
if !force && !jsonOutput {
fmt.Printf("About to burn mol %s (%d issues)\n", resolvedID, len(issueIDs))
fmt.Printf("This will permanently delete all molecule data with no digest.\n")
fmt.Printf("Note: Persistent mol - deletions sync to remotes.\n")
fmt.Printf("Use 'bd mol squash' instead if you want to preserve a summary.\n")
fmt.Printf("\nContinue? [y/N] ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
fmt.Println("Canceled.")
return nil
}
}
if err := deleteBatch(nil, issueIDs, true, false, false, jsonOutput, false, nil, "mol burn"); err != nil {
return HandleErrorRespectJSON("%v", err)
}
return nil
}
// burnWisps deletes all wisp issues atomically within a single transaction.
// If any delete fails, the entire operation is rolled back to prevent partial deletion.
func burnWisps(ctx context.Context, s storage.DoltStorage, ids []string, actorName string) (*BurnResult, error) {
var result *BurnResult
err := transact(ctx, s, "bd: burn wisps", func(tx storage.Transaction) error {
r, err := burnWispsInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, ids, actorName)
if err != nil {
return err
}
result = r
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func burnWispsInto(ctx context.Context, w molWriter, ids []string, actorName string) (*BurnResult, error) {
result := &BurnResult{
DeletedIDs: make([]string, 0, len(ids)),
}
for _, id := range ids {
if err := w.DeleteIssue(ctx, id, actorName); err != nil {
return nil, fmt.Errorf("failed to delete wisp %s: %w", id, err)
}
result.DeletedIDs = append(result.DeletedIDs, id)
result.DeletedCount++
}
return result, nil
}
func init() {
molBurnCmd.Flags().Bool("dry-run", false, "Preview what would be deleted")
molBurnCmd.Flags().Bool("force", false, "Skip confirmation prompt")
molBurnCmd.Flags().BoolP("yes", "y", false, "Alias for --force (skip confirmation)")
_ = molBurnCmd.Flags().MarkHidden("yes")
molCmd.AddCommand(molBurnCmd)
}