Implement Step.Condition evaluation in bd cook

## Summary
Implement conditional step execution based on variable values.

## Location
- Schema: `internal/formula/types.go:177-180`
- Implement in: `internal/formula/cook.go` (or new file `condition.go`)

## Current Schema
```go
// Condition makes this step optional based on a variable.
// Format: "{{var}}" (truthy) or "{{var}} == value".
// TODO(bd-7zka): Not yet implemented in bd cook. Filed as future work.
Condition string `json:"condition,omitempty"`
```

## Implementation

### Parsing
Support two formats:
1. `"{{var}}"` - truthy check (non-empty, non-"false", non-"0")
2. `"{{var}} == value"` - equality check

```go
func evaluateCondition(condition string, vars map[string]string) (bool, error) {
    // Check for equality format
    if strings.Contains(condition, "==") {
        parts := strings.SplitN(condition, "==", 2)
        varExpr := strings.TrimSpace(parts[0])
        expected := strings.TrimSpace(parts[1])

        // Extract variable name from {{var}}
        varName := extractVarName(varExpr)
        actual := vars[varName]
        return actual == expected, nil
    }

    // Truthy check
    varName := extractVarName(condition)
    val := vars[varName]
    return val != "" && val != "false" && val != "0", nil
}
```

### Integration with bd cook
In the step processing loop, check condition before creating issue:
```go
if step.Condition != "" {
    include, err := evaluateCondition(step.Condition, vars)
    if err != nil {
        return fmt.Errorf("invalid condition %q: %w", step.Condition, err)
    }
    if !include {
        continue // Skip this step
    }
}
```

## Example Usage
```yaml
steps:
  - title: "Run integration tests"
    condition: "{{run_integration}}"

  - title: "Deploy to staging"
    condition: "{{environment}} == staging"
```

## Testing
- Test truthy evaluation (empty, "false", "0", valid value)
- Test equality check
- Test invalid condition format
- Test missing variable (should be falsy)

## Acceptance Criteria
- [x] Truthy conditions work
- [x] Equality conditions work
- [x] Steps are skipped when condition is false
- [x] Clear error on malformed condition
- [x] Works with variable substitution

Implemented Step.Condition evaluation in stepcondition.go with tests


Implement Gate evaluation in bd cook

## Summary
Implement async wait conditions (gates) for formula steps.

## Design Decision: RESOLVED

**Gates are issues.** A gate is a `bd-gate-*` prefixed issue that blocks the step it guards.

### Gate Issue Structure
```
bd-gate-abc: Gate: gh:run test.yml
  type: gate
  gate_type: gh:run
  gate_target: test.yml
  gate_timeout: 1h
  gate_created: 2025-01-01T12:00:00Z
  blocks: bd-xyz  # The step issue waiting on this gate
```

### Gate Types and Watchers

| Gate Type | Signal Source | Watcher | Trigger |
|-----------|---------------|---------|---------|
| bead (cross-rig) | bd sync | Existing dep resolution | Sync |
| gh:run | GitHub API | Refinery | Patrol poll |
| gh:pr | GitHub API | Refinery | Patrol poll |
| timer | Clock | Witness | Patrol cycle |
| human | Human | None | bd close |
| mail | Inbox | Deacon | Mail receipt (future) |

### Visibility
- bd list hides gate-type issues by default
- bd gate list shows all open gates
- bd mol show displays gates inline in molecule view

### Timeouts
- Gate timeout triggers escalation to Deacon/Overseer inbox
- See: bd-0sgd (escalation inbox design)

## Implementation Phases

### Phase 1: Gate Issues + Human Gates
- bd cook creates bd-gate-* issues for steps with gates
- Gate issues block the next step via dependency
- Human gates: just bd close bd-gate-xxx
- bd list filters out type=gate by default
- bd gate list command

### Phase 2: Timer Gates
- Witness patrol includes bd gate check --type=timer
- Gate metadata: timeout, created_at
- Expired gates escalate (not auto-close)

### Phase 3: GitHub Gates
- Refinery patrol includes bd gate check --type=gh
- Uses gh CLI to check workflow/PR status
- Resolved gates close

### Phase 4: Cross-Rig Bead Gates
- Leverage existing external dep resolution
- bd cook creates gate with external dep on target bead
- bd ready / bd sync resolves naturally

### Phase 5: Mail Gates (future)
- Deacon watches for mail responses
- Complex - may YAGNI

## Commands

```bash
bd gate list                    # Show open gates
bd gate check                   # Evaluate all gates
bd gate check --type=timer      # Check only timer gates
bd gate check --type=gh         # Check only GitHub gates
bd gate resolve <id> [--reason] # Force-close a gate
```

## Location
- Schema: internal/formula/types.go
- Gate issue creation: internal/formula/cook.go
- Gate commands: cmd/bd/gate.go (new)
- List filtering: cmd/bd/list.go

## Acceptance Criteria
- [ ] bd cook creates bd-gate-* issues for gated steps
- [ ] Gate issues block subsequent steps
- [ ] bd list hides gates by default
- [ ] bd gate list shows all gates
- [ ] bd gate check --type=timer works (Witness integration)
- [ ] bd mol show displays gates in molecule view
- [ ] Human gates closeable via bd close

Implemented Phase 1: Gate Issues + Human Gates


Merge: bd-bqcc

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


Add import.orphan_handling config option

Add configuration option to control orphan handling behavior: 'strict' (fail on missing parent, current behavior), 'resurrect' (auto-resurrect from JSONL, recommended default), 'skip' (skip orphaned issues with warning), 'allow' (import orphans without validation). Update CONFIG.md documentation.


Add unit tests for import ordering

Test topological sort: import [child, parent] should succeed, import [parent.1.2, parent, parent.1] should sort correctly. Verify depth-based batching works. Test max depth limits.


Add programmatic tip injection API

Allow tips to be programmatically injected at runtime based on detected conditions. This enables dynamic tips (not just pre-defined ones) to be shown with custom priority and frequency.


Investigate jujutsu VCS as potential solution for conflict-free merging

## Context
Current N-way collision resolution struggles with Git line-based merge model. When 5+ clones create issues with same ID, Git merge conflicts require manual resolution, and our collision resolver can fail during convergence rounds.

## Research Question
Could jujutsu (jj) provide better conflict handling for JSONL files?

## Jujutsu Overview
- Next-gen VCS built on libgit2
- Designed to handle conflicts as first-class citizens
- Supports conflict-free replicated data types (CRDTs) in some scenarios
- Better handling of concurrent edits
- Can work with Git repos (compatible with existing infrastructure)

## Investigation Tasks
1. JSONL Merge Behavior - How does jj handle line-by-line JSONL conflicts?
2. Integration Feasibility - Can beads use jj as backend while maintaining Git compatibility?
3. Conflict Resolution Model - Does jj conflict model map to our collision resolution?
4. Operational Transform Support - Does jj implement operational transforms?

## Deliverables
1. Technical report on jj merge algorithm for JSONL
2. Proof-of-concept: 5-clone collision test using jj instead of Git
3. Performance comparison: Git vs jj for beads workload
4. Recommendation: Adopt, experiment further, or abandon

## References
- https://github.com/martinvonz/jj
- Related to bd-e6d71828, bd-7a2b58fc


Add migration guide for library consumers

The contributor-workflow-analysis.md has excellent migration examples for CLI users (lines 508-549) but lacks examples for library consumers like VC that use beadsLib in Go/TypeScript code.

Library consumers need to know:
- Whether their existing code continues to work unchanged (backward compatibility)
- How config.toml is automatically read (transparent hydration)
- When and how to use explicit multi-repo configuration
- What happens if config.toml doesn't exist (defaults)

Example needed:
```go
// Before (v0.17.3)
store, err := beadsLib.NewSQLiteStorage(".beads/vc.db")

// After (v0.18.0 with multi-repo) - still works!
store, err := beadsLib.NewSQLiteStorage(".beads/vc.db")
// Automatically reads .beads/config.toml if present

// Explicit multi-repo (if needed)
cfg := beadsLib.Config{
    Primary: ".beads/vc.db",
    Additional: []string{"~/.beads-planning"},
}
store, err := beadsLib.NewStorageWithConfig(cfg)
```


cmd/bd tests fail without -short flag (parallel test deadlock)


bd validate - Comprehensive health check

Run all validation checks in one command.

Checks:
- Duplicates
- Orphaned dependencies
- Test pollution
- Git conflicts

Supports --fix-all for auto-repair.

Depends on bd-cbed9619.1, bd-0dcea000, bd-2752a7a2, bd-9826b69a.

Files: cmd/bd/validate.go (new)


Remove top-level comment alias

Remove 'comment' as top-level command. Users should use 'comments add' instead. Reduces command surface area.


bd cleanup fails with CHECK constraint on status/closed_at mismatch

## Problem

Running `bd cleanup --force` fails with:

```
Error: failed to create tombstone for bd-okh: sqlite3: constraint failed: CHECK constraint failed: (status = 'closed') = (closed_at IS NOT NULL)
```

## Root Cause

The database has a CHECK constraint ensuring closed issues have `closed_at` set and non-closed issues don't. When `bd cleanup` tries to convert a closed issue to a tombstone, this constraint fails if:
1. The issue has status='closed' but closed_at is NULL, OR
2. The issue is being converted but the tombstone creation doesn't properly handle the closed_at field

## Impact

- `bd cleanup --force` cannot complete
- 722 closed issues cannot be cleaned up
- Blocks routine maintenance

## Investigation Needed

1. Check the bd-okh record in the database:
   ```sql
   SELECT id, status, closed_at, deleted_at FROM issues WHERE id = 'bd-okh';
   ```
2. Determine if this is data corruption or a bug in tombstone creation

## Proposed Solutions

1. **If data corruption**: Add a `bd doctor --fix` check that repairs status/closed_at mismatches
2. **If code bug**: Fix the tombstone creation to properly handle the constraint

## Files to Investigate

- `internal/storage/sqlite/sqlite.go` - DeleteIssue / tombstone creation
- Schema CHECK constraint definition

## Acceptance Criteria

- [ ] Identify root cause (data vs code bug)
- [ ] `bd cleanup --force` completes successfully
- [ ] `bd doctor` detects status/closed_at mismatches


Publish bd-wasm to npm

Package and publish WASM build to npm. Child of epic bd-44d0.

## Tasks
- [ ] Optimize WASM bundle (compression)
- [ ] Create README for npm package
- [ ] Set up npm publishing workflow
- [ ] Publish v0.1.0-alpha
- [ ] Test installation in clean environment
- [ ] Update beads AGENTS.md with installation instructions

## Package Name
bd-wasm (or @beads/wasm-cli)


Switch from modernc.org/sqlite to ncruces/go-sqlite3 for WASM support

modernc.org/sqlite depends on modernc.org/libc which has no js/wasm support (platform-specific syscalls). Need to switch to ncruces/go-sqlite3 which wraps a WASM build of SQLite using wazero runtime.

Key differences:
- ncruces/go-sqlite3: Uses WASM build of SQLite + wazero runtime
- modernc.org/sqlite: Pure Go translation, requires libc for syscalls

This is a prerequisite for bd-62a0 (WASM build infrastructure).


Add tests for internal/autoimport package

Currently 0.0% coverage. Need tests for auto-import functionality that detects and imports updated JSONL files.


Add integration tests for multi-repo sync

Test: Clone A deletes issue, Clone B imports Clone A's JSONL. Verify Clone B handles deletion gracefully with resurrection. Test concurrent imports with same orphans (should be idempotent). Test round-trip fidelity (export→delete parent→import→verify structure).


Merge: jasper-mjxcarqd

branch: polecat/jasper-mjxcarqd
target: main
source_issue: jasper-mjxcarqd
rig: beads
agent_bead: bd-beads-polecat-jasper

Branches merged, cleaning up stale MR beads


Test issue 1


Publish @beads/bd package to npm registry

Publish the npm package to the public npm registry:

## Prerequisites
- npm account created
- Organization @beads created (or use different namespace)
- npm login completed locally
- Package tested locally (bd-f282 completed)

## Publishing steps
1. Verify package.json version matches current bd version
2. Run npm pack and inspect tarball contents
3. Test installation from tarball one more time
4. Run npm publish --access public
5. Verify package appears on https://www.npmjs.com/package/@beads/bd
6. Test installation from registry: npm install -g @beads/bd

## Post-publish
- Add npm badge to README.md
- Update CHANGELOG.md with npm package release
- Announce in release notes

## Note
- May need to choose different name if @beads namespace unavailable
- Alternative: beads-cli, bd-cli, or unscoped beads-issue-tracker


Testing event-driven mode!


Daemon gets stuck when auto-import blocked by git conflicts

CRITICAL: The daemon enters a corrupt state that breaks RPC commands when auto-import is triggered but git pull fails due to uncommitted changes.

Impact: This is a data integrity and usability issue that could cause users to lose trust in Beads. The daemon silently fails for certain commands while appearing healthy.

Reproduction:
1. Make local changes to issues (creates uncommitted .beads/beads.jsonl)
2. Remote has updates (JSONL newer, triggers auto-import)
3. Daemon tries to pull but fails: 'cannot pull with rebase: You have unstaged changes'
4. Daemon enters bad state - 'bd show' and other commands return EOF
5. 'bd list' still works, daemon process is running, no errors logged

Technical details:
- Auto-import check runs in handleRequest() before processing RPC commands
- When import is blocked, it appears to corrupt daemon state
- Likely: deadlock, unclosed transaction, or storage handle corruption
- Panic recovery (server_lifecycle_conn.go:183) didn't catch anything - not a panic

Required fix:
- Auto-import must not block RPC command execution
- Handle git pull failures gracefully without corrupting state
- Consider: skip auto-import if git is dirty, queue import for later, or use separate goroutine
- Add timeout/circuit breaker for import operations
- Log clear warnings when auto-import is skipped

Without this fix, users in collaborative environments will frequently encounter mysterious EOF errors that require daemon restarts.


Add UNIQUE constraint on external_ref column

The external_ref column should have a UNIQUE constraint to prevent multiple issues from having the same external reference. This ensures data integrity when syncing from external systems (Jira, GitHub, Linear).

Current behavior:
- Multiple issues can have the same external_ref
- GetIssueByExternalRef returns first match (non-deterministic with duplicates)

Proposed solution:
- Add UNIQUE constraint to external_ref column
- Add migration to check for and resolve existing duplicates
- Update tests to verify constraint enforcement

Related: bd-1022


Daemon race condition: stale export overwrites recent DB changes

**Symptom:**
Merged bd-fc2d into bd-fb05 in ~/src/beads (commit ce4d756), pushed to remote. The ~/src/fred/beads daemon then exported its stale DB state and committed (8cc1bb4), reverting bd-fc2d back to "open" status.

**Timeline:**
1. 21:45:12 - Merge committed from ~/src/beads (ce4d756): bd-fc2d closed
2. 21:49:42 - Daemon in ~/src/fred/beads exported stale state (8cc1bb4): bd-fc2d open again

**Root cause:**
The fred/beads daemon had a stale database (bd-fc2d still open) and didn't auto-import the newer JSONL before exporting. When it exported, it overwrote the merge with its stale state.

**Expected behavior:**
Daemon should detect that JSONL is newer than its last export and import before exporting.

**Actual behavior:**
Daemon exported stale DB state, creating a conflicting commit that reverted upstream changes.

**Impact:**
Multi-workspace setups with daemons can silently lose changes if one daemon has stale state and exports.


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


Fix Windows-specific test failures in CI

Several tests are failing on Windows but passing on Linux:

**Failing tests:**
- TestFindDatabasePathEnvVar
- TestHashIDs_MultiCloneConverge
- TestHashIDs_IdenticalContentDedup
- TestDatabaseReinitialization (all 5 subtests):
  - fresh_clone_auto_import
  - database_removal_scenario
  - legacy_filename_support
  - precedence_test
  - init_safety_check
- TestFindBeadsDir_NotFound
- TestMetricsSnapshot/uptime (in internal/rpc)

**CI Run:** https://github.com/steveyegge/beads/actions/runs/19015638968

These are likely path separator or filesystem behavior differences between Windows and Linux.

Fixed all Windows path issues:
1. TestFindDatabasePathEnvVar - expects canonicalized paths ✅
2. TestHashIDs tests - use platform-specific bd.exe command ✅
3. TestMetricsSnapshot/uptime - enforce minimum 1 second uptime ✅
4. TestFindBeadsDir_NotFound - allow finding .beads in parent dirs ✅
5. TestDatabaseReinitialization - fix git path conversion on Windows (git returns /c/Users/... but filepath needs C:\Users\...) ✅

CI run in progress to verify all fixes.


Refactor: deduplicate FindJSONLInDir and FindJSONLPath

## Background

After fixing bd-tqo, we now have two nearly identical functions for finding the JSONL file:
- `autoimport.FindJSONLInDir(dbDir string)` in internal/autoimport/autoimport.go
- `beads.FindJSONLPath(dbPath string)` in internal/beads/beads.go

Both implement the same logic:
1. Prefer issues.jsonl
2. Fall back to beads.jsonl for legacy support
3. Skip deletions.jsonl and merge artifacts
4. Default to issues.jsonl if nothing found

## Problem

Code duplication means bug fixes need to be applied in multiple places (as we just experienced with bd-tqo).

## Proposed Solution

Extract shared logic to a utility package that both can import. Options:
1. Create `internal/jsonlpath` package with the core logic
2. Have `autoimport` import `beads` and call `FindJSONLPath` (but APIs differ slightly)
3. Move to `internal/utils` if appropriate

Need to verify no import cycles would be created.

## Affected Files
- internal/autoimport/autoimport.go
- internal/beads/beads.go


Session ended: gt-beads-crew-emma


bd import auto-detects wrong prefix from directory name instead of issue IDs

When importing issues.jsonl into a fresh database, 'bd import' prints:

  ✓ Initialized database with prefix 'beads' (detected from issues)

But the issues all have prefix 'bd-' (e.g., bd-03r). It appears to be detecting the prefix from the directory name (.beads/) rather than from the actual issue IDs in the JSONL.

This causes import to fail with:
  validate ID prefix for bd-03r: issue ID 'bd-03r' does not match configured prefix 'beads'

Workaround: Run 'bd config set issue_prefix bd' before import, or use 'bd init --prefix bd'.


bd-hv01: Race condition with concurrent snapshot operations

## Problem
Snapshot files have no locking. Multiple processes can call captureLeftSnapshot simultaneously:

1. Process A: export → begins snapshot
2. Process B: export → begins snapshot
3. Process A: writes partial left.jsonl
4. Process B: overwrites with its left.jsonl
5. Process A: completes merge with wrong snapshot

## Impact
- Data corruption in multi-process scenarios
- Daemon + manual sync race
- Multiple git clones on same filesystem

## Fix
Use atomic file operations with process-specific temp files:
```go
func captureLeftSnapshot(jsonlPath string) error {
    _, leftPath := getSnapshotPaths(jsonlPath)
    tempPath := fmt.Sprintf("%s.%d.tmp", leftPath, os.Getpid())
    if err := copyFileSnapshot(jsonlPath, tempPath); err != nil {
        return err
    }
    return os.Rename(tempPath, leftPath) // Atomic on POSIX
}
```

## Files Affected
- cmd/bd/deletion_tracking.go:24-29 (captureLeftSnapshot)
- cmd/bd/deletion_tracking.go:31-36 (updateBaseSnapshot)


Remove molecule.go (simple instantiation)

molecule.go uses is_template field for simple single-issue cloning. This is too simple for what molecules should be - full DAG orchestration. The use case is covered by bd mol bond with a single-issue molecule. Delete molecule.go and its commands.


Add depth-based batch creation in upsertIssues

Replace single batch creation with depth-level batching (max depth 3). Create issues at depth 0, then 1, then 2, then 3. Prevents parent validation errors when importing hierarchical issues in same batch. File: internal/importer/importer.go:534-546


Merge: bd-au0.6

branch: polecat/furiosa
target: main
source_issue: bd-au0.6
rig: beads


gt sling --create fails to create polecat before resolving pane

gt sling --create tries to resolve pane BEFORE creating the polecat, causing failure.

Expected: gt sling gt-xyz gastown/newcat --create should:
1. Create polecat if not exists
2. Start session
3. Hook work
4. GUPP triggers autonomous execution

Actual: Fails with 'getting pane for gt-gastown-newcat: exit status 1'

Location: internal/cmd/sling.go - need to reorder operations

Fixed in PR #4: https://github.com/steveyegge/gastown/pull/4


Merge: beads-ocs

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


Test update


test hash length


Test role bead


Fix G304 potential file inclusion in cmd/bd/tips.go:259

Linting issue: G304: Potential file inclusion via variable (gosec) at cmd/bd/tips.go:259:18. Error: if data, err := os.ReadFile(settingsPath); err == nil {


Add GUPP to non-polecat roles (Mayor, Deacon, Witness, Refinery)

GUPP (propulsion nudge after beacon) is only implemented for polecats in session/manager.go.

Other roles have different startup flows but could benefit from similar auto-propulsion:
- Mayor: mayor/manager.go or wherever mayor session starts
- Deacon: deacon startup flow
- Witness: witness startup flow
- Refinery: refinery startup flow

Each role may need role-specific propulsion message.


Auto-routing and maintainer detection

Implement intelligent routing to automatically send new issues to correct repo based on user's maintainer vs contributor status, with discovered issues inheriting parent's source_repo.


Kill running daemons

Stop all bd daemons before release:

```bash
pkill -f 'bd.*daemon' || true
sleep 1
pgrep -lf 'bd.*daemon'  # Should show nothing
```


Debug test


bd delete bulk operations fight with auto-import/daemon causing data resurrection

When bulk deleting issues (e.g., 244 closed issues older than 24h), the process fights with auto-import and daemon infrastructure:

**Expected behavior:**
- Delete 244 issues from 468-issue database
- Export to JSONL (224 lines)
- Commit and push
- Result: 224 issues

**Actual behavior:**
- Delete 244 issues
- Import runs (from stale git JSONL with 468 issues)
- Resurrects deleted issues back into database
- Export writes 356 lines (not 224)
- Math: 468 - 244 = 224, but got 356 (132 issues resurrected)

**Root cause:**
Auto-import keeps re-importing from git during the delete operation, before the new JSONL is committed. The workflow is:
1. Delete from DB
2. Auto-import runs (reads old JSONL from git with deleted issues still present)
3. Issues come back
4. Export writes partially-deleted state

**Solution options:**
1. Add `--no-auto-import` flag to bulk delete operations
2. Atomic delete-export-commit operation that suppresses imports
3. Dedicated `bd prune` command that handles this correctly
4. Lock file to prevent auto-import during bulk mutations

**Impact:**
- Bulk cleanup operations don't work reliably
- Makes it nearly impossible to prune old closed issues
- Confusing UX (delete 244, but only 112 actually removed)

**FIXED**: Auto-import now skips during delete operations to prevent resurrection.

**Root cause confirmed**: Auto-import was running in PersistentPreRun before delete executed, causing it to re-import stale JSONL from git and resurrect deleted issues.

**Solution implemented**:
1. Added delete to skip list in main.go PersistentPreRun (alongside import and sync --dry-run)
2. Delete operations now complete atomically without auto-import interference
3. Added comprehensive test (TestBulkDeleteNoResurrection) to prevent regression

**Test verification**:
- Creates 20 issues, deletes 10
- Verifies no resurrection after delete
- Confirms JSONL has correct count (10 remaining)
- All existing tests still pass


bd message: Implement full message reading functionality

The `bd message read` command is incomplete and doesn't actually fetch or display message content.

**Location:** cmd/bd/message.go:413-441

**Current Behavior:**
- Only marks message as read
- Prints placeholder text
- Doesn't fetch message body

**Expected:**
- Fetch full message from Agent Mail resource API
- Display sender, subject, timestamp, body
- Consider markdown rendering

**Blocker:** Core feature for message system MVP


Verify docs/property-layers.md exists after merge

During property layers implementation, docs/property-layers.md was deleted in multiple polecat branches. Verify this file exists after all merges complete. If missing, restore from backup or recreate based on ~/gt/docs/hop/PROPERTY-LAYERS.md.


Support Ubuntu 20.04 LTS (glibc compatibility issue)

Starting at v0.22, precompiled binaries require GLIBC 2.32+ which is not available on Ubuntu 20.04 LTS (Focal Fossa). Ubuntu 20.04 has GLIBC 2.31.

Error:
```
bd: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.34' not found (required by bd)
bd: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.32' not found (required by bd)
```

Current workarounds:
1. Upgrade to Ubuntu 22.04+
2. Build from source: `go build -o bd ./cmd/bd/`

Root cause: Go 1.24+ runtime requires newer glibc. CGO is already disabled in .goreleaser.yml.

Possible solutions:
- Pin Go version to 1.21 or 1.22 for releases
- Use Docker/cross-compile with older build environment
- Provide separate build for older distros
- Document minimum requirements clearly

Decision: Document minimum requirements in README instead of pinning Go version.

Rationale:
- Ubuntu 20.04 LTS standard support ended April 2025 (already EOL)
- Pinning Go prevents security fixes, performance improvements, and new features
- Users on EOL distros can upgrade OS or build from source
- Added Requirements section to README with clear glibc 2.32+ requirement


Version Bump: 0.30.7

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


Remove misleading placeholder 'bd merge' command from duplicates output

**Problem:**
The `bd duplicates` command suggests running a command that doesn't exist:
```
bd merge <source-ids> --into <target-id>
```

This is confusing because:
1. `bd merge` is actually a git 3-way JSONL merge driver (takes 4 file paths)
2. The suggested syntax for merging duplicate issues is not implemented
3. Line 75 in duplicates.go even has: `// TODO: performMerge implementation pending`

**Current behavior:**
- Users see suggested command that doesn't work
- No indication that feature is unimplemented
- Related to issue #349 item #2

**Proposed fix:**
Replace line 77 in cmd/bd/duplicates.go with either:

Option A (conservative):
```go
cmd := fmt.Sprintf("# TODO: Merge %s into %s (merge command not yet implemented)",
    strings.Join(sources, " "), target.ID)
```

Option B (actionable):
```go
cmd := fmt.Sprintf("# Duplicate found: %s\n# Manual merge: Close duplicates with 'bd close %s' and link to %s as 'related'",
    strings.Join(sources, " "), strings.Join(sources, " "), target.ID)
```

**Files to modify:**
- cmd/bd/duplicates.go (line ~77)


Migration and onboarding for multi-repo

Create migration tools, wizards, and documentation to help users adopt multi-repo workflow, with special focus on OSS contributor onboarding and team adoption scenarios.


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.


bd doctor --fix hydrates issues that remain in deletions manifest, causing perpetual skip warnings

When bd doctor --fix hydrates issues from git history, it doesn't remove them from the deletions manifest. This causes a conflict where:
1. Issue exists in database as 'open'
2. Issue also exists in deletions manifest
3. Every sync reports 'Skipping bd-xxx (in deletions manifest)'
4. Issue is 'Protected from incorrect sanitization'

**Reproduction:**
1. Run bd doctor --fix (which hydrates issues from git history)
2. Run bd sync
3. Observe conflicting messages about protected issues being skipped

**Affected issues in this session:**
bd-eyto, bd-6rl, bd-y2v, bd-abjw, bd-a0cp, bd-mql4, bd-nl2

**Expected behavior:**
When hydrating an issue, also remove it from the deletions manifest to prevent conflict.

**Workaround:** Manually remove conflicting IDs from deletions.jsonl


Code Review Sweep: thorough

Perform thorough code review sweep based on accumulated activity.

**AI Reasoning:**
Significant code volume added (150,273 lines) across multiple critical areas, including cmd/bd, internal/storage/sqlite, and internal/rpc. High file change count (616) indicates substantial refactoring or new functionality. The metrics suggest potential for subtle architectural or implementation issues that warrant review.

**Scope:** thorough
**Target Areas:** cmd/bd, internal/storage/sqlite, internal/rpc
**Estimated Files:** 12
**Estimated Cost:** $5

**Task:**
Review files for non-obvious issues that agents miss during focused work:
- Inefficiencies (algorithmic, resource usage)
- Subtle bugs (race conditions, off-by-one, copy-paste)
- Poor patterns (coupling, complexity, duplication)
- Missing best practices (error handling, docs, tests)
- Unnamed anti-patterns

File discovered issues with detailed reasoning and suggestions.


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.


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 'bd where' command to show active beads location

## Problem

When using redirects, it's unclear which beads database is actually being used. This caused debugging confusion during the v0.39.0 release.

## Proposed Solution

Add `bd where` command:

```bash
bd where
# → /Users/stevey/gt/beads/mayor/rig/.beads (via redirect from crew/dave/.beads)

bd where --json
# → {"path": "...", "redirected_from": "...", "prefix": "bd"}
```

## Alternatives Considered

- `bd info --beads-path` - but `bd where` is more discoverable
- Just fix the UX so it's never confusing - defense in depth is better

## Desire Paths

This supports the 'desire paths' design principle: make the system's behavior visible so agents can debug and understand it.


Add bd mol progress command

New command showing molecule progress without listing steps.

Output format:
  Molecule: gt-hanoi-xyz (Towers of Hanoi - 20 disks)
  Progress: 347,892 / 1,048,575 (33.2%)
  Current step: gt-hanoi-xyz.move-347893
  Rate: ~1,200 steps/hour
  ETA: ~9.7 hours remaining

Uses indexed query on dependencies table:
  SELECT COUNT(*), SUM(CASE WHEN status='closed' THEN 1 ELSE 0 END)
  FROM dependencies d JOIN issues i ON d.issue_id = i.id
  WHERE d.depends_on_id = ? AND d.type = 'parent-child'

Implemented bd mol progress command with efficient indexed queries


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


Code smell: runCook function is ~275 lines

attached_args: Refactor runCook function (~275 lines)

The runCook() function in cmd/bd/cook.go (lines 83-357) is ~275 lines handling:

1. Flag parsing and validation
2. Mode determination (compile vs runtime)
3. Formula parsing and resolution
4. Control flow, advice, and expansion application
5. Dry-run output
6. Ephemeral mode JSON output
7. Persist mode database operations
8. Result display

Consider extracting:
- parseAndValidateFlags() - flag handling
- loadAndResolveFormula() - parse, resolve, apply transformations
- outputDryRun() - dry run display logic
- outputEphemeral() - ephemeral JSON output
- persistFormula() - database persistence logic

The function has multiple exit points and nested conditionals that make it hard to follow.

Location: cmd/bd/cook.go:83-357


MCP server loses workspace context after Amp restart - causes silent failures

**CRITICAL BUG**: The beads MCP server loses workspace context when Amp restarts, leading to silent failures and potential data corruption.

## Reproduction
1. Start Amp with beads MCP server configured
2. Call `mcp__beads__set_context(workspace_root="/path/to/project")`
3. Use MCP tools successfully (e.g., `mcp__beads__show`, `mcp__beads__list`)
4. Restart Amp (new thread/session)
5. Try to use MCP tools without calling `set_context` again
6. **Result**: "Not connected" or "No workspace set" errors

## Impact
- Amp agents silently fail when trying to read/update beads issues
- May attempt to create duplicate issues because they can't see existing ones
- Potential for data corruption if operating on wrong database
- Breaks multi-session workflows
- Creates confusion: CLI works (`./bd`) but MCP tools don't

## Current Workaround
Manually call `mcp__beads__set_context()` at start of every Amp session.

## Root Cause
MCP server is stateful and doesn't persist workspace context across restarts.

## Proposed Fix
**Option 1 (Best)**: Auto-detect workspace from current working directory
- Match behavior of CLI `./bd` commands
- Check for `.beads/` directory in current dir or parents
- No manual context setting needed

**Option 2**: Persist context in MCP server state file
- Save last workspace_root to `~/.config/beads/mcp_context.json`
- Restore on server startup

**Option 3**: Require explicit context in every MCP call
- Add optional `workspace_root` parameter to all MCP tools
- Fall back to saved context if not provided

Acceptance:
- MCP tools work across Amp restarts without manual set_context()
- Auto-detection matches CLI behavior (walks up from CWD)
- Clear error message when no workspace found
- set_context() still works for explicit override
- BEADS_WORKING_DIR env var support
- Integration test validates restart behavior


Add tests for bd init --contributor wizard

Write integration tests for the contributor wizard:
- Test fork detection logic
- Test planning repo creation
- Test config setup
- Test with/without upstream remote
- Test with SSH vs HTTPS origins


Clean up linter errors (914 total issues)

The codebase has 914 linter issues reported by golangci-lint. While many are documented as baseline in LINTING.md, we should clean these up systematically to improve code quality and maintainability.

Reduced from 56 to 41 issues locally, then to 0 issues.

**Fixed in commits:**
- c2c7eda: Fixed 15 actual errors (dupl, gosec, revive, staticcheck, unparam)
- 963181d: Configured exclusions to get to 0 issues locally

**Current status:**
- ✅ Local: golangci-lint reports 0 issues
- ❌ CI: Still failing (see [deleted:bd-cb64c226.1])

**Problem:**
Config v2 format or golangci-lint-action@v8 compatibility issue causing CI to fail despite local success.

**Next:** Debug [deleted:bd-cb64c226.1] to fix CI/local discrepancy


Add bd hooks install command to embed git hooks in binary

Currently git hooks are installed via `examples/git-hooks/install.sh`, which only exists in the beads source repo. Users who install bd via installer/homebrew/npm can't easily install hooks.

**Proposal:**
Add `bd hooks install` command that:
- Embeds hook scripts in the bd binary (using go:embed)
- Installs them to .git/hooks/ in current repo
- Backs up existing hooks
- Makes them executable

**Commands:**
- `bd hooks install` - Install all hooks
- `bd hooks uninstall` - Remove hooks
- `bd hooks list` - Show installed hooks status

**Benefits:**
- Works for all bd users, not just source repo users
- More discoverable (shows in bd --help)
- Consistent with bd workflow
- Can version hooks with bd releases


Extract hash ID generation functions to hash_ids.go

Move generateHashID, getNextChildNumber, GetNextChildID to hash_ids.go


Merge: amber-1767138546434

branch: polecat/amber-1767138546434
target: main
source_issue: amber-1767138546434
rig: beads


bd prime: AI context loading and Claude Code integration

Implement `bd prime` command and Claude Code hooks for context recovery. Hooks work with BOTH MCP server and CLI approaches - they solve the context memory problem (keeping bd workflow fresh after compaction) not the tool access problem (MCP vs CLI).


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.


Rapid 5


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


Add fallback to polling on watcher failure

Detect fsnotify.NewWatcher() errors and log warning. Auto-switch to polling mode with 5s ticker. Add BEADS_WATCHER_FALLBACK env var to control behavior.


Add unit tests for config modes

Test all four orphan_handling modes: strict (fails), resurrect (creates tombstone), skip (logs warning), allow (imports orphan). Verify error messages and logging output for each mode.


CRDT-based architecture for guaranteed convergence (v2.0)

## Vision
Redesign beads around Conflict-Free Replicated Data Types (CRDTs) to provide mathematical guarantees for N-way collision resolution at arbitrary scale.

## Current Limitations
- Content-hash based collision resolution fails at 5+ clones
- Non-deterministic convergence in multi-round scenarios
- UNIQUE constraint violations during rename operations
- No formal proof of convergence properties

## CRDT Benefits
- Provably convergent (Strong Eventual Consistency)
- Commutative/Associative/Idempotent operations
- No coordination required between clones
- Scales to 100+ concurrent workers
- Well-understood mathematical foundations

## Proposed Architecture

### 1. UUID-Based IDs
Replace sequential IDs with UUIDs:
- Current: bd-1c63eb84, bd-9063acda, bd-4d80b7b1
- CRDT: bd-a1b2c3d4-e5f6-7890-abcd-ef1234567890
- Human aliases maintained separately: #42 maps to UUID

### 2. Last-Write-Wins (LWW) Elements
Each field becomes an LWW register:
- title: (timestamp, clone_id, value)
- status: (timestamp, clone_id, value)
- Deterministic conflict resolution via Lamport timestamp + clone_id tiebreaker

### 3. Operation Log
Track all operations as CRDT ops:
- CREATE(uuid, timestamp, clone_id, fields)
- UPDATE(uuid, field, timestamp, clone_id, value)
- DELETE(uuid, timestamp, clone_id) - tombstone, not hard delete

### 4. Sync as Merge
Syncing becomes merging two CRDT states:
- No merge conflicts possible
- Deterministic merge function
- Guaranteed convergence

## Implementation Phases

### Phase 1: Research & Design (4 weeks)
- Study existing CRDT implementations (Automerge, Yjs, Loro)
- Design schema for CRDT-based issue tracking
- Prototype LWW-based Issue CRDT
- Benchmark performance vs current system

### Phase 2: Parallel Implementation (6 weeks)
- Implement CRDT storage layer alongside SQLite
- Build conversion tools: SQLite ↔ CRDT
- Maintain backward compatibility with v1.x format
- Migration path for existing databases

### Phase 3: Testing & Validation (4 weeks)
- Formal verification of convergence properties
- Stress testing with 100+ clone scenario
- Performance profiling and optimization
- Documentation and examples

### Phase 4: Migration & Rollout (4 weeks)
- Release v2.0-beta with CRDT backend
- Gradual migration from v1.x
- Monitoring and bug fixes
- Final v2.0 release

## Risks & Mitigations

**Risk 1: Performance overhead**
- Mitigation: Benchmark early, optimize hot paths
- CRDTs can be slower than append-only logs
- May need compaction strategy

**Risk 2: Storage bloat**
- Mitigation: Implement operation log compaction
- Tombstone garbage collection for deleted issues
- Periodic snapshots to reduce log size

**Risk 3: Breaking changes**
- Mitigation: Maintain v1.x compatibility layer
- Gradual migration tools
- Dual-mode operation during transition

**Risk 4: Complexity**
- Mitigation: Use battle-tested CRDT libraries
- Comprehensive documentation
- Clear migration guide

## Success Criteria
- 100-clone collision test passes without failures
- Formal proof of convergence properties
- Performance within 2x of current system
- Zero manual conflict resolution required
- Backward compatible with v1.x databases

## Timeline
18-20 weeks total (4-5 months)

## References
- Automerge: https://automerge.org
- Yjs: https://docs.yjs.dev
- Loro: https://loro.dev
- CRDT theory: Shapiro et al, A comprehensive study of CRDTs
- Related issues: bd-0dcea000, bd-4d7fca8a, bd-6221bdcd


bd mol run: panic slice bounds out of range in mol_run.go:130

## Problem
bd mol run panics after successfully creating the molecule:

```
✓ Molecule running: created 9 issues
  Root issue: gt-i4lo (pinned, in_progress)
  Assignee: stevey

Next steps:
  bd ready                # Find unblocked work in this molecule
panic: runtime error: slice bounds out of range [:8] with length 7

goroutine 1 [running]:
main.runMolRun(0x1014fc0c0, {0x140001e0f80, 0x1, 0x10089daad?})
  /Users/stevey/gt/beads/crew/dave/cmd/bd/mol_run.go:130 +0xc38
```

## Reproduction
```bash
bd --no-daemon mol run gt-lwuu --var issue=gt-test123
```
Where gt-lwuu is a mol-polecat-work proto with 8 child steps.

## Impact
The molecule IS created successfully - the panic happens after creation when formatting the "Next steps" output.


Merge: onyx-1767138516448

branch: polecat/onyx-1767138516448
target: main
source_issue: onyx-1767138516448
rig: beads


Event-driven daemon architecture

Replace 5-second polling sync loop with event-driven architecture that reacts instantly to changes. Eliminates stale data issues while reducing CPU ~60%. Key components: FileWatcher (fsnotify), Debouncer (500ms), RPC mutation events, optional git hooks. Target latency: <500ms (vs 5000ms). See event_driven_daemon.md for full design.

## Implementation Progress

**Completed:**
1. ✅ Mutation events infrastructure (bd-143 equivalent)
   - MutationEvent channel in RPC server
   - Events emitted for all write operations: create, update, close, label add/remove, dep add/remove, comment add
   - Non-blocking emission with dropped event counter

2. ✅ FileWatcher with fsnotify (bd-b0c7f7ef related)
   - Watches .beads/issues.jsonl and .git/refs/heads
   - 500ms debounce
   - Polling fallback if fsnotify unavailable

3. ✅ Debouncer (bd-144 equivalent)
   - 500ms debounce for both export and import triggers
   - Thread-safe trigger/cancel

4. ✅ Separate export-only and import-only functions
   - createExportFunc(): exports + optional commit/push (no pull/import)
   - createAutoImportFunc(): pull + import (no export)
   - Target latency <500ms achieved by avoiding full sync

5. ✅ Dropped events safety net (bd-eef03e0a related)
   - Atomic counter tracks dropped mutation events
   - 60-second health check triggers export if events were dropped
   - Prevents silent data loss from event storms

**Still Needed:**
- Platform-specific tests (bd-69bce74a)
- Integration test for mutation→export latency (bd-140)
- Unit tests for FileWatcher (bd-b0c7f7ef)
- Unit tests for Debouncer (bd-144)
- Event storm stress test (bd-eef03e0a)
- Documentation update (bd-142)

**Next Steps:**
Add comprehensive test coverage before enabling events mode by default.


Update AGENTS.md with event-driven mode

Document BEADS_DAEMON_MODE env var. Explain opt-in during Phase 1. Add troubleshooting for watcher failures.


Implement clone-scoped ID allocation to prevent N-way collisions

## Problem
Current ID allocation uses per-clone atomic counters (issue_counters table) that sync based on local database state. In N-way collision scenarios:
- Clone B sees {test-1} locally, allocates test-2
- Clone D sees {test-1, test-2, test-3} locally, allocates test-4
- When same content gets assigned test-2 and test-4, convergence fails

Root cause: Each clone independently allocates IDs without global coordination, leading to overlapping assignments for the same content.

## Solution
Add clone UUID to ID allocation to make every ID globally unique:

**Current format:** `test-1`, `test-2`, `test-3`
**New format:** `test-1-a7b3`, `test-2-a7b3`, `test-3-c4d9`

Where suffix is first 4 chars of clone UUID.

## Implementation

### 1. Add clone_identity table
```sql
CREATE TABLE clone_identity (
    clone_uuid TEXT PRIMARY KEY,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
```

### 2. Modify getNextIDForPrefix()
```go
func (s *SQLiteStorage) getNextIDForPrefix(ctx context.Context, prefix string) (string, error) {
    cloneUUID := s.getOrCreateCloneUUID(ctx)
    shortUUID := cloneUUID[:4]

    nextNum := s.getNextCounterForPrefix(ctx, prefix)
    return fmt.Sprintf("%s-%d-%s", prefix, nextNum, shortUUID), nil
}
```

### 3. Update ID parsing logic
All places that parse IDs (utils.ExtractIssueNumber, etc.) need to handle new format.

### 4. Migration strategy
- Existing IDs remain unchanged (no suffix)
- New IDs get clone suffix automatically
- Display layer can hide suffix in UI: `bd-cb64c226.3-a7b3` → `#42`

## Benefits
- **Zero collision risk**: Same content in different clones gets different IDs
- **Maintains readability**: Still sequential numbering within clone
- **No coordination needed**: Works offline, no central authority
- **Scales to 100+ clones**: 4-char hex = 65,536 unique clones

## Concerns
- ID format change may break existing integrations
- Need migration path for existing databases
- Display logic needs update to hide/show suffixes appropriately

## Success Criteria
- 10+ clone collision test passes without failures
- Existing issues continue to work (backward compatibility)
- Documentation updated with new ID format
- Migration guide for v1.x → v2.x

## Timeline
Medium-term (v1.1-v1.2), 2-3 weeks implementation

## References
- Related to bd-e6d71828 (immediate fix)
- See beads_nway_test.go for failing N-way tests


Fix wisp leak in nodb mode writeIssuesToJSONL

writeIssuesToJSONL in nodb.go calls writeJSONLAtomic without filtering wisps. This means any wisps created during a nodb session would be written to issues.jsonl, leaking ephemeral data into the git-tracked file.

Fix: Add the same wisp filter pattern used in sync_export.go, autoflush.go, and export.go:

```go
// Filter out wisps before writing
filtered := make([]*types.Issue, 0, len(issues))
for _, issue := range issues {
    if !issue.Wisp {
        filtered = append(filtered, issue)
    }
}
issues = filtered
```

Location: cmd/bd/nodb.go:writeIssuesToJSONL()


Backend task


Recurring dirty state after merge conflicts - bd sync keeps failing

## Problem

`bd sync` consistently fails with merge conflicts in `.beads/beads.jsonl`, creating a loop:
1. User runs `bd sync`
2. Git merge conflict occurs
3. User resolves with `git checkout --theirs` (takes remote)
4. Daemon auto-exports database state (which has local changes)
5. JSONL becomes dirty again immediately
6. Repeat

This has been happening for **weeks** and is extremely frustrating.

## Root Cause

The recommended conflict resolution (`git checkout --theirs`) throws away local database state (comments, dependencies, closed issues). The daemon then immediately re-exports, creating a dirty state.

## Current Workaround

Manual `bd export -o .beads/beads.jsonl && git add && git commit && git push` after every failed sync.

## Example Session

```bash
$ bd sync
CONFLICT (content): Merge conflict in .beads/beads.jsonl

$ git checkout --theirs .beads/beads.jsonl && bd import && git add && git commit && git push
# Pushed successfully

$ git status
modified: .beads/beads.jsonl  # DIRTY AGAIN!
```

## Lost Data in Recent Session

- bd-ry1u closure (lost in merge)
- Comments on bd-08fd, bd-23a8, bd-6049, bd-87a0 (lost)
- Dependencies that existed only in local DB

## Potential Solutions

1. **Use beads-merge tool** - Implement proper 3-way JSONL merge (bd-bzfy)
2. **Smarter conflict resolution** - Detect when `--theirs` will lose data, warn user
3. **Sync validation** - Check if JSONL == DB after merge, re-export if needed
4. **Daemon awareness** - Pause auto-export during merge resolution
5. **Transaction log** - Replay local changes after merge instead of losing them

## Related Issues

- bd-bzfy (beads-merge integration)
- Possibly related to daemon auto-export behavior

## Solution Implemented

Fixed the recurring dirty state after merge conflicts by adding **sync validation** before re-exporting.

### Root Cause
Lines 217-237 in `sync.go` unconditionally re-exported DB to JSONL after every import, even when they were already in sync. This created an infinite loop:
1. User runs `bd sync` which pulls and imports remote JSONL
2. Sync unconditionally re-exports DB (which has local changes)
3. JSONL becomes dirty immediately
4. Repeat

### Fix
Added `dbNeedsExport()` function in `integrity.go` that checks:
- If JSONL exists
- If DB modification time is newer than JSONL
- If DB and JSONL issue counts match

Now `bd sync` only re-exports if DB actually has changes that differ from JSONL.

### Changes
- Added `dbNeedsExport()` in `cmd/bd/integrity.go` (lines 228-271)
- Updated `sync.go` lines 217-251 to check before re-exporting
- Added comprehensive tests in `cmd/bd/sync_merge_test.go`

### Testing
All tests pass including 4 new tests:
- `TestDBNeedsExport_InSync` - Verifies no export when synced
- `TestDBNeedsExport_DBNewer` - Detects DB modifications
- `TestDBNeedsExport_CountMismatch` - Catches divergence
- `TestDBNeedsExport_NoJSONL` - Handles missing JSONL

This prevents the weeks-long frustration of merge conflicts causing infinite dirty loops.


Code smell: Duplicated step collection functions in cook.go

attached_args: Fix duplicated step collection functions in cook.go

Two pairs of nearly identical functions exist in cook.go:

1. collectStepsRecursive() (line 754) vs collectStepsToSubgraph() (line 415)
   - Both iterate over steps and create issues
   - Main difference: one writes to DB, one builds in-memory subgraph

2. collectDependencies() (line 833) vs collectDependenciesToSubgraph() (line 502)
   - Both collect dependencies from steps
   - Nearly identical logic

Consider:
1. Extract common step/dependency processing logic
2. Use a strategy pattern or callback for the DB vs in-memory difference
3. Create a single function that returns data, then have callers decide how to persist

Location: cmd/bd/cook.go:415-567 and cmd/bd/cook.go:754-898


Update docs for import bug fix

Update AGENTS.md, README.md, TROUBLESHOOTING.md with import.orphan_handling config documentation. Document resurrection behavior, tombstones, config modes. Add troubleshooting section for import failures with deleted parents.


Optimize Memory backend GetIssueByExternalRef with index

Currently GetIssueByExternalRef in Memory storage uses O(n) linear search through all issues.

Current code (memory.go:282-308):
for _, issue := range m.issues {
    if issue.ExternalRef != nil && *issue.ExternalRef == externalRef {
        return &issueCopy, nil
    }
}

Proposed optimization:
- Add externalRefToID map[string]string to MemoryStorage
- Maintain it in CreateIssue, UpdateIssue, DeleteIssue
- Achieve O(1) lookup like SQLite's index

Impact: Low (--no-db mode typically has smaller datasets)
Related: bd-1022


Test Issue


Session ended: gt-beads-crew-emma


Add internal/ai package for LLM integration

Shared AI client for repair commands.

Providers:
- Anthropic (Claude)
- OpenAI (GPT)
- Ollama (local)

Env vars:
- BEADS_AI_PROVIDER
- BEADS_AI_API_KEY
- BEADS_AI_MODEL

Files: internal/ai/client.go (new)


DetectCycles SQL query has bug preventing cycle detection

The DetectCycles function's SQL query has a bug in the LIKE filter that prevents it from detecting cycles.

Current code (line 571):
```sql
AND p.path NOT LIKE '%' || d.depends_on_id || '→%'
```

This prevents ANY revisit to nodes, including returning to the start node to complete a cycle.

Fix:
```sql
AND (d.depends_on_id = p.start_id OR p.path NOT LIKE '%' || d.depends_on_id || '→%')
```

This allows revisiting the start node (to detect the cycle) while still preventing intermediate node revisits.

Impact: Currently DetectCycles cannot detect any cycles, but this hasn't been noticed because AddDependency prevents cycles from being created. The function would only matter if cycles were manually inserted into the database.


Document external_ref in content hash behavior

The content hash includes external_ref, which has implications that should be documented.

Current behavior:
- external_ref is included in content hash calculation (collision.go:158-160)
- Changing external_ref changes content hash
- This means: local issue → add external_ref → different hash

Implications:
- Local issue + external_ref addition = looks like 'new content'
- May not match by content hash in some scenarios
- Generally correct behavior, but subtle

Action items:
- Document in code comments
- Add to ARCHITECTURE.md or similar
- Add test demonstrating this behavior
- Consider if this is desired long-term

Related: bd-1022
Files: internal/storage/sqlite/collision.go:158-160


Baseline quality gate failure: test

The test quality gate is failing on the baseline (main branch).

This blocks the executor from claiming work until fixed.

Error: go test failed: exit status 1

Output:
```
?   	github.com/steveyegge/beads	[no test files]
# github.com/steveyegge/beads/internal/beads_test [github.com/steveyegge/beads/internal/beads.test]
internal/beads/routing_integration_test.go:142:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
# github.com/steveyegge/beads/internal/compact [github.com/steveyegge/beads/internal/compact.test]
internal/compact/compactor_test.go:17:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
# github.com/steveyegge/beads/cmd/bd [github.com/steveyegge/beads/cmd/bd.test]
cmd/bd/integrity_content_test.go:31:32: undefined: ctx
cmd/bd/integrity_content_test.go:183:32: undefined: ctx
FAIL	github.com/steveyegge/beads/cmd/bd [build failed]
# github.com/steveyegge/beads/internal/daemon [github.com/steveyegge/beads/internal/daemon.test]
internal/daemon/discovery_test.go:21:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
internal/daemon/discovery_test.go:59:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
internal/daemon/discovery_test.go:232:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
# github.com/steveyegge/beads/internal/importer [github.com/steveyegge/beads/internal/importer.test]
internal/importer/external_ref_test.go:22:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
internal/importer/external_ref_test.go:106:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
internal/importer/external_ref_test.go:197:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
internal/importer/external_ref_test.go:295:27: not enough arguments in call to sqlite.New
	have (string)
	want (context.Context, string)
internal/importer/importer_test.go:566:27: not enough arguments in call to sqlite.New
	have (st
... (truncated, see full output in logs)
```

Released by executor after budget limit hit. Tests were already fixed manually. Issue can be closed when tests are verified to pass.


Fix or remove TestFindJSONLPathDefault (issue #356)

Code health review found .test-skip permanently skips TestFindJSONLPathDefault.

The test references issue #356 about wrong JSONL filename expectations (issues.jsonl vs beads.jsonl).

Test file: internal/beads/beads_test.go

The underlying migration from beads.jsonl to issues.jsonl may be complete, so either:
1. Fix the test expectations
2. Remove the test if no longer needed
3. Document why it remains skipped


Add prefix-based routing with routes.jsonl

## Summary

When running `bd show gt-xyz` from a location where that bead doesn't exist locally,
bd should check a `routes.jsonl` file to find where beads with that prefix live.

## Problem

From ~/gt (town root):
- `bd show hq-xxx` works (hq-* beads are local)
- `bd show gt-xxx` fails (gt-* beads live in gastown/mayor/rig)

This breaks `gt hook`, `gt handoff`, and `gt prime` which need to verify beads exist.

## Solution

Add `.beads/routes.jsonl` for prefix-based routing:

\`\`\`json
{"prefix": "gt-", "path": "gastown/mayor/rig"}
{"prefix": "hq-", "path": "."}
{"prefix": "bd-", "path": "beads/crew/dave"}
\`\`\`

### Lookup Algorithm

1. Try local .beads/ first (current behavior)
2. If not found, check for routes.jsonl in current .beads/
3. Match ID prefix against routes
4. If match found, resolve path relative to routes file location and retry
5. If still not found, error as usual

### Affected Commands

Read operations that take a bead ID:
- bd show <id>
- bd update <id>
- bd close <id>
- bd dep add <id> <dep> (both IDs)

Write operations (bd create) still go to local .beads/ - no change needed.

## Implementation Notes

1. New file: routes.jsonl in .beads/ directory
2. New function: resolveBeadsPath(id string) (string, error)
3. Update: beads.Show(), beads.Update(), beads.Close(), etc. to use resolver
4. Caching: Can cache routes in memory since file rarely changes

## Context

This unblocks the gt handoff flow for Mayor. Currently gt handoff gt-xyz fails
because it can't verify the bead exists when running from town root.


Code smell: Long function flushToJSONLWithState (~280 lines)

The flushToJSONLWithState() function in cmd/bd/autoflush.go (lines 490-772) is ~280 lines with:

1. Multiple nested conditionals
2. Inline helper function definitions (recordFailure, recordSuccess)
3. Complex multi-repo filtering logic
4. Mixed concerns (validation, export, error handling)

Consider breaking into:
- validateJSONLIntegrity() - already exists but could absorb more
- getIssuesToExport(fullExport bool) - determines what to export
- mergeWithExistingJSONL(issueMap, dirtyIDs) - handles incremental merge
- filterByPrefix(issues) - multi-repo prefix filtering
- performExport(issues, jsonlPath) - the actual write
- updateMetadataAfterExport() - hash/timestamp updates

Location: cmd/bd/autoflush.go:490-772


Test event


Run tests and linting

go test -short ./... && golangci-lint run ./...


Create Docker image for Agent Mail

Containerize Agent Mail server for easy deployment.

Acceptance Criteria:
- Dockerfile with Python 3.14
- Health check endpoint
- Volume mount for storage
- Environment variable configuration
- Multi-arch builds (amd64, arm64)

File: deployment/agent-mail/Dockerfile


Add monitoring and alerting

Observability for production Agent Mail server.

Acceptance Criteria:
- Health check endpoint (/health)
- Prometheus metrics export
- Grafana dashboard
- Alerts for server downtime
- Alerts for high error rate
- Log aggregation config

File: deployment/agent-mail/monitoring/


Document sandbox workarounds for GH #353

Add documentation for sandbox troubleshooting and new flags.

**Tasks:**
1. Create or update TROUBLESHOOTING.md with sandbox section
2. Document new flags in CLI reference
3. Add comment to GH #353 with immediate workarounds

**Content needed:**
- Symptoms of daemon lock issues in sandboxed environments
- Usage guide for --sandbox, --force, and --allow-stale flags
- Step-by-step troubleshooting for Codex users
- Examples of each escape hatch

**Files to update:**
- docs/TROUBLESHOOTING.md (create if needed)
- docs/CLI_REFERENCE.md or README.md
- GitHub issue #353

**References:**
- docs/GH353_INVESTIGATION.md (lines 240-276)


Merge: bd-c7y5

branch: polecat/toast
target: main
source_issue: bd-c7y5
rig: beads


Support P-prefix priority format (P0-P4) in create and update commands


Test prefix bd


Test suite hangs/never finishes

Running 'go test ./... -count=1' hangs indefinitely. The full test suite never completes, making it difficult to verify changes. Need to investigate which tests are hanging and fix or add timeouts.


bd status "Recent Activity" is misleading - should use git history

## Problem

`bd status` shows "Recent Activity (last 7 days)" but the numbers are wrong. It only looks at database timestamps, not git history. Says "141 issues closed in last 7 days" when thousands have actually come and go.

## Issues

1. Only queries database timestamps, not git history
2. 7 days is too long a window
3. Numbers don't reflect actual activity in JSONL git history

## Proposed Fix

Either:
- Query git history of `.beads/beads.jsonl` to get actual activity (last 24-48 hours)
- Remove "Recent Activity" section entirely if not useful
- Make time window configurable and default to 24h

## Example Output (Current)
```
Recent Activity (last 7 days):
Issues Created:    174
Issues Closed:     141
Issues Updated:    37
```
This is misleading when thousands of issues have actually cycled through.


Improve test coverage for internal/lockfile (42.0% → 60%)

The lockfile package has only 42.0% test coverage. Lock file handling is critical for preventing data corruption in concurrent scenarios.

Current coverage: 42.0%
Target coverage: 60%


Merge: flint-mjtmdf12

branch: polecat/flint-mjtmdf12
target: main
source_issue: flint-mjtmdf12
rig: beads

Stale MR - branch no longer exists on remote


Improve integration test coverage for stateful features


Consider using types.Status in merge package for type safety

The merge package uses string for status comparison (e.g., result.Status == closed, issue.Status == StatusTombstone). The types package defines Status as a type alias with validation. While the merge package needs its own Issue struct for JSONL flexibility, it could import and use types.Status for constants to get compile-time type checking. Current code: if left == closed || right == closed. Could be: if left == string(types.StatusClosed). This is low priority since string comparison works correctly. Files: internal/merge/merge.go:44, 488, 501-521

Added StatusClosed constant derived from types.StatusClosed and replaced hardcoded strings with the constant for type safety


Support separate branch for beads commits

Allow beads to commit to a separate branch (e.g., beads-metadata) using git worktrees to support protected main branch workflows.

Solves GitHub Issue #205 - Users need to protect main branch while maintaining beads workflow.

Key advantages:
- Works on any git platform
- Main branch stays protected
- No disruption to user's working directory
- Backward compatible (opt-in via config)
- Minimal disk overhead (sparse checkout)

Total estimate: 17-24 days (4-6 weeks with parallel work)


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


Integration test: mutation to export latency

Measure time from bd create to JSONL update. Verify <500ms latency. Test with multiple rapid mutations to verify batching.


Merge: opal-1767138520240

branch: polecat/opal-1767138520240
target: main
source_issue: opal-1767138520240
rig: beads


RemoveDependency fails on external deps - FK violation in dirty_issues

In dependencies.go:225, RemoveDependency marks BOTH issueID and dependsOnID as dirty. For external refs (e.g., external:project:capability), dependsOnID doesn't exist in the issues table. This causes FK violation since dirty_issues.issue_id has FK constraint to issues.id.

Fix: Check if dependsOnID starts with 'external:' and only mark source issue as dirty, matching the logic in AddDependency (lines 162-170).

Repro: bd dep rm <issue> external:project:capability


bd validate - Comprehensive health check

Run all validation checks in one command.

Checks:
- Duplicates
- Orphaned dependencies
- Test pollution
- Git conflicts

Supports --fix-all for auto-repair.

Depends on bd-cbed9619.1, bd-0dcea000, bd-31aab707, bd-9826b69a.

Files: cmd/bd/validate.go (new)


Implement git worktree management

Create git worktree lifecycle management for separate beads branch.

Tasks:
- Create internal/git/worktree.go
- Implement CreateBeadsWorktree(branch, path)
- Implement RemoveBeadsWorktree(path)
- Implement CheckWorktreeHealth(path)
- Configure sparse checkout (only .beads/)
- Implement SyncJSONLToWorktree()
- Handle worktree errors gracefully
- Auto-cleanup on config change

Estimated effort: 3-4 days


Test RPC mutation event


Issue 1 to reopen


Update version to 0.33.2 in version.go

Edit cmd/bd/version.go line 17:

```go
Version = "0.33.2"
```

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


Break run-bump-script into individual version-update steps

Replace the monolithic `run-bump-script` step with individual steps for each file:

## Steps to Create

1. **bump-version-go** - Update cmd/bd/version.go
```bash
sed -i "" "s/Version = \"[^\"]*\"/Version = \"{{version}}\"/" cmd/bd/version.go
```

2. **bump-plugin-json** - Update .claude-plugin/*.json
```bash
jq ".version = \"{{version}}\"" .claude-plugin/plugin.json > tmp && mv tmp .claude-plugin/plugin.json
jq ".plugins[0].version = \"{{version}}\"" .claude-plugin/marketplace.json > tmp && mv tmp .claude-plugin/marketplace.json
```

3. **bump-mcp-python** - Update MCP package
```bash
sed -i "" "s/version = \"[^\"]*\"/version = \"{{version}}\"/" integrations/beads-mcp/pyproject.toml
sed -i "" "s/__version__ = \"[^\"]*\"/__version__ = \"{{version}}\"/" integrations/beads-mcp/src/beads_mcp/__init__.py
```

4. **bump-npm-package** - Update npm package
```bash
jq ".version = \"{{version}}\"" npm-package/package.json > tmp && mv tmp npm-package/package.json
```

5. **bump-hook-templates** - Update hook versions
```bash
for f in cmd/bd/templates/hooks/*; do
  sed -i "" "s/# bd-hooks-version: .*/# bd-hooks-version: {{version}}/" "$f"
done
```

6. **bump-readme** - Update README badge
```bash
sed -i "" "s/Alpha (v[^)]*)/Alpha (v{{version}})/" README.md
```

7. **stamp-changelog** - Add date to [Unreleased]
```bash
DATE=$(date +%Y-%m-%d)
sed -i "" "s/## \[Unreleased\]/## [Unreleased]\n\n## [{{version}}] - $DATE/" CHANGELOG.md
```

## Notes
- Each step should have `needs` pointing to the previous step
- Commands should work on both macOS and Linux (may need platform detection)
- The existing update-changelog step handles content; stamp-changelog just adds the date


GH#146: No color showing in terminal for some users

User reports color not working in macOS (Taho 26.0.1) with iTerm 3.6.4 and Terminal.app, despite color working elsewhere in terminal. Python rich and printf escape codes work.

Need to investigate:
- Is NO_COLOR env var set?
- Terminal type detection?
- fatih/color library configuration
- Does bd list show colors? bd ready? bd init?
- What's the output of: echo $TERM, echo $NO_COLOR


Add composite index (status, priority) for common list queries

SearchIssues and GetReadyWork frequently filter by status and sort by priority. Currently uses two separate indexes.

**Common query pattern (queries.go:1646-1647):**
```sql
WHERE status = ?
ORDER BY priority ASC, created_at DESC
```

**Problem:** Index merge or full scan when both columns are used.

**Solution:** Add migration:
```sql
CREATE INDEX IF NOT EXISTS idx_issues_status_priority ON issues(status, priority);
```

**Expected impact:** Faster bd list, bd ready with filters. Particularly noticeable at 10K+ issues.


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.


Review PR #917: fix(doctor) duplicate detection

dispatched_by: beads/crew/emma

Review and merge PR #917 from aaron-sangster.

PR: https://github.com/anthropics/beads/pull/917
Changes: +281/-3, 2 files (cmd/bd/doctor/validation.go, test)

Fix: align duplicate detection with bd duplicates (bd-sali)

Review checklist:
- [ ] Code quality and style
- [ ] Tests pass
- [ ] Logic is correct
- [ ] Approve or request changes


Consider consolidating config.yaml parsing into shared utility

Multiple places parse config.yaml with custom structs:

1. **autoimport.go:148** - `localConfig{SyncBranch}`
2. **main.go:310** - strings.Contains for no-db (fragile, see bd-r6k2)
3. **doctor.go:863** - strings.Contains for no-db (fragile, see bd-r6k2)
4. **internal/config/config.go** - Uses viper (but caches at startup, problematic for tests)

Consider creating a shared utility in `internal/configfile/` or extending the viper config:

```go
// internal/configfile/yaml.go
type YAMLConfig struct {
    SyncBranch string `yaml:"sync-branch"`
    NoDb       bool   `yaml:"no-db"`
    IssuePrefix string `yaml:"issue-prefix"`
    Author     string `yaml:"author"`
}

func LoadYAML(beadsDir string) (*YAMLConfig, error) {
    // Parse config.yaml with proper YAML library
}
```

Benefits:
- Single source of truth for config.yaml structure
- Proper YAML parsing everywhere
- Easier to add new config fields

Trade-off: May add complexity for simple one-off reads.


Add AI planning docs management guidance to bd onboard (GH-196)

Enhanced bd onboard command to provide guidance for managing AI-generated planning documents (Claude slop).

Addresses GitHub issue #196: https://github.com/steveyegge/beads/issues/196

Changes:
- Added Managing AI-Generated Planning Documents section to bd onboard
- Recommends using history/ directory for ephemeral planning files
- Updated AGENTS.md to demonstrate the pattern
- Added comprehensive tests

Commit: d46177d


Perpetual 'JSONL file hash mismatch detected (bd-160)' warning

After cleanup operations, every bd command shows:
```
⚠  WARNING: JSONL file hash mismatch detected (bd-160)
  This indicates JSONL and export_hashes are out of sync.
  Clearing export_hashes to force full re-export.
```

The warning appears repeatedly even after the hash is supposedly cleared. This suggests either:
1. The clear isn't persisting
2. Something keeps causing the mismatch
3. The detection logic has a bug

**Impact:** Warning fatigue - users ignore it, may miss real issues.

**Expected behavior:** After clearing export_hashes once, subsequent operations should not show the warning unless there's a new mismatch.


Add --hard flag to bd cleanup to permanently cull tombstones before cutoff date

Currently tombstones persist for 30 days before cleanup prunes them. Need an official way to force-cull tombstones earlier than the default TTL, for scenarios like cleaning house after extended absence where resurrection from old clones is not a concern. Proposed: bd cleanup --hard --older-than N to bypass the 30-day tombstone TTL.


Update LINTING.md with current baseline

After cleanup, document the remaining acceptable baseline in LINTING.md so we can track regression.


bd-hv01: Missing cleanup of .merged temp file on failure

Problem: deletion_tracking.go:49 creates tmpMerged file but does not clean up on failure, causing disk space leak and potential interference with subsequent syncs.

Fix: Add defer os.Remove(tmpMerged) after creating temp file path.

Files: cmd/bd/deletion_tracking.go:38-89


Add daemon RPC endpoints for config and stale check

Two TODOs request daemon RPC endpoints:

1. cmd/bd/create.go:208 - Add RPC method to get config in daemon mode
2. cmd/bd/mol_stale.go:67 - Add RPC endpoint for stale check

These would allow the CLI to query the daemon for configuration and staleness checks instead of reading directly.

Files:
- cmd/bd/create.go:208
- cmd/bd/mol_stale.go:67

Implemented GetConfig and MolStale RPC endpoints. CLI commands now work in daemon mode.


Merge: quartz-1767083470444

branch: polecat/quartz-1767083470444
target: main
source_issue: quartz-1767083470444
rig: beads

Branch polecat/quartz-1767083470444 no longer exists on remote


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.


bd create --parent allocates colliding child IDs when child_counters not backfilled

GH#728: When explicit child IDs are created (--id bd-test.1) or imported from JSONL, child_counters table isn't updated. Then --parent auto-allocation starts at 1 and collides.

Fix approach: Update child_counters when creating issues with explicit hierarchical IDs that match <parent>.<n> pattern.


Push release v0.33.2 to remote

Push the commit and tag:

```bash
git push && git push --tags
```

Verify on GitHub that the tag appears in releases.


Design molecule step hooks

Hooks that fire between molecule steps. When a bead in a molecule closes, trigger hook that can spawn agent attention to prompts/requests. This enables reactive orchestration - the molecule drives, hooks respond. Gas Town feature built on Beads data plane.


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.


Version Bump: 0.32.1

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


Implement bd mol stale command

Add command to detect complete-but-unclosed molecules.

**Definition of stale:**
A molecule is stale if:
1. All children are closed (Completed >= Total)
2. Root issue is still open
3. Not assigned to anyone
4. Not pinned to any hook
5. AND it's blocking other assigned work (graph pressure)

**Command design:**
```bash
bd mol stale              # List stale mols
bd mol stale --json       # Machine-readable
bd mol stale --blocking   # Only show those blocking other work
bd mol stale --all        # Include orphaned-but-not-blocking
```

**Output:**
```
Stale molecules (complete but unclosed, blocking work):

  bd-xyz  "Version bump v0.36.0"  (blocking: bd-abc, bd-def)
    → Close with: bd close bd-xyz
    → Or squash: bd mol squash bd-xyz

Orphaned molecules (complete but unclosed, not blocking):
  bd-uvw  "Old patrol cycle"
    → Consider: bd mol burn bd-uvw
```

**Implementation:**
1. Query all open issues with children (potential mols)
2. Compute progress for each (Completed vs Total)
3. Filter to complete ones
4. Check assigned_to field
5. Check pinned status (may need gt integration)
6. Check if blocking other assigned work

Does NOT use time-based staleness. Graph pressure only.


bd graph crashes with --no-daemon on closed issues

The `bd graph` command panics with nil pointer dereference when using `--no-daemon` flag on an issue with closed children.

**Reproduction:**
```bash
bd graph bd-qqc --no-daemon
# panic: runtime error: invalid memory address or nil pointer dereference
# in main.computeDependencyCounts
```

**Stack trace:**
```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x20 pc=0x1010bdfb0]

goroutine 1 [running]:
main.computeDependencyCounts(...)
    /Users/stevey/gt/beads/crew/emma/cmd/bd/graph.go:428
main.renderGraph(0x1400033bb80, 0x0)
    /Users/stevey/gt/beads/crew/emma/cmd/bd/graph.go:307 +0x300
```

**Location:** cmd/bd/graph.go:428 - computeDependencyCounts() not handling nil case


Merge: bd-u2sc.3

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


Code review follow-up for bd-dvd and bd-ymj fixes

Track improvements and issues identified during code review of parent resurrection (bd-dvd) and export metadata (bd-ymj) bug fixes.

## Context
Code review identified several areas for improvement:
- Code duplication in metadata updates
- Missing multi-repo support
- Test coverage gaps
- Potential race conditions

## Related Issues
Original bugs fixed: bd-dvd, bd-ymj

## Goals
- Eliminate code duplication
- Add multi-repo support where needed
- Improve test coverage
- Address edge cases


Extract duplicated metadata update code in daemon_sync.go

## Problem
The same 22-line metadata update block appears identically in both:
- createExportFunc (lines 309-328)
- createSyncFunc (lines 520-539)

This violates DRY principle and makes maintenance harder.

## Solution
Extract to helper function:

```go
// updateExportMetadata updates last_import_hash and related metadata after a successful export.
// This prevents "JSONL content has changed since last import" errors on subsequent exports (bd-ymj fix).
func updateExportMetadata(ctx context.Context, store storage.Storage, jsonlPath string, log daemonLogger) {
    currentHash, err := computeJSONLHash(jsonlPath)
    if err != nil {
        log.log("Warning: failed to compute JSONL hash for metadata update: %v", err)
        return
    }

    if err := store.SetMetadata(ctx, "last_import_hash", currentHash); err != nil {
        log.log("Warning: failed to update last_import_hash: %v", err)
    }

    exportTime := time.Now().Format(time.RFC3339)
    if err := store.SetMetadata(ctx, "last_import_time", exportTime); err != nil {
        log.log("Warning: failed to update last_import_time: %v", err)
    }

    // Store mtime for fast-path optimization
    if jsonlInfo, statErr := os.Stat(jsonlPath); statErr == nil {
        mtimeStr := fmt.Sprintf("%d", jsonlInfo.ModTime().Unix())
        if err := store.SetMetadata(ctx, "last_import_mtime", mtimeStr); err != nil {
            log.log("Warning: failed to update last_import_mtime: %v", err)
        }
    }
}
```

## Files
- cmd/bd/daemon_sync.go

## Benefits
- Easier maintenance
- Single source of truth
- Consistent behavior


Fix hasJSONLChanged to support per-repo metadata keys

## Problem
After bd-ar2.2, we store metadata with per-repo keys like `last_import_hash:<path>`, but `hasJSONLChanged` and `validatePreExport` still only check global keys.

## Impact
- Multi-repo mode won't benefit from bd-ymj fix
- validatePreExport will fail incorrectly or pass incorrectly
- Metadata updates are written but never read

## Location
- cmd/bd/integrity.go:97 (hasJSONLChanged)
- cmd/bd/integrity.go:138 (validatePreExport)

## Solution
Update hasJSONLChanged to accept optional keySuffix parameter:
```go
func hasJSONLChanged(ctx context.Context, store storage.Storage, jsonlPath string, keySuffix string) bool {
    // Build metadata keys with optional suffix
    hashKey := "last_import_hash"
    mtimeKey := "last_import_mtime"
    if keySuffix != "" {
        hashKey += ":" + keySuffix
        mtimeKey += ":" + keySuffix
    }
    // ... rest of function
}
```

Update all callers to pass correct keySuffix.


Use stable repo identifiers instead of full paths in metadata keys

## Problem
bd-ar2.2 uses full absolute paths as metadata key suffixes:
```go
updateExportMetadata(exportCtx, store, path, log, path)
// Creates: last_import_hash:/Users/stevey/src/cino/beads/repo1/.beads/issues.jsonl
```

## Issues
1. Absolute paths differ across machines/clones
2. Keys are very long
3. If user moves repo or clones to different path, metadata becomes orphaned
4. Metadata won't be portable across team members

## Better Approach
Use source_repo identifiers from multi-repo config (e.g., ".", "../frontend"):
```go
// Get mapping of jsonl_path -> source_repo identifier
for _, path := range multiRepoPaths {
    repoKey := getRepoKeyForPath(path)  // e.g., ".", "../frontend"
    updateExportMetadata(exportCtx, store, path, log, repoKey)
}
```

This creates stable keys like:
- `last_import_hash:.`
- `last_import_hash:../frontend`

## Related
Depends on bd-ar2.10 (hasJSONLChanged update)


Add validation and documentation for metadata key format

## Issues

### 1. No validation that keySuffix doesn't contain separator
```go
if keySuffix != "" {
    hashKey += ":" + keySuffix  // ❌ What if keySuffix contains ":"?
}
```

Add validation:
```go
if strings.Contains(keySuffix, ":") {
    return fmt.Errorf("keySuffix cannot contain ':' separator")
}
```

### 2. Inconsistent keySuffix semantics
Empty string means "global", non-empty means "scoped". Better to always pass explicit key:
```go
const (
    SingleRepoKey = "."
    // Multi-repo uses source_repo identifier
)
```

### 3. Metadata key format not documented
Need to document:
- `last_import_hash` - single-repo mode
- `last_import_hash:<repo_key>` - multi-repo mode
- `last_import_time` - when last import occurred
- `last_import_mtime` - fast-path optimization

Add to internal/storage/sqlite/schema.go or docs/


Add multi-repo support to export metadata updates

## Problem
The bd-ymj fix only updates metadata for the main jsonlPath, but the codebase supports multi-repo mode where exports write to multiple JSONL files.

Other daemon_sync operations handle multi-repo correctly:
- Lines 509-518: Snapshots captured for all multi-repo paths
- Lines 578-587: Deletions applied for all multi-repo paths

But metadata updates are missing!

## Investigation Needed
Metadata is stored globally in database (`last_import_hash`, `last_import_mtime`), but multi-repo has per-repo JSONL files. Current schema may not support tracking multiple JSONL files.

Options:
1. Store metadata per-repo (new schema)
2. Store combined hash of all repos
3. Document that multi-repo doesn't need this metadata (why?)

## Solution (if needed)
```go
// After export
if multiRepoPaths := getMultiRepoJSONLPaths(); multiRepoPaths != nil {
    // Multi-repo mode: update metadata for each JSONL
    for _, path := range multiRepoPaths {
        updateExportMetadata(exportCtx, store, path, log)
    }
} else {
    // Single-repo mode: update metadata for main JSONL
    updateExportMetadata(exportCtx, store, jsonlPath, log)
}
```

## Files
- cmd/bd/daemon_sync.go (createExportFunc, createSyncFunc)
- Possibly: internal/storage/sqlite/metadata.go (schema changes)

## Related
Depends on bd-ar2.1 (extract helper function first)


Fix TestExportUpdatesMetadata to test actual daemon functions

## Problem
TestExportUpdatesMetadata (daemon_sync_test.go:296) manually replicates the metadata update logic rather than calling the fixed functions (createExportFunc/createSyncFunc).

This means:
- Test verifies the CONCEPT works
- But doesn't verify the IMPLEMENTATION in the actual daemon functions
- If daemon code is wrong, test still passes

## Current Test Flow
```go
// Test does:
exportToJSONLWithStore()  // ← Direct call
// ... manual metadata update ...
exportToJSONLWithStore()  // ← Direct call again
```

## Should Be
```go
// Test should:
createExportFunc(...)()  // ← Call actual daemon function
// ... verify metadata was updated by the function ...
createExportFunc(...)()  // ← Call again, should not fail
```

## Challenge
createExportFunc returns a closure that's run by the daemon. Testing this requires:
- Mock logger
- Proper context setup
- Git operations might need mocking

## Files
- cmd/bd/daemon_sync_test.go

## Acceptance Criteria
- Test calls actual createExportFunc and createSyncFunc
- Test verifies metadata updated by daemon code, not test code
- Both functions tested (export and sync)


Use TryResurrectParentChain instead of TryResurrectParent in GetNextChildID

## Context
Current bd-dvd fix uses TryResurrectParent, which only resurrects the immediate parent. For deeply nested hierarchies, this might not be sufficient.

## Example Scenario
Creating child with parent "bd-abc.1.2" where:
- bd-abc exists in DB
- bd-abc.1 was deleted (missing from DB, exists in JSONL)
- bd-abc.1.2 was deleted (missing from DB, exists in JSONL)

Current fix: Only tries to resurrect "bd-abc.1.2", fails because its parent "bd-abc.1" is missing.

## Solution
Replace TryResurrectParent with TryResurrectParentChain:

```go
if count == 0 {
    // Try to resurrect entire parent chain from JSONL history (bd-dvd fix)
    // This handles deeply nested hierarchies where intermediate parents are also missing
    resurrected, err := s.TryResurrectParentChain(ctx, parentID)
    if err != nil {
        return "", fmt.Errorf("failed to resurrect parent chain for %s: %w", parentID, err)
    }
    if !resurrected {
        return "", fmt.Errorf("parent issue %s does not exist and could not be resurrected from JSONL history", parentID)
    }
}
```

## Investigation
- Check if this scenario actually happens in practice
- TryResurrectParentChain already exists (resurrection.go:174-209)
- May be overkill if users always create parents before children

## Files
- internal/storage/sqlite/hash_ids.go

## Testing
Add test case for deeply nested resurrection


Add error handling guidance for export metadata update failures

## Problem
The bd-ymj fix treats all metadata update failures as warnings:

```go
if err := store.SetMetadata(ctx, "last_import_hash", currentHash); err != nil {
    log.log("Warning: failed to update last_import_hash: %v", err)
}
```

But if metadata updates fail, the NEXT export will fail with "JSONL content has changed since last import".

## Questions
1. Should metadata failures be critical (return error)?
2. Should we implement retry logic?
3. Is warning acceptable (safe, just requires import before next export)?

## Current Behavior
- Metadata failure is silent (only logged)
- User won't know until next export fails
- Next export requires import first (safe but annoying)

## Recommendation
Add clear comment explaining the trade-off:

```go
// Note: Metadata update failures are treated as warnings, not errors.
// This is acceptable because the worst case is the next export will
// require an import first, which is safe and prevents data loss.
// Alternative: Make this critical and fail the export if metadata
// updates fail (but this makes exports more fragile).
if err := store.SetMetadata(ctx, "last_import_hash", currentHash); err != nil {
    log.log("Warning: failed to update last_import_hash: %v", err)
    log.log("Next export may require running 'bd import' first")
}
```

## Files
- cmd/bd/daemon_sync.go

## Decision Needed
Choose approach based on failure mode preferences


Add transaction boundaries for export metadata updates

## Problem
Metadata updates happen after export, but there's no transaction ensuring atomicity between:
1. JSONL file write (exportToJSONLWithStore)
2. Metadata update (updateExportMetadata)
3. Database mtime update (TouchDatabaseFile)

If process crashes between these steps, metadata will be inconsistent.

## Example Failure Scenario
```
1. Export to JSONL succeeds
2. [CRASH] Process killed before metadata update
3. Next export: "JSONL content has changed" error
4. User must run import to fix metadata
```

## Options

### Option 1: Tolerate Inconsistency (Current)
- Simple, no code changes
- Safe (worst case: need import before next export)
- Annoying for users if crashes are frequent

### Option 2: Add Write-Ahead Log
- Write metadata intent to temp file
- Complete operations
- Clean up temp file
- More complex, better guarantees

### Option 3: Store Metadata in JSONL Comments
- Add metadata as JSON comment in JSONL file
- Single atomic write
- Requires JSONL format change

### Option 4: Defensive Checks
- On startup, verify metadata matches JSONL
- Auto-fix if mismatch detected
- Simplest improvement

## Recommendation
Start with Option 4 (defensive checks), consider others if needed.

## Files
- cmd/bd/daemon_sync.go
- Possibly: cmd/bd/main.go (startup checks)

## Related
This is lower priority - current behavior is safe, just not ideal


Add edge case tests for GetNextChildID parent resurrection

## Current Coverage
TestGetNextChildID_ResurrectParent tests happy path only:
- Parent exists in JSONL
- Resurrection succeeds

## Missing Test Cases

### 1. Parent Not in JSONL
- Parent doesn't exist in DB
- Parent doesn't exist in JSONL either
- Should return: "could not be resurrected from JSONL history"

### 2. JSONL File Missing
- Parent doesn't exist in DB
- No issues.jsonl file exists
- Should handle gracefully

### 3. Malformed JSONL
- Parent doesn't exist in DB
- JSONL file exists but has invalid JSON
- Should skip bad lines, continue searching

### 4. Concurrent Resurrections
- Multiple goroutines call GetNextChildID with same parent
- Only one should resurrect, others should succeed
- Test for race conditions

### 5. Deeply Nested Missing Parents
- Creating bd-abc.1.2.1 where:
  - bd-abc exists
  - bd-abc.1 missing (should fail with current fix)
- Related to bd-ar2.4

### 6. Content Hash Mismatch
- Parent in JSONL has different content_hash than expected
- Should still resurrect (content_hash is for integrity, not identity)

## Files
- internal/storage/sqlite/child_id_test.go

## Implementation
```go
func TestGetNextChildID_ResurrectParent_NotInJSONL(t *testing.T) { ... }
func TestGetNextChildID_ResurrectParent_NoJSONL(t *testing.T) { ... }
func TestGetNextChildID_ResurrectParent_MalformedJSONL(t *testing.T) { ... }
func TestGetNextChildID_ResurrectParent_Concurrent(t *testing.T) { ... }
```


Add edge case tests for export metadata updates

## Current Coverage
TestExportUpdatesMetadata tests basic happy path only.

## Missing Test Cases

### 1. Multi-Repo Mode
- Export with multi-repo configuration
- Verify metadata updated for ALL JSONL files
- Critical gap (related to bd-ar2.2)

### 2. computeJSONLHash Failure
- JSONL file deleted/inaccessible after export
- Should log warning, not crash
- Verify behavior on next export

### 3. SetMetadata Failures
- Database write-protected
- Disk full
- Should log warnings, continue

### 4. os.Stat Failure
- JSONL file deleted after export, before stat
- Should handle gracefully (mtime just not updated)

### 5. Concurrent Exports
- Two daemon instances export simultaneously
- Verify metadata doesn't get corrupted
- Race condition test

### 6. Clock Skew
- System time goes backward between exports
- Verify mtime handling still works

### 7. Partial Export Failure
- Multi-repo mode: some exports succeed, some fail
- What metadata should be updated?

### 8. Large JSONL Files
- Performance test with large files (10k+ issues)
- Verify hash computation doesn't timeout

## Files
- cmd/bd/daemon_sync_test.go

## Implementation Priority
1. Multi-repo test (P1 - related to critical issue)
2. Failure handling tests (P2)
3. Performance/edge cases (P3)


Fix variable shadowing in GetNextChildID resurrection code

## Problem
Minor variable shadowing in hash_ids.go:

```go
// Line 33: err declared here
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM issues WHERE id = ?`, parentID).Scan(&count)

// Line 38: err reused/shadowed here
resurrected, err := s.TryResurrectParent(ctx, parentID)
```

While Go allows this, it can be confusing and some linters flag it.

## Solution
Use different variable name:

```go
resurrected, resurrectErr := s.TryResurrectParent(ctx, parentID)
if resurrectErr != nil {
    return "", fmt.Errorf("failed to resurrect parent %s: %w", parentID, resurrectErr)
}
```

## Files
- internal/storage/sqlite/hash_ids.go:38

## Priority
Low - code works correctly, just a style improvement


bd sync fails from crew dirs with .beads/redirect pointing outside repo

## Problem

`bd sync` fails at the final git-status check when run from a crew directory that uses `.beads/redirect` to point to a shared beads directory in another repo.

```
Error: checking git status after re-export: git status failed: exit status 128
```

The underlying error is:
```
fatal: /path/to/mayor/rig/.beads: is outside repository at '/path/to/crew/wolf'
```

## Root Cause

`gitHasBeadsChanges()` in `cmd/bd/sync_git.go:93-111` runs:
```go
statusCmd := exec.CommandContext(ctx, "git", "status", "--porcelain", beadsDir)
```

When `beadsDir` resolves to a path outside the current git repo (via redirect), git fails.

## Affected Scenario

- Crew workers (`crew/wolf`) with `.beads/redirect` → `../../mayor/rig/.beads`
- The redirect points to a different git clone
- Sync actually succeeds (commit/push/pull/import all work) but fails at final validation

## Workaround

Run `bd sync` from the directory containing the actual `.beads/` (e.g., `mayor/rig`).

## Suggested Fix

`gitHasBeadsChanges()` should detect redirects and run git commands from the directory containing the actual `.beads/`, not from cwd.

Fixed: gitHasBeadsChanges() and gitHasUncommittedBeadsChanges() now detect redirects and run git commands from the target repository directory


Session ended: gt-beads-crew-emma


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


Add global verbosity flags (--verbose, --quiet)

Add consistent verbosity controls across all commands.

**Current state:**
- bd init has --quiet flag
- No other commands have verbosity controls
- Debug output controlled by BD_VERBOSE env var

**Proposal:**
Add persistent flags:
- --verbose / -v: Enable debug output
- --quiet / -q: Suppress non-essential output

**Implementation:**
- Add to rootCmd.PersistentFlags()
- Replace BD_VERBOSE checks with flag checks
- Standardize output levels:
  * Quiet: Errors only
  * Normal: Errors + success messages
  * Verbose: Errors + success + debug info

**Files to modify:**
- cmd/bd/main.go (add flags)
- internal/debug/debug.go (respect flags)
- Update all commands to respect quiet mode

**Testing:**
- Verify --verbose shows debug output
- Verify --quiet suppresses normal output
- Ensure errors always show regardless of mode