* fix(mol): clear root Ephemeral on bd mol squash
bd mol squash auto-closes a wisp molecule's root but did not clear its
Ephemeral flag, contrary to the wisp lifecycle help text ("Squash: bd
mol squash <id> (clears Ephemeral flag, promotes to persistent)").
The closed-but-still-ephemeral root row remained in the wisps table, so
auto-export queries (Ephemeral=true) re-emitted it as a duplicate JSONL
row on every export cycle, accumulating noise indefinitely.
Within the squash transaction, after closing the root, also call
tx.UpdateIssue to set wisp=false. This mirrors what the bd update
<id> --persistent workaround does today and matches the natural
"squash absorbs the molecule into a digest" mental model.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test(mol): add embedded-dolt regression for squash root Ephemeral
The standalone-Dolt regression test in mol_test.go skips in the
Embedded Dolt CI tier, leaving the squash fix's lines uncovered
(Codecov 0% on the patch).
Add a parallel test using embeddeddolt.New so the fix is exercised
in the default CI matrix.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
308 lines
9.7 KiB
Go
308 lines
9.7 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
)
|
|
|
|
var molSquashCmd = &cobra.Command{
|
|
Use: "squash <molecule-id>",
|
|
Short: "Compress molecule execution into a digest",
|
|
Long: `Squash a molecule's ephemeral children into a single digest issue.
|
|
|
|
This command collects all ephemeral child issues of a molecule (Ephemeral=true),
|
|
generates a summary digest, and promotes the wisps to persistent by
|
|
clearing their Wisp flag (or optionally deletes them).
|
|
|
|
The squash operation:
|
|
1. Loads the molecule and all its children
|
|
2. Filters to only wisps (ephemeral issues with Ephemeral=true)
|
|
3. Generates a digest (summary of work done)
|
|
4. Creates a permanent digest issue (Ephemeral=false)
|
|
5. Clears Wisp flag on children (promotes to persistent)
|
|
OR keeps them with --keep-children (default: delete)
|
|
|
|
AGENT INTEGRATION:
|
|
Use --summary to provide an AI-generated summary. This keeps bd as a pure
|
|
tool - the calling agent (orchestrator worker, Claude Code, etc.) is responsible
|
|
for generating intelligent summaries. Without --summary, a basic concatenation
|
|
of child issue content is used.
|
|
|
|
This is part of the wisp workflow: spawn creates wisps,
|
|
execution happens, squash compresses the trace into an outcome (digest).
|
|
|
|
Example:
|
|
bd mol squash bd-abc123 # Squash and promote children
|
|
bd mol squash bd-abc123 --dry-run # Preview what would be squashed
|
|
bd mol squash bd-abc123 --keep-children # Keep wisps after digest
|
|
bd mol squash bd-abc123 --summary "Agent-generated summary of work done"`,
|
|
Args: cobra.ExactArgs(1),
|
|
Run: runMolSquash,
|
|
}
|
|
|
|
// SquashResult holds the result of a squash operation
|
|
type SquashResult struct {
|
|
MoleculeID string `json:"molecule_id"`
|
|
DigestID string `json:"digest_id"`
|
|
SquashedIDs []string `json:"squashed_ids"`
|
|
SquashedCount int `json:"squashed_count"`
|
|
DeletedCount int `json:"deleted_count"`
|
|
KeptChildren bool `json:"kept_children"`
|
|
WispSquash bool `json:"wisp_squash,omitempty"` // True if this was a wisp→digest squash
|
|
}
|
|
|
|
func runMolSquash(cmd *cobra.Command, args []string) {
|
|
CheckReadonly("mol squash")
|
|
|
|
ctx := rootCtx
|
|
|
|
// mol squash requires direct store access
|
|
if store == nil {
|
|
FatalErrorWithHint("no database connection", diagHint())
|
|
}
|
|
|
|
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
keepChildren, _ := cmd.Flags().GetBool("keep-children")
|
|
summary, _ := cmd.Flags().GetString("summary")
|
|
|
|
// Resolve molecule ID in main store
|
|
moleculeID, err := utils.ResolvePartialID(ctx, store, args[0])
|
|
if err != nil {
|
|
FatalError("resolving molecule ID %s: %v", args[0], err)
|
|
}
|
|
|
|
// Load the molecule subgraph from main store
|
|
subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID)
|
|
if err != nil {
|
|
FatalError("loading molecule: %v", err)
|
|
}
|
|
|
|
// Filter to only ephemeral children (exclude root)
|
|
var wispChildren []*types.Issue
|
|
for _, issue := range subgraph.Issues {
|
|
if issue.ID == subgraph.Root.ID {
|
|
continue // Skip root
|
|
}
|
|
if issue.Ephemeral {
|
|
wispChildren = append(wispChildren, issue)
|
|
}
|
|
}
|
|
|
|
if len(wispChildren) == 0 {
|
|
if jsonOutput {
|
|
outputJSON(SquashResult{
|
|
MoleculeID: moleculeID,
|
|
SquashedCount: 0,
|
|
})
|
|
} else {
|
|
fmt.Printf("No ephemeral children found for molecule %s\n", moleculeID)
|
|
}
|
|
return
|
|
}
|
|
|
|
if dryRun {
|
|
fmt.Printf("\nDry run: would squash %d ephemeral children of %s\n\n", len(wispChildren), moleculeID)
|
|
fmt.Printf("Root: %s\n", subgraph.Root.Title)
|
|
fmt.Printf("\nWisp children to squash:\n")
|
|
for _, issue := range wispChildren {
|
|
status := string(issue.Status)
|
|
fmt.Printf(" - [%s] %s (%s)\n", status, issue.Title, issue.ID)
|
|
}
|
|
fmt.Printf("\nDigest preview:\n")
|
|
digest := generateDigest(subgraph.Root, wispChildren)
|
|
// Show first 500 chars of digest
|
|
if len(digest) > 500 {
|
|
fmt.Printf("%s...\n", digest[:500])
|
|
} else {
|
|
fmt.Printf("%s\n", digest)
|
|
}
|
|
if keepChildren {
|
|
fmt.Printf("\n--keep-children: children would NOT be deleted\n")
|
|
} else {
|
|
fmt.Printf("\nChildren would be deleted after digest creation.\n")
|
|
}
|
|
return
|
|
}
|
|
|
|
// Perform the squash
|
|
result, err := squashMolecule(ctx, store, subgraph.Root, wispChildren, keepChildren, summary, actor)
|
|
if err != nil {
|
|
FatalError("squashing molecule: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
outputJSON(result)
|
|
return
|
|
}
|
|
|
|
fmt.Printf("%s Squashed molecule: %d children → 1 digest\n", ui.RenderPass("✓"), result.SquashedCount)
|
|
fmt.Printf(" Digest ID: %s\n", result.DigestID)
|
|
if result.DeletedCount > 0 {
|
|
fmt.Printf(" Deleted: %d wisps\n", result.DeletedCount)
|
|
} else if result.KeptChildren {
|
|
fmt.Printf(" Children preserved (--keep-children)\n")
|
|
}
|
|
if result.WispSquash {
|
|
fmt.Printf(" Root auto-closed: %s\n", result.MoleculeID)
|
|
}
|
|
}
|
|
|
|
// generateDigest creates a summary from the molecule execution
|
|
// Tier 2: Simple concatenation of titles and descriptions
|
|
// Tier 3 (future): AI-powered summarization using Haiku
|
|
func generateDigest(root *types.Issue, children []*types.Issue) string {
|
|
var sb strings.Builder
|
|
|
|
sb.WriteString("## Molecule Execution Summary\n\n")
|
|
sb.WriteString(fmt.Sprintf("**Molecule**: %s\n", root.Title))
|
|
sb.WriteString(fmt.Sprintf("**Steps**: %d\n\n", len(children)))
|
|
|
|
// Count completed vs other statuses
|
|
completed := 0
|
|
inProgress := 0
|
|
for _, c := range children {
|
|
switch c.Status {
|
|
case types.StatusClosed:
|
|
completed++
|
|
case types.StatusInProgress:
|
|
inProgress++
|
|
}
|
|
}
|
|
sb.WriteString(fmt.Sprintf("**Completed**: %d/%d\n", completed, len(children)))
|
|
if inProgress > 0 {
|
|
sb.WriteString(fmt.Sprintf("**In Progress**: %d\n", inProgress))
|
|
}
|
|
sb.WriteString("\n---\n\n")
|
|
|
|
// List each step with its outcome
|
|
sb.WriteString("### Steps\n\n")
|
|
for i, child := range children {
|
|
status := string(child.Status)
|
|
sb.WriteString(fmt.Sprintf("%d. **[%s]** %s\n", i+1, status, child.Title))
|
|
if child.Description != "" {
|
|
// Include first 200 chars of description
|
|
desc := child.Description
|
|
if len(desc) > 200 {
|
|
desc = desc[:200] + "..."
|
|
}
|
|
sb.WriteString(fmt.Sprintf(" %s\n", desc))
|
|
}
|
|
if child.CloseReason != "" {
|
|
sb.WriteString(fmt.Sprintf(" *Outcome: %s*\n", child.CloseReason))
|
|
}
|
|
sb.WriteString("\n")
|
|
}
|
|
|
|
return sb.String()
|
|
}
|
|
|
|
// squashMolecule performs the squash operation
|
|
// If summary is provided (non-empty), it's used as the digest content.
|
|
// Otherwise, generateDigest() creates a basic concatenation.
|
|
// This enables agents to provide AI-generated summaries while keeping bd as a pure tool.
|
|
func squashMolecule(ctx context.Context, s storage.DoltStorage, root *types.Issue, children []*types.Issue, keepChildren bool, summary string, actorName string) (*SquashResult, error) {
|
|
if s == nil {
|
|
return nil, fmt.Errorf("no database connection")
|
|
}
|
|
|
|
// Collect child IDs
|
|
childIDs := make([]string, len(children))
|
|
for i, c := range children {
|
|
childIDs[i] = c.ID
|
|
}
|
|
|
|
// Use agent-provided summary if available, otherwise generate basic digest
|
|
var digestContent string
|
|
if summary != "" {
|
|
digestContent = summary
|
|
} else {
|
|
digestContent = generateDigest(root, children)
|
|
}
|
|
|
|
// Create digest issue (permanent, not a wisp)
|
|
now := time.Now()
|
|
digestIssue := &types.Issue{
|
|
Title: fmt.Sprintf("Digest: %s", root.Title),
|
|
Description: digestContent,
|
|
Status: types.StatusClosed,
|
|
CloseReason: fmt.Sprintf("Squashed from %d wisps", len(children)),
|
|
Priority: root.Priority,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: false, // Digest is permanent, not a wisp
|
|
ClosedAt: &now,
|
|
}
|
|
|
|
result := &SquashResult{
|
|
MoleculeID: root.ID,
|
|
SquashedIDs: childIDs,
|
|
SquashedCount: len(children),
|
|
KeptChildren: keepChildren,
|
|
}
|
|
|
|
// All squash operations in a single transaction for atomicity (bd-4kgbq):
|
|
// digest creation, child deletion, and root close
|
|
err := transact(ctx, s, fmt.Sprintf("bd: squash molecule %s", root.ID), func(tx storage.Transaction) error {
|
|
// Create digest issue
|
|
if err := tx.CreateIssue(ctx, digestIssue, actorName); err != nil {
|
|
return fmt.Errorf("failed to create digest issue: %w", err)
|
|
}
|
|
result.DigestID = digestIssue.ID
|
|
|
|
// Link digest to root as parent-child
|
|
dep := &types.Dependency{
|
|
IssueID: digestIssue.ID,
|
|
DependsOnID: root.ID,
|
|
Type: types.DepParentChild,
|
|
}
|
|
if err := tx.AddDependency(ctx, dep, actorName); err != nil {
|
|
return fmt.Errorf("failed to link digest to root: %w", err)
|
|
}
|
|
|
|
// Delete ephemeral children within the same transaction
|
|
if !keepChildren {
|
|
for _, id := range childIDs {
|
|
if err := tx.DeleteIssue(ctx, id); err != nil {
|
|
return fmt.Errorf("failed to delete child %s: %w", id, err)
|
|
}
|
|
result.DeletedCount++
|
|
}
|
|
}
|
|
|
|
// Auto-close the root if it's a wisp — squash completes the molecule lifecycle
|
|
if root.Ephemeral {
|
|
reason := fmt.Sprintf("Squashed: %d steps → digest %s", len(children), result.DigestID)
|
|
if err := tx.CloseIssue(ctx, root.ID, reason, actorName, ""); err != nil {
|
|
return fmt.Errorf("failed to close wisp root %s: %w", root.ID, err)
|
|
}
|
|
// Clear ephemeral so the closed root stops being re-emitted by every wisp-table export cycle.
|
|
if err := tx.UpdateIssue(ctx, root.ID, map[string]interface{}{"wisp": false}, actorName); err != nil {
|
|
return fmt.Errorf("failed to clear ephemeral flag on root %s: %w", root.ID, err)
|
|
}
|
|
result.WispSquash = true
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func init() {
|
|
molSquashCmd.Flags().Bool("dry-run", false, "Preview what would be squashed")
|
|
molSquashCmd.Flags().Bool("keep-children", false, "Don't delete ephemeral children after squash")
|
|
molSquashCmd.Flags().String("summary", "", "Agent-provided summary (bypasses auto-generation)")
|
|
|
|
molCmd.AddCommand(molSquashCmd)
|
|
}
|