Version Bump: {{version}}

Release checklist for version {{version}}. This molecule ensures all release steps are completed properly.


Witness Patrol

Per-rig worker monitor patrol loop with progressive nudging.


Add tests for helper functions (GetDirtyIssueHash, GetAllDependencyRecords, export hashes)

Several utility functions have 0% coverage:
- GetDirtyIssueHash (dirty.go)
- GetAllDependencyRecords (dependencies.go)
- GetExportHash, SetExportHash, ClearAllExportHashes (hash.go)

These are lower priority but should have basic coverage.


Test message

Hello world


Add bd template list command

Add a convenience command to list available templates:

bd template list

This is equivalent to 'bd list --label=template' but more discoverable.
Could also show variable placeholders found in each template.


Restart daemons

bd daemons killall


Merge: bd-ot0w

branch: polecat/dementus
target: main
source_issue: bd-ot0w
rig: beads


bd merge omits priority:0 due to omitempty JSON tag

GitHub issue #671. The merge code in internal/merge/merge.go uses 'omitempty' on the Priority field, which causes priority:0 (P0/critical) to be dropped from JSON output since 0 is Go's zero value for int. Fix: either remove omitempty from Priority field or use a pointer (*int). This affects the git merge driver and causes P0 issues to lose their priority.


Clean up orphaned child issues (bd-cb64c226.*, bd-cbed9619.*)

## Problem

Every bd command shows warnings about 12 orphaned child issues:
- bd-cb64c226.1, .6, .8, .9, .10, .12, .13
- bd-cbed9619.1, .2, .3, .4, .5

These are hierarchical IDs (parent.child format) where the parent issues no longer exist.

## Impact

- Clutters output of every bd command
- Confusing for users
- Indicates incomplete cleanup of deleted parent issues

## Proposed Solution

1. Delete the orphaned issues since their parents no longer exist:
   ```bash
   bd delete bd-cb64c226.1 bd-cb64c226.6 bd-cb64c226.8 ...
   ```

2. Or convert them to top-level issues if they contain useful content

## Investigation Needed

- What were the parent issues bd-cb64c226 and bd-cbed9619?
- Why were they deleted without their children?
- Should bd delete cascade to children automatically?


Fix TestImportBugIntegration deadlock in importer_test.go

Code health review found internal/importer/importer_test.go has TestImportBugIntegration skipped with:

TODO: Test hangs due to database deadlock - needs investigation

This indicates a potential unresolved concurrency issue in the importer. The test has been skipped for an unknown duration.

Fix: Investigate the deadlock, fix the underlying issue, and re-enable the test.


Merge: beads-ocs

branch: polecat/valkyrie
target: main
source_issue: beads-ocs
rig: beads


Witness Patrol


Add bd mol run command (bond + assign + pin)

bd mol run = bond + assign root to caller + pin to startup mail. This is the Gas Town integration point. When agent restarts, check startup mail, find pinned molecule root, query bd ready for next step. Makes molecules immortal.


Update info.go versionChanges

Add entry to versionChanges in cmd/bd/info.go with agent-actionable changes for 0.30.7


Upgrade beads-mcp

pip3 install --upgrade beads-mcp


bd init should stop running daemon to avoid stale cache

When running bd init, any running daemon continues with stale cached data, causing bd stats and other commands to show old counts.

Repro:
1. Have daemon running with 788 issues cached
2. Clean JSONL to 128 issues, delete db, run bd init
3. bd stats still shows 788 (daemon cache)
4. Must manually run bd daemon --stop

Fix: bd init should automatically stop any running daemon before reinitializing.


Show pin indicator in bd list output

Add a visual indicator (e.g., pin emoji or [P] marker) for pinned issues in bd list output so users can easily identify them.


bd ship command for publishing capabilities

Add `bd ship <capability>` command that:

1. Finds issue with `export:<capability>` label
2. Validates issue is closed (or --force to override)
3. Adds `provides:<capability>` label
4. Protects `provides:*` namespace (only bd ship can add these labels)

Example:
```bash
bd ship mol-run-assignee
# Output: Shipped mol-run-assignee (bd-xyz)
```

Part of cross-project dependency system.
See: gastown/docs/cross-project-deps.md


Graph Link: relates_to for knowledge graph

Implement relates_to link type for loose associations.

New command:
- bd relate <id1> <id2> - creates bidirectional relates_to link

Query support:
- bd show <id> --related shows related issues
- bd list --related-to <id>

Storage:
- relates_to stored as JSON array of issue IDs
- Consider: separate junction table for efficiency at scale?

This enables 'see also' connections without blocking or hierarchy.


Merge: bd-49kw

branch: polecat/nux
target: main
source_issue: bd-49kw
rig: beads


Add external_projects to config schema

Add external_projects mapping to .beads/config.yaml:

```yaml
external_projects:
  beads: ../beads
  gastown: ../gastown
  other: /absolute/path/to/project
```

Used by bd ready and other commands to resolve external: references.

Part of cross-project dependency system.
See: gastown/docs/cross-project-deps.md


Improve test coverage

The test suite reports less than 45% code coverage. Identify the specific uncovered areas of the codebase, including modules, functions, or features. Rank them by potential impact on system reliability and business value, from most to least, and provide actionable recommendations for improving coverage in each area.


Test actor direct


Add Validation type and validations field to Issue

Add Validation struct (Validator *EntityRef, Outcome string, Timestamp time.Time, Score *float32) and Validations []Validation field to Issue. Tracks who validated/approved work completion. Core to HOP proof-of-stake concept - validators stake reputation on approvals.


Molecule execution state management

Implement molecule execution state tracking.

## State Location

```
.beads/molecules/<mol-id>.state.yaml
```

## State Schema

```yaml
id: mol-deacon-patrol
formula: mol-deacon-patrol  # Source formula
bonded_at: ISO timestamp
bonded_by: entity who created it

# Execution state
status: running | paused | completed | failed
current_step: step-id
started_at: ISO timestamp
completed_at: ISO timestamp (if done)

# Loop tracking
reset_count: 0
last_reset_at: null

# Per-step state
steps:
  inbox-check:
    status: completed | in_progress | pending
    started_at: ...
    completed_at: ...
  spawn-work:
    status: pending
  self-inspect:
    status: pending

# Variables (from formula instantiation)
variables:
  rig: gastown
  issue_id: gt-xxx
```

## Operations

- CreateState(molID, formula, variables) - Initialize state
- LoadState(molID) - Read current state
- SaveState(molID, state) - Write state
- AdvanceStep(molID) - Mark current complete, find next
- ResetState(molID) - Reset all steps to pending

## Files

- internal/mol/state.go
- internal/mol/types.go


Run go install

go install ./cmd/bd


gt spawn/crew setup should create .beads/redirect for worktrees

Crew clones and polecats need a .beads/redirect file pointing to the shared beads database (../../mayor/rig/.beads). Currently:

- redirect files can get deleted by git clean
- not auto-created during gt spawn or worktree setup
- missing redirects cause 'no beads database found' errors

Found missing in: gastown/joe, beads/zoey (after git clean)

Fix options:
1. gt spawn creates redirect during worktree setup
2. gt prime regenerates missing redirects
3. bd commands auto-detect worktree and find shared beads

This should be standard Gas Town rig configuration.


Run tests

TMPDIR=/tmp go test -short ./...


Update info.go versionChanges

Add 0.32.1 entry to versionChanges map in cmd/bd/info.go


BondRef data model for compound lineage

Add data model support for tracking compound molecule lineage.

NEW FIELDS on Issue:
  bonded_from: []BondRef  // For compounds: constituent protos

NEW TYPE:
  type BondRef struct {
      ProtoID   string  // Source proto ID
      BondType  string  // sequential, parallel, conditional
      BondPoint string  // Attachment site (issue ID or empty for root)
  }

JSONL SERIALIZATION:
  {
    "id": "proto-feature-tested",
    "title": "Feature with tests",
    "bonded_from": [
      {"proto_id": "proto-feature", "bond_type": "root"},
      {"proto_id": "proto-testing", "bond_type": "sequential"}
    ],
    ...
  }

QUERIES:
- GetCompoundConstituents(id) → []BondRef
- IsCompound(id) → bool
- GetCompoundsUsing(protoID) → []Issue  // Reverse lookup


Remove unreachable RPC methods

Several RPC server and client methods are unreachable and should be removed:

Server methods (internal/rpc/server.go):
- `Server.GetLastImportTime` (line 2116)
- `Server.SetLastImportTime` (line 2123)
- `Server.findJSONLPath` (line 2255)

Client methods (internal/rpc/client.go):
- `Client.Import` (line 311) - RPC import not used (daemon uses autoimport)

Evidence:
```bash
go run golang.org/x/tools/cmd/deadcode@latest -test ./...
```

Impact: Removes ~80 LOC of unused RPC code


Mol Mall: Formula marketplace using GitHub as backend

Create a marketplace for sharing molecule formulas using GitHub repos as the hosting backend.

## Why GitHub?

GitHub solves multiple problems at once:
- **Hosting**: Raw file URLs for formula.json
- **Versioning**: Git tags (v1.0.0, v1.2.0)
- **Auth**: GitHub tokens for private formulas
- **Discovery**: GitHub search, topics, stars
- **Collaboration**: PRs for contributions, issues for bugs
- **Organizations**: Natural scoping (@anthropic/, @gastown/)

## URL Scheme

```bash
# Direct GitHub URL
bd mol install github.com/anthropics/mol-code-review

# With version tag
bd mol install github.com/anthropics/mol-code-review@v1.2.0

# Shorthand (via registry lookup)
bd mol install @anthropic/mol-code-review
```

## Architecture

### Distributed Model (like Go modules)
Each formula lives in its own repo:
```
github.com/anthropics/mol-code-review/
├── formula.json      # The formula
├── README.md         # Documentation
└── CHANGELOG.md      # Version history
```

### Optional Registry (for discovery)
```
github.com/anthropics/mol-mall/
└── registry.json     # Index pointing to formula repos
```

## Child Issues

1. `bd mol export` - Proto → Formula file
2. `bd mol promote` - Distilled proto → Catalog proto (one step)
3. `bd mol install` - GitHub → Local proto
4. `bd mol update` - Check for newer versions
5. `bd mol search` - Find formulas (GitHub API)
6. `bd mol publish` - Push formula to GitHub repo
7. Formula versioning - Version field + git tag integration
8. Installation tracking - .beads/installed.json

## ID Namespace Design

| Entity | ID Format | Example |
|--------|-----------|---------|
| Formula (GitHub) | `github.com/org/repo` | `github.com/anthropics/mol-code-review` |
| Catalog proto (local) | `mol-name` | `mol-code-review` |
| Distilled proto | `<db>-proto-xxx` | `bd-proto-a7f` |
| Poured instance | `<db>-mol-xxx` | `gt-mol-b8c` |
| Wisp instance | `<db>-wisp-xxx` | `hq-wisp-d9e` |


wish: list & ready show issues as hierarchy tree

`bd ready` and `bd list` just show a flat list, and it's up to the reader to parse which ones are dependent or sub-issues of others. It would be much easier to understand if they were shown in a tree format


Technical debt: Scattered TODOs should be tracked as issues

Multiple TODO comments exist in the codebase that should be tracked as proper issues:

1. cmd/bd/migrate_hash_ids.go:24 - 'Consider integrating into bd doctor migration detection'
2. cmd/bd/migrate_tombstones.go:72 - Same
3. cmd/bd/migrate_sync.go:16 - Same
4. cmd/bd/migrate_issues.go:15 - Same
5. cmd/bd/create.go:164 - 'Switch to target repo for multi-repo support'
6. cmd/bd/create.go:208 - 'Add RPC method to get config in daemon mode'
7. cmd/bd/daemon_logger.go:131 - 'Remove this once all callers are updated'
8. cmd/bd/mol_stale.go:67 - 'Add RPC endpoint for stale check'
9. cmd/bd/sync_test.go:444 - 'Refactor to use direct import logic'
10. cmd/bd/jira.go:633 - 'In a full implementation, fetch Jira issue and compare timestamps'
11. internal/formula/types.go:170,174,179,186,210 - Multiple 'Not yet implemented' TODOs
12. internal/importer/importer_test.go:1010 - 'Test hangs due to database deadlock'

Consider:
1. Running 'grep -r TODO' periodically to find new ones
2. Adding a lint rule to discourage inline TODOs
3. Converting each to a bd issue with proper tracking

Location: Various files across codebase


bd sync --from-main fails: unknown flag --no-git-history


Phase 2.4: Git merge driver optimization for TOON format

Optimize git 3-way merge for TOON line-oriented format.

## Overview
TOON is line-oriented (unlike binary formats), enabling smarter git merge strategies. Implement custom merge driver to handle TOON-specific merge patterns.

## Required Work

### 2.4.1 TOON Merge Driver
- [ ] Create .git/info/attributes entry for *.toon files
- [ ] Implement custom merge driver script/command
- [ ] Handle tabular format row merges (line-based 3-way)
- [ ] Handle YAML-style format merges
- [ ] Conflict markers for unsolvable conflicts

### 2.4.2 Merge Patterns
- [ ] Row addition: both branches add different rows → union
- [ ] Row deletion: one branch deletes, other modifies → conflict (manual review)
- [ ] Row modification: concurrent field changes → intelligent merge or conflict
- [ ] Field ordering changes: ignore (TOON format resilient to order)

### 2.4.3 Testing & Documentation
- [ ] Unit tests for merge scenarios (3-way merge logic)
- [ ] Integration tests with actual git merges
- [ ] Conflict scenario testing
- [ ] Documentation of merge strategy

## Success Criteria
- Git merge handles TOON conflicts intelligently
- Fewer manual merge conflicts than JSONL
- Round-trip preserved through merges
- All 70+ tests still passing
- Git history stays clean (minimal conflict markers)


Update molecular chemistry docs with discoveries

Document recent discoveries about molecule/epic relationship and lifecycle:

**Layer Cake (corrected order):**
```
Formulas (YAML compile-time macros)
    ↓
Protos (template label, read-only)
    ↓
Molecules (pour, bond, squash, burn)
    ↓
Epics (parent-child, dependencies) ← DATA PLANE
    ↓
Issues (JSONL, git-backed) ← STORAGE
```

**Key insight:** Molecules work without protos - you can create ad-hoc molecules.
Protos are templates FOR molecules, not the other way around.

**New concepts to document:**
1. Orphan vs Stale matrix (blocking × assigned dimensions)
2. Graph pressure as staleness indicator (not time)
3. Parallelism via absence of depends_on (default parallel, opt-in sequential)
4. progress.Completed/Total are computed, not stored
5. WaitsFor: all-children for dynamic fanout gates

**Common pitfalls for agents:**
- Thinking phases/steps imply sequence (NO - deps do)
- Confusing protos with molecules
- Temporal language inverting dependencies
- Forgetting to squash/burn wisps

**Consider splitting docs:**
- molecules.md → conceptual overview
- formulas.md → YAML syntax reference
- lifecycle.md → pour/squash/burn/bond operations
- patterns.md → Christmas Ornament, factory assembly, etc.


Test actor flag


Daemon should be singleton and aggressively kill stale instances

Found 2 bd daemons running (PIDs 76868, 77515) during shutdown. The daemon should:

1. Be a singleton - only one instance per rig allowed
2. On startup, check for existing daemon and kill it before starting
3. Use a PID file or lock file to enforce this

Currently stale daemons can accumulate, causing confusion and resource waste.

**Investigation 2025-12-21:**

The singleton mechanism is already implemented and working correctly:

1. **daemon.lock** uses flock (exclusive non-blocking) to prevent duplicate daemons
2. **bd.sock.startlock** coordinates concurrent auto-starts via O_CREATE|O_EXCL
3. **Registry** tracks all daemons globally in ~/.beads/registry.json

Testing shows:
- Trying to start a second daemon gives: 'Error: daemon already running (PID X)'
- Multiple daemons for *different* rigs is expected/correct behavior

The original report ('Found 2 bd daemons running PIDs 76868, 77515') was likely:
1. Two daemons for different rigs (expected), OR
2. An edge case that's since been fixed

Consider closing as RESOLVED or clarifying the original scenario.


Cross-project dependency support

Enable tracking dependencies across project boundaries.

## Mechanism
- Producer: `bd ship <capability>` adds `provides:<capability>` label
- Consumer: `blocked_by: external:<project>:<capability>`
- Resolution: `bd ready` checks external deps via config

## Design Doc
See: gastown/docs/cross-project-deps.md

## Children
- bd-eijl: bd ship command
- bd-om4a: external: prefix in blocked_by
- bd-66w1: external_projects config
- bd-zmmy: bd ready resolution


Remove Cache-Related Tests

Delete or update tests that assume multi-repo caching


Add test files for internal/storage

The internal/storage package has no test files at all. This package provides the storage interface abstraction.

Current coverage: N/A (no test files)
Target: Add basic interface tests


Update local installations.

Update local installations.

```bash
# Upgrade Homebrew
brew upgrade steveyegge/beads/bd

# Or install from source
./scripts/bump-version.sh 0.37.0 --install

# Install MCP locally
pip install -e integrations/beads-mcp

# Restart daemons
pkill -f "bd daemon" || true
```

Verify: `bd --version` shows 0.37.0

instantiated_from: bd-mol-xga
step: update-local


Add creator field to Issue struct

Add Creator *EntityRef field to Issue. Tracks who created the issue. Optional, omitted if nil in JSONL. This enables CV chain tracking - every piece of work is attributed to its creator.


Fix JSON errors in comments.go

Replace direct stderr writes with FatalErrorRespectJSON() in comments.go.

Commands affected:
- commentsCmd (list)
- commentsAddCmd


Tier 4: Auto-squash on molecule completion

Automatically squash molecules when they reach terminal state.

## Integration Points

1. Hook into molecule completion handler
2. Detect when all steps are done/failed
3. Trigger squash automatically

## Config

bd config set mol.auto_squash true  # Default: false
bd config set mol.auto_squash_on_success true  # Only on success
bd config set mol.auto_squash_delay '5m'  # Wait before squash

## Implementation Options

### Option A: Post-Completion Hook
In mol completion handler:
- Check if auto_squash enabled
- Call Squash() after terminal state

### Option B: Git Hook
In .beads/hooks/post-commit:
- bd mol squash --auto

### Option C: Daemon Background Task
- Daemon periodically checks for squashable molecules
- Squashes in background

## Acceptance Criteria

- Completed molecules auto-squash without manual intervention
- Configurable delay before squash
- Option to squash only on success vs always
- Works with both daemon and no-daemon modes


Simplify bd onboard to minimal AGENTS.md snippet pointing to bd prime

## Context
GH#604 raised concerns about bd onboard bloating AGENTS.md with ~100+ lines of static instructions that:
- Load every session whether beads is being used or not
- Get stale when bd upgrades
- Waste tokens

## Solution
Simplify `bd onboard` to output a minimal snippet (~2 lines) that points to `bd prime`:

```markdown
## Issue Tracking
This project uses beads (`bd`) for issue tracking.
Run `bd prime` for workflow context, or hooks auto-inject it.
```

## Rationale
- `bd prime` is dynamic, concise (~80 lines), and always matches installed bd version
- Hooks already auto-inject `bd prime` at session start when .beads/ detected
- AGENTS.md only needs to mention beads exists, not contain full instructions

## Implementation
1. Update `cmd/bd/onboard.go` to output minimal snippet
2. Keep `--output` flag for BD_GUIDE.md generation (may still be useful)
3. Update help text to explain the new approach


Design contributor namespace isolation for beads pollution prevention

## Problem

When contributors work on beads-the-project using beads-the-tool, their personal work-tracking issues leak into PRs. The .beads/issues.jsonl is intentionally tracked (it's the project's issue database), but contributors' local issues pollute the diff.

This is a recursion problem unique to self-hosting projects.

## Possible Solutions to Explore

1. **Contributor namespaces** - Each contributor gets a private prefix (e.g., `bd-steve-xxxx`) that's gitignored or filtered
2. **Separate database** - Contributors use BEADS_DIR pointing elsewhere for personal tracking
3. **Issue ownership/visibility flags** - Mark issues as "local-only" vs "project"
4. **Prefix-based filtering** - Configure which prefixes are committed vs ignored

## Design Considerations

- Should be zero-friction for contributors (no manual setup)
- Must not break existing workflows
- Needs to work with sync/collaboration features
- Consider: what if a "personal" issue graduates to "project" issue?

## Expansion Needed

This is a placeholder. Needs detailed design exploration before implementation.


Add versionChanges to info.go

Add entry at TOP of versionChanges in cmd/bd/info.go


Preflight: Check git status

Ensure working tree is clean before starting release.

```bash
git status
```

If there are uncommitted changes, either:
- Commit them first
- Stash them: `git stash`
- Abort and resolve


Update Homebrew formula

After GoReleaser completes, the Homebrew tap should be auto-updated.

If manual update needed:
```bash
./scripts/update-homebrew.sh v0.30.4
```

Or manually update steveyegge/homebrew-beads with new SHA256.

Verify:
```bash
brew update
brew info beads
```


Remove bd mol spawn - use pour/wisp only

Remove the spawn command from bd mol. Replace with:

- bd pour <proto> - Instantiate as mol (liquid, persistent)
- bd wisp <proto> - Instantiate as wisp (vapor, ephemeral)

Rationale:
- 'spawn' doesn't fit the chemistry metaphor
- Two phase transitions (pour/wisp) are clearer than one command with flags
- Avoids confusion about defaults

Implementation:
1. Add bd pour command (currently bd mol spawn --pour)
2. Add bd wisp command (currently bd mol spawn without --pour)
3. Remove bd mol spawn
4. Update all docs/tests

Gas Town tracking: gt-ingm.6


CLI cleanup: Rename bd mol catalog to bd formula list

## Problem
`bd mol catalog` shows formulas, not molecules. This is confusing.

Current state:
- `bd formula list` - lists formulas
- `bd mol catalog` - ALSO lists formulas (duplicate!)

The "mol" namespace should be for molecules (instantiated work), not formulas (templates).

## Proposed Change
- Remove `bd mol catalog`
- Keep `bd formula list` as the canonical command
- Update docs to use `bd formula list`

## Alternative
If we want a "catalog" concept separate from "list", make it `bd formula catalog`.


Install 0.30.4 Go binary locally

Rebuild and install the Go binary:
```bash
go install ./cmd/bd
# OR
make install
```

Verify:
```bash
bd --version
```

```verify
bd --version 2>&1 | grep -q '0.30.4'
```


Make DetectCollisions read-only (separate detection from modification)

**Summary:** The project restructured the collision detection process in the database to separate read-only detection from state modification, eliminating race conditions and improving system reliability. This was achieved by introducing a two-phase approach: first detecting potential collisions, then applying resolution separately.

**Key Decisions:**
- Create read-only DetectCollisions method
- Add RenameDetail to track potential issue renames
- Implement atomic ApplyCollisionResolution function
- Separate detection logic from database modification

**Resolution:** The refactoring creates a more robust, composable collision handling mechanism that prevents partial failures and maintains database consistency during complex issue import scenarios.


Update npm-package/package.json to 0.30.4

Update version field in npm-package/package.json:
```json
"version": "0.30.4"
```

```verify
jq -e '.version == "0.30.4"' npm-package/package.json
```


bd hook: detect agent from cwd instead of defaulting to $USER

**Problem:**
`bd hook` without `--agent` defaults to `$USER` (e.g., "stevey") instead of detecting the agent identity from the current working directory.

**Expected behavior:**
When running from `/Users/stevey/gt/beads/crew/dave`, the agent should be detected as `beads/crew/dave`.

**Current behavior:**
```bash
$ pwd
/Users/stevey/gt/beads/crew/dave
$ bd hook
Hook: stevey
  (empty)

$ bd hook --agent beads/crew/dave
Hook: beads/crew/dave
  📌 bd-hobo (mol) - open
```

**Fix:**
bd hook should use the same cwd-based agent detection that other commands use (similar to how `gt mail` determines identity from cwd).


Fix unparam unused parameter in cmd/bd/doctor.go:1879

Linting issue: checkGitHooks - path is unused (unparam) at cmd/bd/doctor.go:1879:20. Error: func checkGitHooks(path string) doctorCheck {


Polecat sessions terminate unexpectedly during work

During swarm bd-784c, polecat sessions (Toast, Nux) terminated mid-task without completing their work.

**Observed:**
- Polecats were actively working (edits in progress, tests running)
- Sessions suddenly showed 'not running' in gt polecat status
- tmux sessions existed but were empty/reset
- Work was partially complete (some commits made, issue still open)

**Timeline example:**
1. Toast working on bd-1tkd, making edits
2. Check status 30s later - session empty, state shows 'idle'
3. Had to re-sling to restart

**Impact:**
- Lost work progress
- Required manual intervention to restart
- Unclear if work was saved/committed

**Possible causes:**
- Session timeout?
- Claude Code crash?
- Resource limit?

**Suggestion:**
- Add session health monitoring
- Auto-restart on unexpected termination
- Log session exit reasons


Merge: bd-d28c

branch: polecat/capable
target: main
source_issue: bd-d28c
rig: beads


Review and document rarely-used commands

Document use cases or consider deprecation for infrequently-used commands.

**Commands to review:**
1. bd rename-prefix - How often is this used? Document use cases
2. bd detect-pollution - Consider integrating into bd validate
3. bd migrate-hash-ids - One-time migration, keep but document as legacy

**For each command:**
- Document typical use cases
- Add examples to help text
- Consider if it should be a subcommand instead
- Add deprecation warning if appropriate

**Not changing:**
- duplicates ✓ (useful for data quality)
- repair-deps ✓ (useful for fixing broken refs)
- restore ✓ (critical for compacted issues)
- compact ✓ (performance feature)

**Deliverable:**
- Updated help text
- Documentation in ADVANCED.md
- Deprecation plan if needed


Work on beads-2vn: Add simple built-in beads viewer (GH#6...

Work on beads-2vn: Add simple built-in beads viewer (GH#654). Add bd list --pretty with --watch flag, tree view with priority/status symbols. When done, submit MR (not PR) to integration branch for Refinery.


Commit release

Stage and commit all version changes.

```bash
git add -A
git commit -m "chore: Bump version to 0.39.0"
```

Review the commit to ensure all expected files are included.


Add GetMoleculeProgress RPC endpoint

New RPC endpoint to get detailed progress for a specific molecule. Returns: moleculeID, title, assignee, and list of steps with their status (done/current/ready/blocked), start/close times. Used when user expands a worker in the activity feed TUI.


CLI cleanup: Consolidate bd top-level commands

## Problem
bd has 76 top-level commands, making it hard to discover and remember.

## Proposed Changes

### Remove from top-level (nest instead):
- `bd cook` → `bd formula cook` (cooking is a formula operation)
- `bd pin` → already covered by `bd mol` commands
- `bd thanks` → `bd info --thanks` or just README
- `bd quickstart` → `bd help quickstart` or docs
- `bd detect-pollution` → `bd doctor --check=pollution`

### Consolidate migrations under `bd migrate`:
- `bd migrate-hash-ids` → `bd migrate hash-ids`
- `bd migrate-issues` → `bd migrate issues`
- `bd migrate-sync` → `bd migrate sync`
- `bd migrate-tombstones` → `bd migrate tombstones`

### Consolidate admin under `bd admin`:
- `bd cleanup` → `bd admin cleanup`
- `bd compact` → `bd admin compact`
- `bd reset` → `bd admin reset`

## Backwards Compatibility
Keep old commands as hidden aliases for one release cycle.


Merge: bd-u2sc.3

branch: polecat/Modular
target: main
source_issue: bd-u2sc.3
rig: beads


Rename 'wisp' back to 'ephemeral' in beads API

The beads API uses 'wisp' terminology (Wisp field, bd wisp command) but the underlying SQLite column is 'ephemeral'.

This creates cognitive overhead since wisp is a Gas Town concept.

Rename to use 'ephemeral' consistently:
- types.Issue.Wisp → types.Issue.Ephemeral
- JSON field: wisp → ephemeral
- CLI: bd wisp → bd ephemeral (or just use flags on existing commands)

The SQLite column already uses 'ephemeral' so no schema migration needed.


Add tests for import/export functionality

Import/export functions like ImportIssues, exportToJSONLWithStore, and AutoImportIfNewer have low coverage. These are critical for data integrity and multi-repo synchronization.


Routing bypassed in daemon mode

## Bug

Prefix-based routing (routes.jsonl) only works in direct mode. When the daemon is running, it bypasses routing logic because:

1. Daemon mode resolves IDs via RPC (`daemonClient.ResolveID`)
2. Daemon uses its own store, which only knows about local beads
3. The routing logic in `resolveAndGetIssueWithRouting` is only called in direct mode

## Reproduction

```bash
# With daemon running:
cd ~/gt
bd show gt-1py3y  # Fails - daemon can't find it

# With daemon bypassed:
bd --no-daemon show gt-1py3y  # Works - uses routing
```

## Fix Options

### Option A: Client-side routing detection (Recommended)
Before calling daemon RPC, check if the ID prefix matches a route to a different beads dir. If so, use direct mode with routing for that ID.

```go
// In show.go, before daemon mode:
if daemonClient != nil && needsRouting(id) {
    // Fall back to direct mode for this ID
    result, err := resolveAndGetIssueWithRouting(ctx, store, id)
    ...
}
```

### Option B: Daemon-side routing
Add routing support to the daemon RPC server. More complex - daemon would need to:
- Load routes.jsonl on startup
- Open connections to multiple databases
- Route requests based on ID prefix

### Option C: Hybrid
Daemon returns "not found + prefix hint", client retries with routing.

## Recommendation

Option A is simplest. The client already has routing logic; just use it when we detect a routed prefix.


Command Set Standardization & Flag Consistency

Comprehensive improvements to bd command set based on 2025 audit findings.

## Background
See docs/command-audit-2025.md for detailed analysis.

## Goals
1. Standardize flag naming and behavior across all commands
2. Add missing flags for feature parity
3. Fix naming confusion
4. Improve consistency in JSON output

## Success Criteria
- All mutating commands support --dry-run (no --preview variants)
- bd update supports label operations
- bd search has filter parity with bd list
- Priority flags accept both int and P0-P4 format everywhere
- JSON output is consistent across all commands


test pin issue


Deacon Patrol

Mayor's daemon patrol loop for handling callbacks, health checks, and cleanup.


Add content-addressable identity to Issue type

**Summary:** Added content-addressable identity to Issue type by implementing a ContentHash field that generates a unique SHA256 fingerprint based on semantic issue content. This resolves issue identification challenges when multiple system instances create issues with identical IDs but different contents.

**Key Decisions:**
- Use SHA256 for content hashing
- Hash excludes ID and timestamps
- Compute hash automatically at creation/import time
- Add database column for hash storage

**Resolution:** Successfully implemented a deterministic content hashing mechanism that enables reliable issue identification across distributed systems, improving data integrity and collision detection.


Enhance bd doctor to suggest reset for broken states

Update bd doctor to detect severely broken states and suggest reset.

## Detection Criteria
Suggest reset when:
- Multiple unfixable errors detected
- Corrupted JSONL that can't be repaired
- Schema version mismatch that can't be migrated
- Daemon state inconsistent and unkillable

## Implementation
Add to doctor's check/fix flow:
```go
if unfixableErrors > threshold {
    suggest('State may be too broken to fix. Consider: bd reset')
}
```

## Output Example
```
✗ Found 5 unfixable errors

  Your beads state may be too corrupted to repair.
  Consider running 'bd reset' to start fresh.
  (Use 'bd reset --backup' to save current state first)
```

## Notes
- Don't auto-run reset, just suggest
- This is lower priority, can be done in parallel with main work


CLI API Audit for OSS Launch

Comprehensive CLI API audit before OSS launch.

## Tasks
1. Review gt command groupings - propose consolidation
2. Review bd command groupings
3. Document gt vs bd ownership boundaries
4. Identify naming inconsistencies
5. Document flag vs subcommand criteria

## Context
- Pre-OSS launch cleanup
- Goal: clean, consistent, discoverable CLI surface


Test agent with fields


Merge: bd-au0.7

branch: polecat/dementus
target: main
source_issue: bd-au0.7
rig: beads


Add composite index (issue_id, type) on dependencies table

GetBlockedIssues uses EXISTS clauses that filter by issue_id AND type together.

**Query pattern (ready.go:427-429):**
```sql
EXISTS (
  SELECT 1 FROM dependencies d2
  WHERE d2.issue_id = i.id AND d2.type = 'blocks'
)
```

**Problem:** Only idx_dependencies_issue exists. SQLite must filter type after index lookup.

**Solution:** Add migration:
```sql
CREATE INDEX IF NOT EXISTS idx_dependencies_issue_type ON dependencies(issue_id, type);
```

**Note:** This complements the existing idx_dependencies_depends_on_type for the reverse direction.


Add EntityRef type for structured entity references

Create EntityRef struct with Name, Platform, Org, ID fields. This is the foundation for HOP entity tracking. Can render as entity://hop/<platform>/<org>/<id> when needed. Add to internal/types/types.go.


GetBlockedIssues shows external deps as blocking even when satisfied

GetBlockedIssues (ready.go:385-493) shows external:* refs in the blocked_by list but doesn't check if they're actually satisfied using CheckExternalDep.

This can be confusing - an issue shows as blocked by external:project:capability even if that capability has been shipped (closed issue with provides: label exists).

Options:
1. Call CheckExternalDep for each external ref and filter satisfied ones from blocked_by
2. Add a note in output indicating external deps need lazy resolution
3. Document this is expected behavior (bd blocked shows all deps, bd ready shows resolved state)

Related: GetReadyWork correctly filters by external deps, but GetBlockedIssues doesn't.


Tier 1: Ephemeral repo routing

Simplified: Make mol spawn set ephemeral=true on spawned issues.

## The Fix

Modify cloneSubgraph() in template.go to set Ephemeral: true:

```go
// template.go:474
newIssue := &types.Issue{
    Title:      substituteVariables(oldIssue.Title, vars),
    // ... existing fields ...
    Ephemeral:  true,  // ADD THIS LINE
}
```

## Optional: Add --persistent flag

Add flag to bd mol spawn for when you want spawned issues to persist:

```bash
bd mol spawn mol-code-review --var pr=123  # ephemeral (default)
bd mol spawn mol-code-review --var pr=123 --persistent  # not ephemeral
```

## Why This Is Simpler Than Original Design

Original design proposed separate ephemeral repo routing. After code review:

- Ephemeral field already exists in schema
- bd cleanup --ephemeral already works
- No new config needed
- No multi-repo complexity

## Acceptance Criteria

- bd mol spawn creates issues with ephemeral=true
- bd cleanup --ephemeral -f deletes them after closing
- --persistent flag opts out of ephemeral
- Existing molecules continue to work


Code smell: Multiple CLI command files exceed 1000 lines

Several CLI command files are very large and could benefit from splitting:

| File | Lines | Notes |
|------|-------|-------|
| init.go | 1928 | Multiple init modes, contributor/team setup |
| show.go | 1592 | Display formatting, tree views, output modes |
| doctor.go | 1295 | Many health checks |
| sync.go | 1201 | Sync branch operations |
| compact.go | 1199 | Compaction logic |
| linear.go | 1190 | Linear integration |
| main.go | 1148 | Entry point and globals |

Consider:
1. Splitting init.go into init_core.go, init_contributor.go (already exists), init_team.go (already exists)
2. Moving show.go formatters to internal/ui package
3. Doctor checks could be individual files under doctor/ subpackage (already started)

Location: cmd/bd/*.go


Add covering index (label, issue_id) for label queries

GetIssuesByLabel joins labels table but requires table lookup after using idx_labels_label.

**Query (labels.go:165):**
```sql
SELECT ... FROM issues i
JOIN labels l ON i.id = l.issue_id
WHERE l.label = ?
```

**Problem:** Current idx_labels_label index doesn't cover issue_id, requiring row lookup.

**Solution:** Add migration:
```sql
CREATE INDEX IF NOT EXISTS idx_labels_label_issue ON labels(label, issue_id);
```

This is a covering index - query can be satisfied entirely from the index without touching the labels table rows.


Witness Patrol

Per-rig worker monitor patrol loop with progressive nudging.


Add test coverage for external dep edge cases

During code review of bd-zmmy, identified missing test coverage:

1. RemoveDependency with external ref target (will fail - see bd-a3sj)
2. GetBlockedIssues with mix of local and external blockers
3. GetDependencyTree with external deps
4. AddDependency cycle detection with external refs (should be skipped?)
5. External dep resolution with WAL mode database
6. External dep resolution when target project has no .beads directory
7. External dep resolution with invalid external: format variations

Priority 2 because bd-a3sj is a real bug that tests would catch.


Gate eval: Consider rate limiting for GitHub API calls

Each gate evaluation makes a network call to GitHub API via gh CLI. With many gates, this could hit API rate limits.

Future improvements:
1. Batch queries where possible
2. Add caching with TTL for recently-checked gates
3. Exponential backoff on rate limit errors

Low priority - unlikely to be an issue until we have many concurrent gates.


Push commit and create release tag.

Push commit and create release tag.

```bash
git push origin main
git tag v0.37.0
git push origin v0.37.0
```

This triggers GitHub Actions release workflow.

instantiated_from: bd-mol-xga
step: push-and-tag


Swarm status doesn't update after task completions

During swarm bd-784c, the swarm status remained at '9% (1/11 tasks merged)' even after 5 tasks were completed and closed.

**Observed:**
```
gt swarm status bd-784c
Progress: 9% (1/11 tasks merged)
```

But bd list showed 4+ issues closed:
- bd-j3dj, bd-kkka, bd-1tkd, bd-9btu all closed

**Expected:**
Swarm status should reflect actual completion count, either by:
1. Polling issue status from beads
2. Updating when polecats close issues
3. Updating when commits are pushed to integration branch

**Impact:**
Coordinator (me) had to manually check bd list to know actual progress.


gt swarm dispatch command not working

The 'gt swarm dispatch' command shown in help doesn't appear to work as expected.

**Observed:**
```
$ gt swarm dispatch bd-784c
[prints help text instead of dispatching]
```

**Expected:**
Should dispatch the next ready task from the epic to an available worker.

**Workaround:**
Had to manually use 'gt sling <issue> <polecat>' for each task dispatch.

**Impact:**
- Manual task dispatch defeats swarm automation
- Coordinator has to track which tasks are ready and which polecats are free

**Suggestion:**
Implement or fix 'gt swarm dispatch' to:
1. Find next unassigned task in epic
2. Find idle polecat in swarm
3. Sling task to polecat automatically


Add warning when staleness check errors

## Problem

When ensureDatabaseFresh() calls CheckStaleness() and it errors (corrupted metadata, permission issues, etc.), we silently proceed with potentially stale data.

**Location:** cmd/bd/staleness.go:27-32

**Scenarios:**
- Corrupted metadata table
- Database locked by another process
- Permission issues reading JSONL file
- Invalid last_import_time format in DB

## Current Code

```go
isStale, err := autoimport.CheckStaleness(ctx, store, dbPath)
if err \!= nil {
    // If we can't determine staleness, allow operation to proceed
    // (better to show potentially stale data than block user)
    return nil
}
```

## Fix

```go
isStale, err := autoimport.CheckStaleness(ctx, store, dbPath)
if err \!= nil {
    fmt.Fprintf(os.Stderr, "Warning: Could not verify database freshness: %v\n", err)
    fmt.Fprintf(os.Stderr, "Proceeding anyway. Data may be stale.\n\n")
    return nil
}
```

## Impact
Medium - users should know when staleness check fails

## Effort
Easy - 5 minutes


Update .claude-plugin/plugin.json to 0.30.4

Update version field in .claude-plugin/plugin.json:
```json
"version": "0.30.4"
```

```verify
jq -e '.version == "0.30.4"' .claude-plugin/plugin.json
```


Gate eval: Add error visibility for gh CLI failures

Currently evalGHRunGate and evalGHPRGate silently swallow errors when the gh CLI fails (lines 738-741, 780-783 in gate.go).

This makes debugging difficult - if gh isn't installed, auth fails, or network issues occur, gates silently stall forever with no indication of why.

Options:
1. Add debug logging when gh fails
2. Return error info in the skipped list for aggregate reporting
3. Add a --verbose flag to gate eval that shows failures

Low priority since the fail-safe behavior (don't close gate on error) is correct.


Issue lifecycle hooks (on-close, on-complete)

Add hooks that fire on issue state transitions, enabling automation like closing linked GitHub issues.

## Problem

We have `external_ref` to link beads issues to external systems (GitHub, Linear, Jira), but no mechanism to trigger actions when issues close. Currently:

```
bd-u2sc (external_ref: gh-692) closes → nothing happens
```

## Proposed Solution

### Phase 1: Shell Hooks

Add `.beads-hooks/on-close.sh` (and similar lifecycle hooks):

```bash
# .beads-hooks/on-close.sh
# Called by bd close with issue JSON on stdin
#\!/bin/bash
issue=$(cat)
external_ref=$(echo "$issue" | jq -r '.external_ref // empty')
if [[ "$external_ref" == gh-* ]]; then
    number="${external_ref#gh-}"
    gh issue close "$number" --repo steveyegge/beads \
      --comment "Completed via beads epic $(echo $issue | jq -r .id)"
fi
```

### Lifecycle Events

| Event | Trigger | Use Cases |
|-------|---------|-----------|
| `on-close` | Issue closed | Close external refs, notify, archive |
| `on-complete` | Epic children all done | Roll-up completion, close parent refs |
| `on-status-change` | Any status transition | Sync to external systems |

### Phase 2: Molecule Completion Handlers

Molecules could define completion actions:

```yaml
name: github-issue-tracker
on_complete:
  - action: shell
    command: gh issue close {{external_ref}} --repo {{repo}}
  - action: mail
    to: mayor/
    subject: "Epic {{id}} completed"
```

### Phase 3: Gas Town Integration

For full Gas Town deployments:
- Witness observes closures via beads events
- Routes to integration agents via mail
- Agents handle external system interactions

## Implementation Notes

- Hooks should be async (don't block bd close)
- Pass full issue JSON to hook via stdin
- Support hook timeout and failure handling
- Consider `--no-hooks` flag for bulk operations

## Related

- `external_ref` field already exists (GH#142)
- Cross-project deps: bd-h807, bd-d9mu
- Git hooks: .beads-hooks/ pattern established

## Use Cases

1. **GitHub integration**: Close GH issues when beads epic completes
2. **Linear sync**: Update Linear status when beads status changes
3. **Notifications**: Send mail/Slack when high-priority issues close
4. **Audit**: Log all closures to external system


Swarm: 13 beads backlog issues for polecat execution

## Swarm Overview

13 issues prepared for parallel polecat execution. All issues have been enhanced with concrete implementation guidance, file lists, and success criteria.

## Issue List

### Bug (1) - HIGH PRIORITY
| ID | Priority | Title |
|----|----------|-------|
| bd-phtv | P1 | Pinned field overwritten by subsequent commands |

### Test Coverage (3)
| ID | Package | Target |
|----|---------|--------|
| bd-io8c | internal/syncbranch | 27% → 70% |
| bd-thgk | internal/compact | 17% → 70% |
| bd-tvu3 | internal/beads | 48% → 70% |

### Code Quality (3)
| ID | Task |
|----|------|
| bd-qioh | FatalError pattern standardization |
| bd-rgyd | Split queries.go (1704 lines → 5 files) |
| bd-u2sc.3 | Split cmd/bd files (sync/init/show/compact) |

### Features (4)
| ID | Task |
|----|------|
| bd-au0.5 | Search date/priority filters |
| bd-ykd9 | Doctor --fix auto-repair |
| bd-g4b4 | Close hooks system |
| bd-likt | Gate daemon RPC |

### Polish (2)
| ID | Task |
|----|------|
| bd-4qfb | Doctor output formatting |
| bd-u2sc.4 | slog structured logging |

## Issue Details

All issues have been enhanced with:
- Concrete file lists to modify
- Code snippets and patterns
- Success criteria
- Test commands

Run `bd show <id>` for full details on any issue.

## Execution Notes

- All issues are independent (no blockers between them)
- bd-phtv (P1 bug) should get priority - affects bd pin functionality
- Test coverage tasks are straightforward but time-consuming
- File split tasks (bd-rgyd, bd-u2sc.3) are mechanical but important

## Completed During Prep

- bd-ucgz (P2 bug) - Fixed inline: external deps orphan check (commit f2db0a1d)
- Moved 5 gastown issues out of beads backlog (gt-dh65, gt-ng6g, gt-fqcz, gt-gswn, gt-rw2z)
- Deferred 4 premature/post-1.0 issues
- Closed bd-udsi epic (core implementation complete)


Deleted issues resurrect during bd sync (tombstones not propagating)

## Problem

When issues are deleted with bd delete --force, they get deleted from the local DB but resurrect during the next bd sync.

## Reproduction

1. Observe orphan warnings (bd-cb64c226.*, bd-cbed9619.*)
2. Delete them: bd delete bd-cb64c226.1 ... --force
3. Run bd sync
4. Orphan warnings reappear - issues were resurrected!

## Root Cause Hypothesis

The sync branch workflow (beads-sync) has the old state before deletions. When bd sync pulls from beads-sync and copies JSONL to main, the deleted issues are re-imported.

Tombstones may not be properly:
1. Written to beads-sync during export
2. Propagated during pull/merge
3. Honored during import

## Related

- bd-7b7h: chicken-and-egg sync.branch bug (same workflow)
- bd-ncwo: ID-based fallback matching to prevent ghost resurrection

## Files to Investigate

- cmd/bd/sync.go (export/import flow)
- internal/syncbranch/worktree.go (PullFromSyncBranch, copyJSONLToMainRepo)
- internal/importer/ (tombstone handling)


Test createTombstone and deleteIssue wrappers

Add tests for the createTombstone and deleteIssue wrapper functions in cmd/bd/delete.go.

## Functions under test
- createTombstone (cmd/bd/delete.go:335) - Wrapper around SQLite CreateTombstone
- deleteIssue (cmd/bd/delete.go:349) - Wrapper around SQLite DeleteIssue

## Test scenarios for createTombstone
1. Successful tombstone creation
2. Tombstone with reason and actor tracking
3. Error when issue doesn't exist
4. Verify tombstone status set correctly
5. Verify audit trail recorded
6. Rollback/error handling

## Test scenarios for deleteIssue
1. Successful issue deletion
2. Error on non-existent issue
3. Verify issue removed from database
4. Error handling when storage backend doesn't support delete

## Coverage target
Current: 0%
Target: >85%

## Related
- Parent epic: bd-kyll
- Original issue: bd-7z4


Code Review: PR #551 - Persist close_reason to issues table

Code review of PR #551 which fixes close_reason persistence bug.

## Summary
The PR correctly fixes a bug where close_reason was only stored in the events table, not in the issues.close_reason column. This caused `bd show --json` to return empty close_reason.

## What Was Fixed
- ✅ CloseIssue now updates both close_reason and closed_at
- ✅ ReOpenIssue clears both close_reason and closed_at
- ✅ Comprehensive tests added for both storage and CLI layers
- ✅ Clear documentation in queries.go about dual storage strategy

## Quality Assessment
✅ Tests cover both storage layer and CLI JSON output
✅ Handles reopen case (clearing close_reason)
✅ Good comments explaining dual-storage design
✅ No known issues

## Potential Followups
See linked issues for suggestions.


bd close --continue: auto-advance to next molecule step

Add --continue flag to bd close for seamless molecule step transitions.

## Usage

bd close <step-id> --continue [--no-auto]

## Behavior

1. Closes the specified step
2. Finds next ready step in same molecule (sibling/child)
3. By default, marks it in_progress (--no-auto to skip)
4. Outputs the transition

## Output

[done] Closed gt-abc.3: Implement feature

Next ready in molecule:
  gt-abc.4: Write tests

[arrow] Marked in_progress (use --no-auto to skip)

## If no next step

[done] Closed gt-abc.6: Exit decision

Molecule gt-abc complete! All steps closed.
Consider: bd mol squash gt-abc --summary '...'

## Key behaviors
- Detects parent molecule from closed step
- Finds next unblocked sibling
- Auto-claims by default (propulsion principle)
- Graceful handling when molecule is complete

## Gas Town integration
- gt-lz13: Update templates with nav workflow
- gt-um6q: Update docs with nav workflow


Add multi-repo target repo switching in bd create

In cmd/bd/create.go:164, there's a TODO to switch to the target repo for multi-repo support when creating issues. Currently the code may not properly handle creating issues in a different repo than the current one.

File: cmd/bd/create.go:164


Update git hooks

Install the updated hooks:
```bash
bd hooks install
```

Verify hook version:
```bash
grep 'bd-hooks-version' .git/hooks/pre-commit
```

```verify
grep -q 'bd-hooks-version: 0.30.4' .git/hooks/pre-commit 2>/dev/null || echo 'Hooks may not be installed - verify manually'
```


Performance Validation

Confirm no performance regression from cache removal


Integrate migration detection into bd doctor

Multiple migration commands (migrate_hash_ids.go, migrate_issues.go, migrate_sync.go, migrate_tombstones.go, migrate.go) have TODOs suggesting integration into 'bd doctor' for automatic migration detection. This would allow bd doctor to detect when migrations are needed and suggest running them.

Files:
- cmd/bd/migrate_hash_ids.go:24
- cmd/bd/migrate_issues.go:15
- cmd/bd/migrate_sync.go:16
- cmd/bd/migrate_tombstones.go:72
- cmd/bd/migrate.go:22


Remove Storage Cache from Server Struct

Eliminate cache fields and use s.storage directly


GH#519: bd sync fails when sync.branch is currently checked-out branch

bd sync tries to create worktree for sync.branch even when already on that branch. Should commit directly instead. See GitHub issue #519.


Upgrade beads-mcp to {{version}}

Upgrade the MCP server via pip:

```bash
pip install --upgrade beads-mcp
pip show beads-mcp | grep Version  # Verify {{version}}
```

Note: Restart Claude Code or MCP session to use new version.


Split large cmd/bd files into logical modules for maintainability.

## Current State
| File | Lines | Status |
|------|-------|--------|
| sync.go | 2203 | Too large |
| init.go | 1742 | Too large |
| show.go | 1419 | Too large |
| compact.go | 1190 | Borderline |

## Proposed Splits

### 1. sync.go (2203 lines) → 4 files

**sync.go** (~500 lines) - Main command and coordination
```go
var syncCmd = &cobra.Command{...}
func init() {...}
func doSync(...) {...}
```

**sync_export.go** (~400 lines) - Export operations
```go
func exportToJSONL(...)
func markDirtyAndScheduleFlush(...)
func flushPendingChanges(...)
```

**sync_import.go** (~500 lines) - Import operations
```go
func importFromJSONL(...)
func handleImportConflicts(...)
func mergeImportedIssues(...)
```

**sync_branch.go** (~400 lines) - Git branch operations
```go
func commitToSyncBranch(...)
func pullFromSyncBranch(...)
func handleSyncBranchDivergence(...)
```

### 2. init.go (1742 lines) → 3 files

**init.go** (~400 lines) - Main init command
```go
var initCmd = &cobra.Command{...}
func runInit(...)
func determinePrefix(...)
```

**init_wizard.go** (~500 lines) - Interactive setup
```go
func runContributorWizard(...)
func runTeamWizard(...)
func promptForConfig(...)
```

**init_hooks.go** (~400 lines) - Git hooks setup
```go
func installGitHooks(...)
func configureAutosync(...)
func setupMergeDriver(...)
```

### 3. show.go (1419 lines) → 3 files

**show.go** (~400 lines) - Main show command
```go
var showCmd = &cobra.Command{...}
func showIssue(...)
func showMultipleIssues(...)
```

**show_format.go** (~400 lines) - Output formatting
```go
func formatIssueText(...)
func formatIssueMarkdown(...)
func formatDependencyTree(...)
```

**show_threads.go** (~300 lines) - Thread/conversation display
```go
func showThread(...)
func formatThreadMessages(...)
```

### 4. compact.go (1190 lines) → 2 files

**compact.go** (~600 lines) - Main compact command
```go
var compactCmd = &cobra.Command{...}
func runCompact(...)
```

**compact_tiers.go** (~400 lines) - Tier-specific logic
```go
func compactTier1(...)
func compactTier2(...)
func squashWisps(...)
```

## Implementation Steps

1. **Start with sync.go** (largest file)
2. **Create new files** with same package declaration
3. **Move functions** maintaining related code together
4. **Update any file-local variables** that need to be shared
5. **Run tests** after each split:
   ```bash
   go test -short ./cmd/bd/...
   ```

## File Organization After Split
```
cmd/bd/
├── sync.go           (~500 lines)
├── sync_export.go    (~400 lines)
├── sync_import.go    (~500 lines)
├── sync_branch.go    (~400 lines)
├── init.go           (~400 lines)
├── init_wizard.go    (~500 lines)
├── init_hooks.go     (~400 lines)
├── show.go           (~400 lines)
├── show_format.go    (~400 lines)
├── show_threads.go   (~300 lines)
├── compact.go        (~600 lines)
└── compact_tiers.go  (~400 lines)
```

## Success Criteria
- No file > 600 lines
- All tests pass
- Related code stays together
- Clear file naming indicates purpose


Merge: bd-by0d

branch: polecat/furiosa
target: main
source_issue: bd-by0d
rig: beads


Refinery Patrol

Merge queue processor patrol loop with verification gates.


Create git tag v{{version}}

Create the release tag:

```bash
git tag v{{version}}
```

Verify: `git tag | grep {{version}}`


Work on gt-8tmz.34: Expansion var overrides not implement...

Work on gt-8tmz.34: Expansion var overrides not implemented. The ExpandRule.Vars field exists in internal/formula/types.go but is ignored during expansion in internal/formula/expand.go. Implement: 1) Pass rule.Vars to expandStep in ApplyExpansions, 2) Merge vars with formula defaults (rule.Vars wins), 3) Substitute vars in template placeholders, 4) Add test in expand_test.go. When done, commit and push to main.


test pin


bd import reports success but writes nothing to empty database

## Problem

In a fresh crew clone with no database, `bd import` and `bd sync --import-only` report:
```
Import complete: 0 created, 0 updated, 416 unchanged, 203 skipped
```

But the database remains empty:
```
sqlite3 .beads/beads.db 'SELECT COUNT(*) FROM issues'
0
```

## Reproduction Steps

1. Fresh clone (crew/dave) with .beads/issues.jsonl containing 619 issues
2. `bd init --skip-hooks` creates empty database
3. `bd import -i .beads/issues.jsonl` reports 416 unchanged
4. Database still has 0 issues

## Expected

Import should create 416 issues in the database.

## Root Cause Hypothesis

The 'unchanged' count suggests it's comparing against something (maybe in-memory state?) rather than the actual database. The daemon running from a different clone (mayor/rig) may be confusing the import logic.

## Context

Discovered during v0.39.0 release. Worked around by doing the release manually instead of using the beads-release molecule.


bd pin: pinned field overwritten by subsequent bd commands

## Summary

The `bd pin` command correctly sets `pinned=1` in SQLite, but any subsequent `bd` command (including read-only commands like `bd show`) resets `pinned` to 0.

## Reproduction Steps

```bash
bd --no-daemon pin <issue-id> --for=max
sqlite3 .beads/beads.db "SELECT id, pinned FROM issues WHERE id=\"<issue-id>\""
# Shows pinned=1 ✓

bd --no-daemon show <issue-id> --json
sqlite3 .beads/beads.db "SELECT id, pinned FROM issues WHERE id=\"<issue-id>\""
# Shows pinned=0 ✗ WRONG
```

## Root Cause Investigation

### Prime Suspects

1. **JSONL import overwrites DB** - The `pinned` field has `omitempty` so false values arent in JSONL. When JSONL is imported, it overwrites the DB pinned=1 with default pinned=0.

2. **Files to check:**
   - `internal/importer/importer.go` - ImportIssue() may unconditionally set all fields
   - `internal/storage/sqlite/issues.go` - UpsertIssue() may not preserve pinned
   - `cmd/bd/main.go` - ensureStoreActive() may trigger import

### Debug Steps

```bash
# Add debug logging to track what is writing pinned=0
grep -rn "pinned" internal/storage/sqlite/*.go
grep -rn "Pinned" internal/importer/*.go
```

## Likely Fix

In `internal/importer/importer.go` or `internal/storage/sqlite/issues.go`:

```go
// When upserting from JSONL, preserve pinned field if already set
func (s *SQLiteStorage) UpsertIssue(ctx context.Context, issue *types.Issue) error {
    // Check if issue exists and is pinned
    existing, _ := s.GetIssue(ctx, issue.ID)
    if existing != nil && existing.Pinned && !issue.Pinned {
        // Preserve existing pinned status
        issue.Pinned = existing.Pinned
    }
    // ... rest of upsert
}
```

OR the import should skip fields that are omitempty and not present in JSONL:

```go
// In importer, only update fields that are explicitly set in JSONL
// Pinned with omitempty means absent = dont change, not absent = false
```

## Testing

```bash
# After fix:
bd --no-daemon pin <issue-id> --for=max
bd --no-daemon show <issue-id> --json  # Should not reset pinned
bd list --pinned  # Should show the pinned issue
bd hook --agent max  # Should show pinned work
```

## Files to Modify

1. **internal/importer/importer.go** - Preserve pinned on import
2. **internal/storage/sqlite/issues.go** - UpsertIssue preserve pinned
3. **Add test** in internal/importer/importer_test.go

## Success Criteria
- `bd pin` survives subsequent bd commands
- `bd list --pinned` shows pinned issues
- `bd hook --agent X` shows pinned work
- Existing tests still pass


bd create -f crashes with nil pointer dereference

GitHub issue #674. The markdown import feature crashes at markdown.go:338 because global variables (store, ctx, actor) aren't initialized when createIssuesFromMarkdown is called. The function uses globals set by cobra command framework but is being called before they're ready. Need to either initialize globals at start of function or pass them as parameters.


Deacon Patrol

Mayor's daemon patrol loop for handling callbacks, health checks, and cleanup.


Wait for CI

Monitor GitHub Actions for release completion.

https://github.com/steveyegge/beads/actions

Expected time: 5-10 minutes

Watch for:
- Build artifacts (all platforms)
- Test suite pass
- npm publish
- PyPI publish


Test agent bead

Testing new agent type


Fix JSON errors in show.go (update/close/edit commands)

Replace ~51 direct stderr writes with FatalErrorRespectJSON() in show.go.

Commands affected:
- updateCmd (~10 error handlers)
- closeCmd (~15 error handlers)
- editCmd (~10 error handlers)
- showCmd (already uses FatalErrorRespectJSON in some places)

Key error paths:
- ID resolution errors (lines 565, 570, 579)
- Validation errors (lines 474, 515, 524, 545)
- RPC/daemon errors (line 639+)
- Store operation errors


Test pinned issue


Add tests for dependency management

Key dependency functions like mergeBidirectionalTrees, GetDependencyTree, and DetectCycles have low or no coverage. These are essential for maintaining data integrity in the dependency graph.


Code review: bd mol bond --ref and bd activity (bd-xo1o work)

Review dave's recent commits for bd-xo1o (Dynamic Molecule Bonding):

## Commits to Review
- ee04b1ea: feat: add dynamic molecule bonding with --ref flag (bd-xo1o.1)
- be520d90: feat: add bd activity command for real-time state feed (bd-xo1o.3)

## Review Focus
1. Code quality and correctness
2. Error handling
3. Edge cases
4. Test coverage
5. Documentation

## Deliverables
- File beads for any issues found
- Note any concerns or suggestions
- Verify the implementation matches the bd-xo1o epic requirements


Add missing updated_at index on issues table

GetStaleIssues queries filter by updated_at but there's no index on this column.

**Current query (ready.go:253-254):**
```sql
WHERE status != 'closed'
  AND datetime(updated_at) < datetime('now', '-' || ? || ' days')
```

**Problem:** Full table scan when filtering stale issues.

**Solution:** Add migration to create:
```sql
CREATE INDEX IF NOT EXISTS idx_issues_updated_at ON issues(updated_at);
```

**Note:** The datetime() function wrapper may prevent index usage. Consider also storing updated_at as INTEGER (unix timestamp) for better index efficiency, or test if SQLite can use the index despite the function.


Add pinned field to issue schema

Add boolean 'pinned' field to the issue schema. When true, the issue is marked as a persistent context marker that should not be treated as a work item.


Pinned field available in beads v0.37.0

Hey max,

Heads up on your mail overhaul work:

1. **Pinned field is available** - beads v0.37.0 (released by dave earlier) includes the pinned field on issues. You'll want to add this to BeadsMessage in types.go.

2. **Database migration** - Check if existing .beads databases need migration to support the pinned field. Run `bd doctor` to see if it flags anything.

3. **Sorting task** - Once you have the pinned field, gt-ngu1 (pinned beads first in mail inbox) needs implementing. Since messages now come from `bd list --type=message`, you'll need to either:
   - Sort in listBeads() after fetching, or
   - Ensure bd list returns pinned items first (may already do this?)

Check what version of bd you're building against.

-- Mayor


Restart daemons

Restart bd daemons to pick up new version.

```bash
bd daemons killall
```

Daemons will auto-restart with new version on next bd command.

Verify:
```bash
bd daemons list
```


Consolidate duplicate path-finding utilities (findJSONLPath, findBeadsDir, findGitRoot)

Code health review found these functions defined in multiple places:

- findJSONLPath() in autoflush.go:45-73 and doctor/fix/migrate.go
- findBeadsDir() in autoimport.go:197-239 (with git worktree handling)
- findGitRoot() in autoimport.go:242-269 (Windows path conversion)

The beads package has public FindBeadsDir() and FindJSONLPath() APIs that should be used consistently.

Impact: Bug fixes need to be applied in multiple places. Git worktree handling may not be replicated everywhere.

Fix: Consolidate all implementations to use the beads package APIs. Remove duplicates.


gt handoff deadlock at handoff.go:125

When running 'gt handoff -m "message"' after successful MR submit, go panics with 'fatal error: all goroutines are asleep - deadlock\!' at handoff.go:125. The shutdown request still appears to be sent successfully but the command crashes. Stack trace shows issue is in runHandoff select statement.


Warn on invalid depends_on references in workflow templates

workflow.go:780-781 silently skips invalid dependency names. Should log a warning when a depends_on reference doesn't match any task ID in the template.


Merge: bd-l13p

branch: polecat/nux
target: main
source_issue: bd-l13p
rig: beads


Improve test coverage for internal/beads (48.1% → 70%)

Improve test coverage for internal/beads package from 48% to 70%.

## Current State
- Coverage: 48.4%
- Files: beads.go, fingerprint.go
- Tests: beads_test.go (moderate coverage)

## Functions Needing Tests

### beads.go (database discovery)
- [ ] followRedirect - needs redirect file tests
- [ ] findDatabaseInBeadsDir - needs various dir structures
- [x] NewSQLiteStorage - likely covered
- [ ] FindDatabasePath - needs BEADS_DB env var tests
- [ ] hasBeadsProjectFiles - needs file existence tests
- [ ] FindBeadsDir - needs directory traversal tests
- [ ] FindJSONLPath - needs path derivation tests
- [ ] findGitRoot - needs git repo tests
- [ ] findDatabaseInTree - needs nested directory tests
- [ ] FindAllDatabases - needs multi-database tests
- [ ] FindWispDir - needs wisp directory tests
- [ ] FindWispDatabasePath - needs wisp path tests
- [ ] NewWispStorage - needs wisp storage tests
- [ ] EnsureWispGitignore - needs gitignore creation tests
- [ ] IsWispDatabase - needs path classification tests

### fingerprint.go (repo identification)
- [ ] ComputeRepoID - needs various remote URL tests
- [ ] canonicalizeGitURL - needs URL normalization tests
- [ ] GetCloneID - needs clone identification tests

## Implementation Guide

1. **Use temp directories:**
   ```go
   func TestFindBeadsDir(t *testing.T) {
       tmpDir := t.TempDir()
       beadsDir := filepath.Join(tmpDir, ".beads")
       os.MkdirAll(beadsDir, 0755)

       // Create test files
       os.WriteFile(filepath.Join(beadsDir, "beads.db"), []byte{}, 0644)

       // Change to tmpDir and test
       oldWd, _ := os.Getwd()
       os.Chdir(tmpDir)
       defer os.Chdir(oldWd)

       result := FindBeadsDir()
       assert.Equal(t, beadsDir, result)
   }
   ```

2. **Test scenarios:**
   - BEADS_DB environment variable set
   - .beads/ in current directory
   - .beads/ in parent directory
   - Redirect file pointing elsewhere
   - No beads directory found
   - Wisp directory alongside main beads

3. **Git remote URL tests:**
   ```go
   tests := []struct{
       input    string
       expected string
   }{
       {"git@github.com:user/repo.git", "github.com/user/repo"},
       {"https://github.com/user/repo", "github.com/user/repo"},
       {"ssh://git@github.com/user/repo.git", "github.com/user/repo"},
   }
   ```

## Success Criteria
- Coverage ≥ 70%
- All FindXxx functions have tests
- Environment variable handling tested
- Edge cases (missing dirs, redirects) covered

## Run Tests
```bash
go test -v -cover ./internal/beads
go test -race ./internal/beads
```


Ghost resurrection: remote status:closed wins during git merge

During bd sync, the 3-way git merge sometimes keeps remote's status:closed instead of local's status:tombstone. This causes ghost issues to resurrect even when tombstones exist.

Root cause: Git 3-way merge doesn't understand tombstone semantics. If base had closed, local changed to tombstone, and remote has closed, git might keep remote's version.

The early tombstone check in importer.go only prevents CREATION when tombstones exist in DB. But if applyDeletionsFromMerge hard-deletes the tombstones before import runs (because they're not in the merged result), the check doesn't help.

Potential fixes:
1. Make tombstones 'win' in the beads merge driver (internal/merge/merge.go)
2. Don't hard-delete tombstones in applyDeletionsFromMerge if they're in the DB
3. Export tombstones to a separate file that's not subject to merge

Ghost issues: bd-cb64c226.*, bd-cbed9619.*


Consolidate migrate-* commands under bd migrate

## Task
Move standalone migrate commands under `bd migrate` parent:
- `bd migrate-hash-ids` → `bd migrate hash-ids`
- `bd migrate-issues` → `bd migrate issues`
- `bd migrate-sync` → `bd migrate sync`
- `bd migrate-tombstones` → `bd migrate tombstones`

## Implementation

### 1. Update migrate.go
Add subcommands to migrateCmd:
```go
func init() {
    migrateCmd.AddCommand(migrateHashIDsCmd)
    migrateCmd.AddCommand(migrateIssuesCmd)
    migrateCmd.AddCommand(migrateSyncCmd)
    migrateCmd.AddCommand(migrateTombstonesCmd)
}
```

### 2. Update each migrate_*.go file
- Change `Use:` from `migrate-foo` to `foo`
- Remove `rootCmd.AddCommand()` from init()

### 3. Create hidden aliases for backwards compatibility
In main.go, add hidden top-level commands that forward to subcommands.

### 4. Update docs
- docs/DELETIONS.md - references `bd migrate-tombstones`
- docs/CLI_REFERENCE.md - migration section

## Files to modify
- cmd/bd/migrate.go
- cmd/bd/migrate_hash_ids.go
- cmd/bd/migrate_issues.go
- cmd/bd/migrate_sync.go
- cmd/bd/migrate_tombstones.go
- cmd/bd/main.go (aliases)


Rebuild local binary

Build and verify: go build -o bd ./cmd/bd && ./bd version


Document sync.branch 'always dirty' working tree behavior

## Context

When sync.branch is configured, the .beads/issues.jsonl file in main's working tree is ALWAYS dirty. This is by design:

1. bd sync commits to beads-sync branch (via worktree)
2. bd sync copies JSONL to main's working tree (so CLI commands work)
3. This copy is NOT committed to main (to reduce commit noise)

Contributors who watch main branch history pushed for sync.branch to avoid constant beads commit noise. But users need to understand the trade-off.

## Documentation Needed

Update README.md sync.branch section with:

1. **Clear explanation** of why .beads/ is always dirty on main
2. **"Be Zen about it"** - this is expected, not a bug
3. **Workflow options:**
   - Accept dirty state, use `bd sync --merge` periodically to snapshot to main
   - Or disable sync.branch if clean working tree is more important
4. **Shell alias tip** to hide beads from git status:
   ```bash
   alias gs='git status -- ":!.beads/"'
   ```
5. **When to merge**: releases, milestones, or periodic snapshots

## Related

- bd-7b7h: Fix that allows bd sync --merge to work with dirty .beads/
- bd-elqd: Investigation that identified this as expected behavior


Merge: bd-uqfn

branch: polecat/cheedo
target: main
source_issue: bd-uqfn
rig: beads


Detect/prevent child→parent dependency anti-pattern

## Problem

When filing issues with dependencies, it's easy to fall into the "temporal trap":
- Thinking "Phase 1 comes before Phase 2"
- Writing `bd dep add phase1 phase2`
- But that means "phase1 depends on phase2" (backwards!)

A specific variant: children depending on their parent epic. This is ALWAYS wrong because:
1. Parent-child relationship already captures the dependency (parent closes when children done)
2. Child→parent dep creates a block: child can't start because parent is "open"
3. Parent can't close because children aren't done
4. Deadlock

## Solution

### 1. Prevent at creation (`bd dep add`)

When user runs `bd dep add X Y`:
- Check if X is a child of Y (X.id starts with Y.id + ".")
- If so, error: "Cannot add dependency: X is already a child of Y. Children inherit dependency on parent completion via hierarchy."

### 2. Detect in `bd doctor`

Add a check that finds all cases where:
- Issue A depends on Issue B
- A.id matches pattern B.id + ".*" (A is child of B)

Report as: "Child→parent dependency detected (anti-pattern)"
Offer repair: "Remove N backwards dependencies? [y/N]"

## Implementation

- `dep_add.go`: Add parent-child check before adding dependency
- `doctor.go`: Add backwards-dep detection to health checks


Graph Link: supersedes for version chains

Implement supersedes link type for version tracking.

New command:
- bd supersede <id> --with <new> - marks id as superseded by new
- Auto-closes the superseded issue

Query support:
- bd show <id> shows 'Superseded by: <new>'
- bd show <new> shows 'Supersedes: <id>'
- bd list --superseded shows version chains

Storage:
- superseded_by column pointing to replacement issue

Useful for design docs, specs, and evolving artifacts.


Code Review: Beads Refactoring Sprint

Epic for code smell fixes identified during Beads code review.

## Scope
11 issues covering:
- P2: Duplicated code in cook.go (2 issues)
- P3: Long functions and God Objects (5 issues)
- P4: Technical debt and cleanup (4 issues)

## Approach
Swarm with polecats, each taking 1-2 issues. All changes should:
1. Pass existing tests
2. Not change external behavior
3. Improve code maintainability

## Success Criteria
All 11 child issues closed with passing CI.


Install 0.30.4 MCP server locally

Upgrade the MCP server (after PyPI publish):
```bash
pip install --upgrade beads-mcp
# OR if using uv:
uv tool upgrade beads-mcp
```

Verify:
```bash
pip show beads-mcp | grep Version
```

```verify
pip show beads-mcp 2>/dev/null | grep -q 'Version: 0.30.4'
```


.beads-ephemeral/ storage backend

Implement ephemeral storage layer for wisps.

## Requirements
- New storage location: .beads-ephemeral/issues.jsonl (sibling to .beads/)
- Gitignored by default (add to .beads/.gitignore)
- Same JSONL format as regular beads
- Config option: ephemeral.directory (relative path)
- ephemeral.enabled config flag

## Storage Behavior
- Ephemeral issues have `ephemeral: true` field
- No sync to remote (local only)
- No daemon tracking needed (transient)

## Implementation
- Add EphemeralStore in storage package
- Initialize on demand when --ephemeral flag used
- Share Issue struct, just different storage path


Move pour/ephemeral under bd mol subcommand

For consistency, bd pour and bd ephemeral should become bd mol pour and bd mol ephemeral:

Current:
  bd mol list                  # Available protos
  bd mol show <id>             # Proto details
  bd pour <proto>              # Create mol ← sticks out
  bd ephemeral <proto>         # Create ephemeral ← sticks out
  bd mol bond <proto> <parent> # Attach to existing mol
  bd mol squash <id>           # Condense to digest
  bd mol burn <id>             # Discard

Proposed:
  bd mol list
  bd mol show <id>
  bd mol pour <proto>          # Moved under mol
  bd mol ephemeral <proto>     # Moved under mol
  bd mol bond <proto> <parent>
  bd mol squash <id>
  bd mol burn <id>

All molecule operations should be under bd mol for discoverability and consistency.


Create version-bump template as native Beads

Migrate the version-bump workflow from YAML to a native Beads template:

1. Create epic with template label: Release {{version}}
2. Create child tasks for each step (update version files, changelog, commit, push, publish)
3. Set up dependencies between tasks
4. Add verification commands in task descriptions

This serves as both migration and validation of the new system.


Update local binary

cp ./bd ~/.local/bin/bd


Fix daemon/direct mode inconsistency in relate and duplicate commands

The relate.go and duplicate.go commands have inconsistent daemon/direct mode handling:

When daemonClient is connected, they resolve IDs via RPC but then perform updates directly via store.UpdateIssue(), bypassing the daemon.

Affected locations:
- relate.go:125-139 (runRelate update)
- relate.go:235-246 (runUnrelate update)
- duplicate.go:120 (runDuplicate update)
- duplicate.go:207 (runSupersede update)

Should either use RPC for updates when daemon is running, or document why direct access is intentional.


Refactor sync_test to use direct import logic

In cmd/bd/sync_test.go:444, there's a TODO to refactor the test to use direct import logic instead of subprocess calls. This would make the test more reliable and faster.

File: cmd/bd/sync_test.go:444


GH#405: Fix prefix parsing with hyphens - multi-hyphen prefixes parsed incorrectly

Fixed: ExtractIssuePrefix was falling back to first-hyphen for word-like suffixes, breaking multi-hyphen prefixes like 'hacker-news' and 'me-py-toolkit'.


Create release tag

Create annotated git tag.

```bash
git tag -a v0.39.0 -m "Release v0.39.0"
```

Verify: `git tag -l | tail -5`


bd sync fails with orphaned issues and duplicate ID conflict

After fixing the deleted_at TEXT column scanning bug (commit 18b1eb2), bd sync still fails with two issues:

1. Orphan Detection Warning: 12 orphaned child issues whose parents no longer exist (bd-cb64c226.* and bd-cbed9619.*)

2. Import Failure: UNIQUE constraint failed for bd-360 - this tombstone exists in both DB and JSONL

Error: "Import failed: error creating depth-0 issues: bulk insert issues: failed to insert issue bd-360: sqlite3: constraint failed: UNIQUE constraint failed: issues.id"

Fix options:
- Delete orphaned child issues with bd delete
- Resolve bd-360 duplicate (in deletions.jsonl vs tombstone in DB)
- Reset sync branch: git branch -f beads-sync main && git push --force-with-lease origin beads-sync

Fixed tombstone constraint violation bug. When deleting closed issues, the CHECK constraint (status = 'closed') = (closed_at IS NOT NULL) was violated because CreateTombstone didn't clear closed_at. Fix: set closed_at = NULL in tombstone creation SQL.

The sync data corruption (orphaned issues in beads-sync branch) requires manual cleanup: reset sync branch with 'git branch -f beads-sync main && git push --force-with-lease origin beads-sync'


gt nudge doesn't work with crew addresses

## Bug

`gt nudge beads/crew/dave "message"` fails because it uses the polecat session manager which produces wrong session names.

## Expected
Session name: `gt-beads-crew-dave` (hyphen)

## Actual
Session name: `gt-beads-crew/dave` (slash, from polecat manager)

## Root Cause

In nudge.go line 46-57:
```go
rigName, polecatName, err := parseAddress(target)  // beads, crew/dave
sessionName := mgr.SessionName(polecatName)        // gt-beads-crew/dave (WRONG)
```

Should detect `crew/` prefix in polecatName and use `crewSessionName(rigName, crewName)` instead.

## Fix

```go
if strings.HasPrefix(polecatName, "crew/") {
    crewName := strings.TrimPrefix(polecatName, "crew/")
    sessionName = crewSessionName(rigName, crewName)
} else {
    sessionName = mgr.SessionName(polecatName)
}
```


Merge: bd-9usz

branch: polecat/slit
target: main
source_issue: bd-9usz
rig: beads


HANDOFF: Molecule bonding - spawn done, bond next

## Context

Continuing work on bd-o5xe (Molecule bonding epic).

## Completed This Session

- bd-mh4w: Renamed bond to spawn in mol.go
- bd-rnnr: Added BondRef data model to types.go

## Now Unblocked

1. bd-o91r: Polymorphic bond command [P1]
2. bd-iw4z: Compound visualization [P2]
3. bd-iq19: Distill command [P2]

## Key Files

- cmd/bd/mol.go
- internal/types/types.go

## Next Step

Start with bd-o91r. Run bd show bd-o5xe for context.


Merge: bd-ykd9

branch: polecat/Doctor
target: main
source_issue: bd-ykd9
rig: beads


Phase 2.5: TOON-based daemon sync

Implement TOON-native daemon sync (replaces JSONL sync machinery).

## Overview
Daemon sync is the final integration point. Replace export/import/merge machinery with TOON-native sync, building on deletion tracking (2.3) and merge optimization (2.4).

## Required Work

### 2.5.1 TOON-based Daemon Sync
- [ ] Understand current JSONL sync machinery (export.go, import.go, merge.go)
- [ ] Replace export step with TOON encoding (EncodeTOON)
- [ ] Replace import step with TOON decoding (DecodeTOON)
- [ ] Replace merge step with TOON-aware 3-way merge
- [ ] Update daemon auto-sync to read/write TOON
- [ ] Verify 5-second debounce still works

### 2.5.2 Deletion Sync Integration
- [ ] Load deletions.toon during import phase
- [ ] Apply deletions after merging issues
- [ ] Ensure deletion TTL respects daemon schedule

### 2.5.3 Testing
- [ ] Unit tests for daemon sync with TOON
- [ ] Integration tests with actual daemon operations
- [ ] Multi-clone sync scenarios with concurrent edits
- [ ] Performance comparison with JSONL sync
- [ ] Long-running daemon stability tests

## Success Criteria
- Daemon reads/writes TOON format (not JSONL)
- Sync latency comparable to JSONL (<100ms)
- All 70+ tests passing
- bdt commands work seamlessly with daemon
- Multi-clone sync scenarios work correctly


Relocate thanks command to bd info --thanks

## Task
Move `bd thanks` → `bd info --thanks`

## Implementation

### 1. Update info.go
- Add `--thanks` flag
- Import thanks.go display logic
- When --thanks flag set, call thanks display function

### 2. Update thanks.go
- Export the display function (rename to public)
- Remove rootCmd.AddCommand()
- Optionally keep as hidden alias

### 3. Update docs
- README.md if mentioned
- CHANGELOG.md - deprecation notice

## Files to modify
- cmd/bd/info.go
- cmd/bd/thanks.go


Digest: Version Bump: test-squash

## Molecule Execution Summary

**Molecule**: Version Bump: test-squash
**Steps**: 8

**Completed**: 0/8

---

### Steps

1. **[open]** Verify release artifacts
   Check GitHub releases page - binaries for darwin/linux/windows should be available

2. **[open]** Commit and push release
   git add -A && git commit && git push to trigger CI

3. **[open]** Update CHANGELOG.md with release notes
   Add meaningful release notes to CHANGELOG.md describing what changed in test-squash

4. **[open]** Wait for CI to pass
   Monitor GitHub Actions - all checks must pass before release artifacts are built

5. **[open]** Restart running daemons
   Kill and restart any running bd daemons to pick up new version: pkill -f 'bd daemon' && bd daemon --start

6. **[open]** Update local installation
   Run install script or brew upgrade to get new version locally: curl -fsSL .../install.sh | bash

7. **[open]** Run bump-version.sh test-squash
   Run ./scripts/bump-version.sh test-squash to update version in all files

8. **[open]** Update info.go versionChanges
   Add entry to versionChanges in cmd/bd/info.go with agent-actionable changes for test-squash


Merge: bd-gqxd

branch: polecat/furiosa
target: main
source_issue: bd-gqxd
rig: beads


bd formula add: Import formula to local catalog

Import a formula file to the local catalog (search path).

**Replaces**: "bd mol promote" (proto-to-proto concept is obsolete with ephemeral protos)

## Usage
```bash
# Add a formula file to project catalog
bd formula add my-workflow.formula.json

# Add to user-level catalog
bd formula add my-workflow.formula.json --scope user

# Add from URL
bd formula add https://example.com/workflow.formula.json
```

## Implementation
1. Parse the formula file (validate JSON structure)
2. Determine target directory based on scope:
   - project: .beads/formulas/
   - user: ~/.beads/formulas/
   - town: ~/gt/.beads/formulas/
3. Copy/download formula to target
4. Verify it is loadable: bd formula show <name>

## Flags
- `--scope <level>` - Where to add (project|user|town, default: project)
- `--name <name>` - Override formula name (default: from file)

## Note
This is for manually adding formulas. For GitHub-hosted formulas, use:
  bd mol install github.com/org/formula-name


Merge: bd-ao0s

branch: polecat/rictus
target: main
source_issue: bd-ao0s
rig: beads


bd mail uses git user.name for sender instead of BEADS_AGENT_NAME

When sending mail via `bd mail send`, the sender field in the stored issue uses git config user.name instead of the BEADS_AGENT_NAME environment variable.

Reproduction:
1. Set BEADS_AGENT_NAME=gastown-alpha
2. Run: bd mail send mayor/ -s 'Test' -m 'Body'
3. Check the issue.jsonl: sender is 'Steve Yegge' (git user.name) not 'gastown-alpha'

Expected: The sender field should use BEADS_AGENT_NAME when set.

This breaks the mail system for multi-agent workflows where agents need to identify themselves by their role (polecat, refinery, etc.) rather than the human user's git identity.

Related: gt mail routing integration with Gas Town


bd sync deleted non-.beads files (skills/beads/*)

On 2025-12-23, commit 7b671662 (bd sync) inadvertently deleted 5 files from skills/beads/ that were added by PR #722 (commit e432fcc8). These files are outside .beads/ and should never be touched by bd sync.

Files deleted:
- skills/beads/README.md
- skills/beads/references/INTEGRATION_PATTERNS.md
- skills/beads/references/MOLECULES.md
- skills/beads/references/PATTERNS.md
- skills/beads/references/TROUBLESHOOTING.md

Investigation needed:
1. How did bd sync stage/commit files outside .beads/?
2. Was this a one-time accident or is there a systematic bug?
3. Add safeguards to prevent bd sync from touching non-.beads paths

Reported via GH#738.


Update version to {{version}} in version.go

Edit cmd/bd/version.go line 17:

```go
Version = "{{version}}"
```

Verify with: `grep 'Version =' cmd/bd/version.go`


Support --reason flag in daemon mode for reopen command

The reopen.go command has a TODO at line 61 to add reason as a comment once RPC supports AddComment. Currently --reason flag is ignored in daemon mode with a warning.


Update CHANGELOG.md

Write the [Unreleased] section with all changes for 0.39.0.

Format: Keep a Changelog (https://keepachangelog.com)

Sections:
- ### Added
- ### Changed
- ### Fixed
- ### Documentation

The bump script will stamp the date automatically.


Support redirect files in .beads/ directory

Gas Town creates polecat worktrees with .beads/redirect files that point to a shared beads database. The bd CLI should:

1. When finding a .beads/ directory, check if it contains a 'redirect' file
2. If redirect exists, read the relative path and use that as the beads directory
3. This allows multiple git worktrees to share a single beads database

Example:
- polecats/alpha/.beads/redirect contains '../../mayor/rig/.beads'
- bd commands from alpha should use mayor/rig/.beads

Currently bd ignores redirect files and either uses the local .beads/ or walks up to find a parent .beads/.

Related: gt-nriy (test message that can't be retrieved due to missing redirect support)


Correction: Pinned field already in v0.31.0

Quick correction - the Pinned field is already in the current bd v0.31.0:

```go
// In beads internal/types/types.go
Pinned bool `json:"pinned,omitempty"`
```

So you just need to:
1. Add `Pinned bool `json:"pinned,omitempty"`` to BeadsMessage in types.go
2. Sort pinned messages first in listBeads() after fetching

No migration needed - the field is already there.

-- Mayor


bump-version.sh should detect pre-staged release notes

When running the release workflow, I staged CHANGELOG.md and info.go changes before running bump-version.sh. The script:

1. Warned about uncommitted changes (correct)
2. Required stash/pop to proceed
3. After pop, the [Unreleased] header wasn't converted to version/date

The script could be smarter:
- Detect if staged changes are to CHANGELOG.md/info.go (expected for releases)
- Or provide a --allow-staged flag
- Or at minimum, re-apply the [Unreleased] → [X.Y.Z] transformation after detecting manual edits

Workaround: manually edit [Unreleased] to [0.39.1] - 2025-12-27 after stash pop.


Consolidate daemon/daemons commands

Merge daemons functionality into daemon command with subcommands. Currently have both 'daemon' and 'daemons' at top level.


Add git operations for --hard reset

Implement git integration for hard reset mode.

## Operations Needed
1. `git rm -rf .beads/*.jsonl` - remove data files from index
2. `git commit -m 'beads: reset to clean state'` - commit removal
3. After re-init: `git add .beads/` and commit fresh state

## Edge Cases to Handle
- Uncommitted changes in .beads/ - warn or error
- Detached HEAD state - warn, maybe block
- Git not initialized - skip git ops, warn
- Git operations fail mid-way - clear error messaging

## Interface
```go
type GitState struct {
    IsRepo       bool
    IsDirty      bool   // uncommitted changes in .beads/
    IsDetached   bool   // detached HEAD
    Branch       string // current branch name
}

func CheckGitState(beadsDir string) (*GitState, error)
func GitRemoveBeads(beadsDir string) error
func GitCommitReset(message string) error
func GitAddAndCommit(beadsDir, message string) error
```

## Location
`internal/reset/git.go` - keep with reset package for now

Note: Codebase has no central git package. internal/compact/git.go is compact-specific.
Future refactoring could extract shared git utilities, but YAGNI for now.


Auto-migrate database on CLI version bump

When CLI is upgraded (e.g., 0.24.0 → 0.24.1), database version becomes stale. Add auto-migration in PersistentPreRun or daemon startup. Check dbVersion != CLIVersion and run bd migrate automatically. Fixes recurring UX issue where bd doctor shows version mismatch after every CLI upgrade.


bd delete --from-file should add deleted issues to deletions manifest

When using bd delete --from-file to bulk delete issues, the deleted issue IDs are not being added to the deletions.jsonl manifest.

This causes those issues to be resurrected during bd sync when git history scanning finds them in old commits.

Expected: All deleted issues should be added to deletions.jsonl so they wont be reimported from git history.

Workaround: Manually add deletion records to deletions.jsonl.


Code review: mol squash deletion bypasses tombstone system

The deleteEphemeralChildren function in mol_squash.go uses DeleteIssue directly instead of the proper deletion flow. This bypasses tombstone creation, deletion tracking (deletions.jsonl), and dependency cleanup. Could cause issues with deletion propagation across clones.

Current code uses d.DeleteIssue(ctx, id) but should probably use d.DeleteIssues(ctx, ids, false, true, false) for proper tombstone handling.

Alternative: Document that ephemeral issues intentionally use hard delete since they are transient and should never propagate to other clones anyway.


Test stdin 2

Description from stdin test


Document BEADS_DIR pattern for multi-agent workspaces (Gas Town)

Gas Town and similar multi-agent systems need to configure separate beads databases per workspace/rig, distinct from any project-level beads.

## Use Case

In Gas Town:
- Each 'rig' (managed project) has multiple agents (polecats, refinery, witness)
- All agents in a rig should share a single beads database at the rig level
- This should be separate from any .beads/ the project itself uses
- The BEADS_DIR env var enables this

## Documentation Needed

1. Add a section to docs explaining BEADS_DIR for multi-agent setups
2. Example: setting BEADS_DIR in agent startup scripts/hooks
3. Clarify interaction with project-level .beads/ (BEADS_DIR takes precedence)

## Current Support

Already implemented in internal/beads/beads.go:FindDatabasePath():
- BEADS_DIR env var is checked first (preferred)
- BEADS_DB env var still supported (deprecated)
- Falls back to .beads/ search in tree

Just needs documentation for the multi-agent workspace pattern.


Update go install bd to {{version}}

Rebuild and install bd to ~/go/bin:

```bash
go install ./cmd/bd
~/go/bin/bd version  # Verify shows {{version}}
```

Note: If ~/go/bin is in PATH before /opt/homebrew/bin, this is the version that runs by default.


Add {{version}} to versionChanges in info.go

Add new entry at TOP of versionChanges in cmd/bd/info.go with release notes from CHANGELOG.md. Must do before bump-version.sh --commit.


Add bd reset command for clean slate restart

Implement a command to reset beads to a clean starting state.

**Context:** GitHub issue #479 - users sometimes get beads into an invalid state after updates, and there's no clean way to start fresh. The git backup/restore mechanism that protects against accidental deletion also makes it hard to intentionally reset.

**Current workaround** (from maphew):
```bash
bd daemons killall
git rm .beads/*.jsonl
git commit -m 'remove old issues'
rm .beads/*
bd init
bd onboard
```

**Desired:** A proper `bd reset` command that handles this cleanly and safely.


mol-beads-release

Release checklist for beads version 0.37.0.

This molecule ensures all release steps are completed properly.
Variable: 0.37.0 - target version (e.g., 0.35.0)

## Step: update-release-notes
Update cmd/bd/info.go with release notes for 0.37.0.

Add a new VersionChange entry at the top of versionChanges slice:
```go
{
    Version: "0.37.0",
    Date:    "YYYY-MM-DD",
    Changes: []string{
        "NEW: Feature description",
        "FIX: Bug fix description",
        "IMPROVED: Enhancement description",
    },
},
```

Run `git log --oneline v<previous>..HEAD` to see what changed.

## Step: update-changelog
Update CHANGELOG.md with detailed release notes.

Add a new section after [Unreleased]:
```markdown
## [0.37.0] - YYYY-MM-DD

### Added
- **Feature name** (issue-id) - Description

### Changed
- **Change description** (issue-id)

### Fixed
- **Bug fix** (issue-id) - Description
```

Sort by importance, not chronologically.
Needs: update-release-notes

## Step: bump-version
Run the version bump script.

```bash
./scripts/bump-version.sh 0.37.0
```

This updates version in all files:
- cmd/bd/version.go
- .claude-plugin/*.json
- integrations/beads-mcp/pyproject.toml
- npm-package/package.json
- Hook templates

Needs: update-changelog

## Step: run-tests
Run tests and verify lint passes.

```bash
go test -short ./...
```

CI will run full lint, but fix any obvious issues first.
Needs: bump-version

## Step: commit-release
Commit the release changes.

```bash
git add -A
git commit -m "chore: bump version to v0.37.0"
```

Needs: run-tests

## Step: push-and-tag
Push commit and create release tag.

```bash
git push origin main
git tag v0.37.0
git push origin v0.37.0
```

This triggers GitHub Actions release workflow.
Needs: commit-release

## Step: wait-for-ci
Wait for GitHub Actions to complete.

Monitor: https://github.com/steveyegge/beads/actions

CI will:
- Build binaries via GoReleaser
- Create GitHub Release with assets
- Publish to npm (@beads/bd)
- Publish to PyPI (beads-mcp)
- Update Homebrew tap

Wait until all jobs succeed (~5-10 min).
Needs: push-and-tag

## Step: verify-release
Verify the release is complete.

```bash
# Check GitHub release
gh release view v0.37.0

# Check Homebrew
brew update && brew info steveyegge/beads/bd

# Check npm
npm view @beads/bd version

# Check PyPI
pip index versions beads-mcp
```

Needs: wait-for-ci

## Step: update-local
Update local installations.

```bash
# Upgrade Homebrew
brew upgrade steveyegge/beads/bd

# Or install from source
./scripts/bump-version.sh 0.37.0 --install

# Install MCP locally
pip install -e integrations/beads-mcp

# Restart daemons
pkill -f "bd daemon" || true
```

Verify: `bd --version` shows 0.37.0
Needs: verify-release

## Step: manual-publish
(Optional) Manual publish if CI failed.

```bash
# npm (requires npm login)
./scripts/bump-version.sh 0.37.0 --publish-npm

# PyPI (requires TWINE credentials)
./scripts/bump-version.sh 0.37.0 --publish-pypi

# Or both
./scripts/bump-version.sh 0.37.0 --publish-all
```

Only needed if CI publishing failed.
Needs: wait-for-ci


Code review: bd mol bond implementation

Review the mol bond command implementation before shipping.

Focus areas:
1. runMolBond() - polymorphic dispatch logic correctness
2. bondProtoProto() - compound proto creation, dependency wiring
3. bondProtoMol() / bondMolProto() - spawn and attach logic
4. bondMolMol() - joining molecules, lineage tracking
5. BondRef usage - is lineage tracked correctly?
6. Error handling - are all failure modes covered?
7. Edge cases - what could go wrong?

File: cmd/bd/mol.go (lines 485-859)
Commit: 386b513e


Fix update-homebrew.sh awk script corrupts formula

The awk script in scripts/update-homebrew.sh incorrectly removes platform conditionals (on_macos do, on_linux do, if Hardware::CPU.arm?, etc.) when updating SHA256 hashes. This corrupts the Homebrew formula.

The issue is the awk script uses 'next' to skip lines containing platform conditionals but never reconstructs them, resulting in a syntax-invalid formula.

Found during v0.34.0 release - had to manually fix the formula.

Fix options:
1. Rewrite awk script to properly preserve structure while updating sha256 lines only
2. Use sed instead with targeted sha256 replacements
3. Template approach - store formula template and fill in version/hashes


Version Bump: 0.32.1

Release checklist for version 0.32.1. Patch release with MCP output control params and pin field fix.


Implement Jira issue timestamp comparison for sync

In cmd/bd/jira.go:633, there's a TODO for a full implementation that would fetch the Jira issue and compare timestamps to detect conflicts during sync.

File: cmd/bd/jira.go:633


dave Handoff


Unify template.go and mol.go under bd mol

Consolidate the two DAG-template systems into one under the mol command. mol.go (on rictus branch) has the right UX (catalog/show/bond), template.go has the mechanics. Merge them, deprecate bd template commands.


Merge: bd-n386

branch: polecat/immortan
target: main
source_issue: bd-n386
rig: beads


bd cook: needs field not converted to step dependencies

When cooking a formula with `needs` fields on steps, the dependencies are not created between sibling steps.

## Expected

Formula:
```yaml
steps:
  - id: inbox-check
    title: Check inbox
  - id: trigger-spawns
    title: Nudge polecats
    needs: [inbox-check]
```

Should create:
- mol-foo.inbox-check (no deps)
- mol-foo.trigger-spawns → depends on → mol-foo.inbox-check

## Actual

Both steps only depend on the parent proto:
- mol-foo.inbox-check → depends on → mol-foo
- mol-foo.trigger-spawns → depends on → mol-foo

The `needs` field is ignored.

## Impact

This breaks the step execution order. Steps that should wait for predecessors will run in parallel or out of order.

## Reproduction

```bash
bd cook mol-deacon-patrol.formula.yaml
bd show mol-deacon-patrol.trigger-pending-spawns
# Shows: Depends on mol-deacon-patrol (parent only)
# Should show: Depends on mol-deacon-patrol.inbox-check
```


--parent flag reports success but doesn't persist to JSONL

The --parent flag for bd update reports success but the change doesn't persist.

Reported by: Mayor
Location: show.go:810-814 handles the logic

Symptoms:
- bd update <id> --parent=<new-parent> returns success
- But the parent change is not written to JSONL
- Subsequent bd show reveals parent unchanged

This shipped in v0.39.1 as part of bd-cj2e (--parent flag for reparenting).

Investigation: Check the update path from show.go through to JSONL export. The RPC/daemon layer may be dropping the parent field, or the storage layer isn't persisting it.


Create release tag

Create annotated git tag.

```bash
git tag -a v0.39.0 -m "Release v0.39.0"
```

Verify: `git tag -l | tail -5`


Test prefix beads


GH#518: Document bd setup command

bd setup is undiscoverable. Add to README/docs. Currently only findable by grepping source. See GitHub issue #518.


Fix unparam unused parameter in cmd/bd/doctor.go:541

Linting issue: checkHooksQuick - path is unused (unparam) at cmd/bd/doctor.go:541:22. Error: func checkHooksQuick(path string) string {


Split monolithic sqlite.go into focused files

internal/storage/sqlite/sqlite.go is 1050 lines containing initialization, 20+ CRUD methods, query building, and schema management.

Split into:
- store.go: Store struct & initialization (150 lines)
- bead_queries.go: Bead CRUD (300 lines)
- work_queries.go: Work queries (200 lines)
- stats_queries.go: Statistics (150 lines)
- schema.go: Schema & migrations (150 lines)
- helpers.go: Common utilities (100 lines)

Impact: Impossible to understand at a glance; hard to find specific functionality; high cognitive load

Effort: 6-8 hours


Witness Patrol

Per-rig worker monitor patrol loop with progressive nudging.