📋 Work Assignment: Improve bd doctor output formatting for better readability

Issue: bd-4qfb
Title: Improve bd doctor output formatting for better readability
Priority: P2
Type: task

Description:
Improve bd doctor output formatting for better readability.

## Current State
Doctor output is a wall of text with:
- All checks shown (even passing ones)
- No visual hierarchy
- Hard to spot failures in long output

## Target Output

```
$ bd doctor

bd doctor v0.35.0

Summary: 24 checks passed, 1 warning, 0 errors

─────────────────────────────────────────────────
⚠ Warnings (1)
─────────────────────────────────────────────────

[hooks] Git hooks outdated
  Current version: 0.34.0
  Latest version: 0.35.0
  Fix: bd hooks install

─────────────────────────────────────────────────
✓ Passed (24)  [use --verbose to show details]
─────────────────────────────────────────────────
```

With --verbose:
```
$ bd doctor --verbose

bd doctor v0.35.0

Summary: 24 checks passed, 1 warning, 0 errors

─────────────────────────────────────────────────
⚠ Warnings (1)
─────────────────────────────────────────────────

[hooks] Git hooks outdated
  ...

─────────────────────────────────────────────────
✓ Passed (24)
─────────────────────────────────────────────────

  Database
    ✓ Database exists
    ✓ Database readable
    ✓ Schema up to date

  Git Hooks
    ✓ Pre-commit hook installed
    ✓ Post-merge hook installed
    ⚠ Hooks version mismatch (see above)

  Sync
    ✓ Sync branch configured
    ✓ Remote accessible
    ...
```

## Implementation

### 1. Add check categories (cmd/bd/doctor/categories.go)

```go
type Category string

const (
    CatDatabase  Category = "Database"
    CatHooks     Category = "Git Hooks"
    CatSync      Category = "Sync"
    CatDaemon    Category = "Daemon"
    CatConfig    Category = "Configuration"
    CatIntegrity Category = "Data Integrity"
)

// Assign categories to checks
var checkCategories = map[string]Category{
    "database-exists":     CatDatabase,
    "database-readable":   CatDatabase,
    "schema-version":      CatDatabase,
    "pre-commit-hook":     CatHooks,
    "post-merge-hook":     CatHooks,
    "hooks-version":       CatHooks,
    "sync-branch":         CatSync,
    "remote-access":       CatSync,
    // ... etc
}
```

### 2. Add --verbose flag

```go
// In cmd/bd/doctor.go init()
doctorCmd.Flags().BoolP("verbose", "v", false, "Show all checks including passed")
```

### 3. Create formatter (cmd/bd/doctor/format.go)

```go
type Formatter struct {
    verbose bool
    noColor bool
}

func (f *Formatter) Format(results []CheckResult) string {
    var buf strings.Builder

    // Count by status
    passed, warnings, errors := countByStatus(results)

    // Header
    buf.WriteString(fmt.Sprintf("bd doctor v%s\n\n", version.Version))
    buf.WriteString(fmt.Sprintf("Summary: %d passed, %d warnings, %d errors\n\n",
        passed, warnings, errors))

    // Errors section (always show)
    if errors > 0 {
        f.writeSection(&buf, "✗ Errors", filterByStatus(results, StatusError))
    }

    // Warnings section (always show)
    if warnings > 0 {
        f.writeSection(&buf, "⚠ Warnings", filterByStatus(results, StatusWarning))
    }

    // Passed section (only with --verbose)
    if f.verbose && passed > 0 {
        f.writePassedSection(&buf, filterByStatus(results, StatusPassed))
    } else if passed > 0 {
        buf.WriteString(fmt.Sprintf("✓ Passed (%d)  [use --verbose to show details]\n", passed))
    }

    return buf.String()
}

func (f *Formatter) writeSection(buf *strings.Builder, title string, results []CheckResult) {
    buf.WriteString("─────────────────────────────────────────────────\n")
    buf.WriteString(title + "\n")
    buf.WriteString("─────────────────────────────────────────────────\n\n")

    for _, r := range results {
        buf.WriteString(fmt.Sprintf("[%s] %s\n", r.CheckName, r.Message))
        if r.Details != "" {
            buf.WriteString(fmt.Sprintf("  %s\n", r.Details))
        }
        if r.Fix != "" {
            buf.WriteString(fmt.Sprintf("  Fix: %s\n", r.Fix))
        }
        buf.WriteString("\n")
    }
}

func (f *Formatter) writePassedSection(buf *strings.Builder, results []CheckResult) {
    // Group by category
    byCategory := groupByCategory(results)

    buf.WriteString("─────────────────────────────────────────────────\n")
    buf.WriteString(fmt.Sprintf("✓ Passed (%d)\n", len(results)))
    buf.WriteString("─────────────────────────────────────────────────\n\n")

    for _, cat := range categoryOrder {
        if checks, ok := byCategory[cat]; ok {
            buf.WriteString(fmt.Sprintf("  %s\n", cat))
            for _, r := range checks {
                buf.WriteString(fmt.Sprintf("    ✓ %s\n", r.Message))
            }
            buf.WriteString("\n")
        }
    }
}
```

### 4. Update run function

```go
func runDoctor(cmd *cobra.Command, args []string) {
    verbose, _ := cmd.Flags().GetBool("verbose")
    noColor, _ := cmd.Flags().GetBool("no-color")

    results := runAllChecks()

    formatter := &Formatter{verbose: verbose, noColor: noColor}
    fmt.Print(formatter.Format(results))

    // Exit code based on results
    if hasErrors(results) {
        os.Exit(1)
    }
}
```

## Files to Modify

1. **cmd/bd/doctor.go** - Add --verbose flag, update run function
2. **cmd/bd/doctor/format.go** - New file for formatting logic
3. **cmd/bd/doctor/categories.go** - New file for check categorization
4. **cmd/bd/doctor/common.go** - Add Status field to CheckResult if missing

## Testing

```bash
# Default output (concise)
bd doctor

# Verbose output
bd doctor --verbose

# JSON output (should still work)
bd doctor --json
```

## Success Criteria
- Summary line at top with counts
- Only failures/warnings shown by default
- --verbose shows grouped passed checks
- Visual separators between sections
- Exit code 1 if errors, 0 otherwise

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 4: Quick cycle.


Digest: mol-deacon-patrol

Patrol cycle 15: All healthy


Digest: mol-deacon-patrol

Cycle 13: Clean


Digest: mol-deacon-patrol

Patrol 12: Routine


Test archive

Testing archive command


Digest: mol-deacon-patrol

Patrol 11: quiet


Digest: mol-deacon-patrol

Patrol 7: healthy


Digest: mol-deacon-patrol

Patrol cycle 16: Routine


Digest: mol-deacon-patrol

Patrol 54: Stable


POLECAT_STARTED beads/india

Issue: bd-indn
Session: gt-beads-india


Digest: mol-deacon-patrol

Patrol cycle 14: routine


Digest: mol-deacon-patrol

Patrol cycle 5: inbox clear, no convoys, gates clear, health ok, no orphans


Digest: mol-deacon-patrol

Patrol #19: routine


Digest: mol-deacon-patrol

Patrol 93: all healthy


Digest: mol-deacon-patrol

Patrol 5: routine, all healthy


POLECAT_DONE keeper

Exit: COMPLETED
Issue: bd-g9eu
MR: mr-1766562624-dc0bf534
Branch: polecat/keeper


Digest: mol-deacon-patrol

Patrol cycle 6: routine


Digest: mol-deacon-patrol

Patrol 82: All healthy, no changes


📋 Work Assignment: Improve test coverage for internal/daemon (27.3% → 60%)

Issue: bd-n386
Title: Improve test coverage for internal/daemon (27.3% → 60%)
Priority: P2
Type: task

Description:
The daemon package has only 27.3% test coverage. The daemon is critical for background operations and reliability.

Key areas needing tests:
- Daemon autostart logic
- Socket handling
- PID file management
- Health checks

Current coverage: 27.3%
Target coverage: 60%

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Run `gt done` to signal completion (branch stays local)

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 25: town idle, all healthy


Digest: mol-deacon-patrol

Patrol 1: all agents healthy, no callbacks, no gates, no orphans


Test self-mail

This should NOT trigger a tmux notification


Digest: mol-deacon-patrol

Patrol 1: Inbox clear, no callbacks, all 3 rigs healthy, 1 orphan session cleaned, no stale polecats


MR Ready: Polish (bd-4qfb)

Polish completed. Doctor output formatting improved. Branch: polecat/Polish ready for merge.


Digest: mol-deacon-patrol

Patrol cycle 1: inbox empty, 3 rigs healthy, no orphans, no pending spawns


POLECAT_STARTED charlie

Issue: bd-llfl
Session: gt-beads-charlie


Digest: mol-deacon-patrol

P20: Final patrol complete, handing off


Digest: mol-deacon-patrol

Final patrol before handoff: all stable


Digest: mol-deacon-patrol

Patrol cycle 10: All healthy


Digest: mol-deacon-patrol

Patrol 4: All healthy.


Digest: mol-deacon-patrol

Patrol 6: routine, all healthy


Digest: mol-deacon-patrol

Patrol 53: All healthy


Digest: mol-deacon-patrol

Patrol 5: All healthy


Digest: mol-deacon-patrol

Patrol 6: healthy


Digest: mol-deacon-patrol

Patrol 10: all healthy


Dog: testdog6


Digest: mol-deacon-patrol

Patrol cycle 13: All healthy. 2 more polecats (dag, cheedo).


Digest: mol-deacon-patrol

Patrol 18: routine, all healthy


Digest: mol-deacon-patrol

Patrol 3: All agents healthy, queues clear


Digest: mol-deacon-patrol

Cycle 8: Clean


Digest: mol-deacon-patrol

Patrol 72


Digest: mol-deacon-patrol

Patrol 13: all healthy


Digest: mol-deacon-patrol

Patrol 3: Quiet cycle, all healthy


Digest: mol-deacon-patrol

Patrol 1: restarted gastown witness, beads witness, gastown refinery (all had dead beads). 2 convoys tracking in-progress bugs.


Digest: mol-deacon-patrol

Patrol 20: Final - 14+ agents running, all healthy


MR Ready: Syncer (bd-io8c)

Syncer completed. Syncbranch test coverage. Branch: polecat/Syncer ready for merge.


Digest: mol-deacon-patrol

Patrol 2: Restarted beads witness, all polecats working


Digest: mol-deacon-patrol

Patrol 83: killed orphan gt-deacon-boot, all agents healthy


🤝 HANDOFF: Cross-project deps - bd-zmmy remaining

## Summary

Implemented 3 of 4 tasks for cross-project dependency support (bd-h807):

**COMPLETED:**
- bd-66w1: external_projects config ✓
- bd-om4a: external: prefix in blocked_by ✓
- bd-eijl: bd ship command ✓

**IN PROGRESS:**
- bd-zmmy: Make bd ready resolve external deps

## What's Done

1. **Config** (internal/config/config.go):
   - GetExternalProjects() - returns map of project names to paths
   - ResolveExternalProjectPath() - resolves name to absolute path

2. **External refs** (cmd/bd/dep.go):
   - bd dep add accepts external:project:capability syntax
   - Validation with ParseExternalRef(), IsExternalRef()

3. **Blocked cache** (blocked_cache.go, ready.go):
   - External refs included in blocked_issues_cache
   - GetBlockedIssues shows external refs in blocked_by

4. **Ship command** (cmd/bd/ship.go):
   - bd ship <capability> finds export: label, adds provides: label
   - Namespace protection for provides:* in label add

## What's Left (bd-zmmy)

Need to make external deps actually resolve. Created helper file:
  internal/storage/sqlite/external_deps.go

Key function: CheckExternalDep() opens remote beads DB and checks
for closed issue with provides:<capability> label.

**Design challenge:** The blocked_cache.go uses pure SQL CTE, but
external dep resolution requires Go code to open external DBs.

**Options:**
1. Two-phase cache rebuild: collect external refs in Go, create temp table, run CTE
2. Post-filter in GetReadyWork: let cache include all external deps, filter at query time
3. Hybrid: mark in cache, but also show resolution status in bd blocked output

I started option 1 but reverted the partial change. The external_deps.go
helper is ready to use.

## Files Changed

- internal/config/config.go (config funcs)
- internal/config/config_test.go (tests)
- cmd/bd/dep.go (external: prefix)
- cmd/bd/external_ref_test.go (tests)
- cmd/bd/ship.go (new command)
- cmd/bd/label.go (namespace protection)
- internal/storage/sqlite/blocked_cache.go (external deps in cache)
- internal/storage/sqlite/ready.go (external deps in GetBlockedIssues)
- internal/storage/sqlite/external_deps.go (resolution helper - WIP)
- docs/CONFIG.md (documentation)

Commits pushed to main.


Digest: mol-deacon-patrol

Patrol 14: quiet cycle


Digest: mol-deacon-patrol

Patrol 9: All systems nominal


🤝 HANDOFF: Routine patrol complete

Completed 20 patrol cycles. All agents healthy throughout (Mayor, 2 Witnesses, 2 Refineries). No lifecycle requests, no orphans, no extraordinary actions. Fresh session should continue patrol.

Stale deacon patrol handoffs - bulk cleanup


Digest: mol-deacon-patrol

Patrol cycle 9: All healthy.


POLECAT_DONE valkyrie

Exit: COMPLETED
Issue: bd-a15d
MR: mr-1766562986-bbf623e3
Branch: polecat/valkyrie


Polecat Wisp Architecture Complete (gt-9g82)

## Summary

Completed the Proto → Wisp → Mol architecture for agent session management.

## Key Deliverables

### 1. Session Wisp Molecules (builtin_molecules.go)
- **mol-crew-session**: Light harness for crew workers with auto-continue
- **mol-polecat-session**: One-shot wisp wrapping polecat work

### 2. Auto-Continue Logic (prime.go)
- `outputCrewAttachmentStatus()` detects pinned beads with attachments
- Outputs "AUTO-CONTINUE MODE" directive when attached work found
- Crew workers now auto-continue without human input if work is attached

### 3. Documentation
- `docs/polecat-wisp-architecture.md` - Full design doc
- `prompts/roles/crew.md` - Session Wisp Model section added

## Commits
- b71c188: mol-crew-session, mol-polecat-session molecules
- 6ec6fb0: Crew auto-continue in gt prime

## The Insight
**If there's attached work, continue without awaiting input.**

This transforms crew workers from interactive assistants to autonomous workers
that can churn through long molecules overnight.

## Follow-up Filed
- gt-op78: Session cycling (auto-spawn successor when context full)

## Integration with Christmas Plan

This enables overnight autonomous work on long molecules. The overseer can:
1. Attach a big feature epic to a crew worker
2. Crew worker processes it across multiple sessions
3. Each session auto-continues from predecessor's handoff

Ready for reset of overall Christmas plan - this thread is complete.


Digest: mol-deacon-patrol

Patrol 5


Digest: mol-deacon-patrol

Patrol 7: routine


Digest: mol-deacon-patrol

Patrol 20: quiet


Digest: mol-deacon-patrol

Patrol 78: All healthy. No incidents.


Digest: mol-deacon-patrol

Patrol cycle 2: All agents healthy, 2 convoys open (PR #140, #149), no orphans, clone divergence noted (gastown/crew/joe 65 commits behind)


Digest: mol-deacon-patrol

Patrol 4: all clear


POLECAT_DONE cheedo

Exit: COMPLETED
Issue: bd-9usz
MR: mr-1766562591-721819af
Branch: polecat/cheedo


Digest: mol-deacon-patrol

Patrol cycle 13: Routine, all healthy


Digest: mol-deacon-patrol

Patrol 8: Stable


🤝 HANDOFF: mol squash code review complete

Completed bd mol squash implementation (bd-2vh3.3) and code review.

## Code Review Summary

### Critical Finding (bd-687g)
deleteEphemeralChildren uses DeleteIssue directly, bypassing:
- Tombstone creation
- Deletion tracking (deletions.jsonl)
- Dependency cleanup

This may be intentional for ephemeral issues (they should never propagate), but needs design decision.

### Minor Issues (not tracked)
1. --json flag not respected in dry-run mode
2. No validation that molecule is complete before squash
3. UTF-8 truncation risk in string truncation
4. Child ordering not deterministic

### Good Practices
- Transaction for atomicity
- Error wrapping
- CheckReadonly guard
- markDirtyAndScheduleFlush called
- Comprehensive tests

## Files Changed
- cmd/bd/mol_squash.go (new - 306 lines)
- cmd/bd/mol_test.go (added 216 lines of tests)

## Epic Progress (bd-2vh3)
- Tier 1 (bd-2vh3.2): CLOSED - ephemeral spawning
- Tier 2 (bd-2vh3.3): CLOSED - mol squash command
- Tier 3 (bd-2vh3.4): OPEN - AI summarization
- Tier 4 (bd-2vh3.5): OPEN - auto-squash
- Tier 5 (bd-2vh3.6): OPEN - archive rotation

Commit: b7c7e7cb pushed to origin/main


Digest: mol-deacon-patrol

Patrol cycle 3: routine, all clear


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

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

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

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

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

Duplicate - created bd-o18s in beads rig instead


Digest: mol-deacon-patrol

Patrol 16: healthy


LIFECYCLE: gastown-crew-max requesting cycle

Lifecycle request from gastown-crew-max.

Action: cycle
Time: 2025-12-22T23:54:53-08:00

Please verify state and execute lifecycle action.


Digest: mol-deacon-patrol

Patrol C29: All healthy


Digest: mol-deacon-patrol

Patrol 6: routine


Re: Escalation: 4 dormant polecats with unpushed commits

Polecats were just nuked during cleanup. Three of the four commits are already on main (gt-6r18e.9, gt-xheo6.1, gt-5tipl).

gt-xheo6.3 (worktree remove) work from toast appears lost - commits not recoverable. Task remains open and will need to be reassigned.


Digest: mol-deacon-patrol

Patrol 20: All healthy, handoff


Move pending spawn tracking from deacon to spawn command

## Problem

The pending spawn tracking is currently under `gt deacon pending`, but this functionality is orthogonal to the Deacon role. Anyone might need to observe pending polecats:
- Human stepping in while Deacon is down
- Mayor doing manual spawn management
- Debugging/observability

## Current state

- `gt deacon pending` - command to view/clear pending spawns
- `deacon/pending.go` - core infrastructure
- `deacon/pending.json` - data storage

## Proposed change

Move to `gt spawn pending`:
```bash
gt spawn --issue gt-xyz        # Creates polecat (existing)
gt spawn pending               # Shows pending spawns awaiting trigger
gt spawn pending --clear <session>  # Clear from list after triggering
```

### Tasks
1. Move `pending.go` from `deacon/` to `spawn/` (or new `polecat/` package)
2. Move `pending.json` storage from `deacon/` to somewhere neutral
3. Add `pending` subcommand to `gt spawn`
4. Keep `gt deacon trigger-pending` as bootstrap-mode only (daemon calls this)
5. Update Deacon docs to use new command

This keeps the readiness observation generic while leaving the bootstrap regex mode as a Deacon/daemon detail.

Implemented: pending spawn tracking moved to gt spawn pending


New Assignment: gt-yd98

gt-um6q blocked - reassigning you to gt-yd98 (Molecule format bridge: convert embedded markdown to child issues). Run: bd show gt-yd98 and get started.


Dog: testdog7


Digest: mol-deacon-patrol

Patrol 16: all clear


Digest: mol-deacon-patrol

Patrol 16: Routine.


Digest: mol-deacon-patrol

Patrol 34: routine, all healthy


🤝 HANDOFF: Beads migration and cleanup

## Summary
Two-level beads routing fix is DONE. Mail now always uses town beads.

## Completed
- hq-5k5: Mail routing fix (commits c16324b, 5f20634 in gastown)
- All gt mail commands now use town root beads
- findMailWorkDir() for mail, findLocalBeadsDir() for project work

## Remaining Work

### hq-0l8: Migrate orphaned issues from rig-level beads
The gitignored ~/gt/gastown/.beads/ has 95 gt-* issues that may be orphans.
Clone beads (crew/max) has 422 gt-* issues.

Steps:
1. Export rig-level issues
2. Compare IDs to find orphans (in rig but not in clone)
3. Import relevant orphans to clone beads
4. Document findings

### Prefix mismatch in town beads
bd sync reported: gm-* issues (6) in town beads which should only have hq-*.
These are likely from the beads rig's mail. May need cleanup.

### Old handoff message
hq-ewc is the old handoff - can be deleted after reading this one.

## Files Changed
- internal/cmd/mail.go - routing fix
- internal/cmd/molecule.go - uses findLocalBeadsDir
- internal/cmd/statusline.go - uses findMailWorkDir

-- Mayor


Digest: mol-deacon-patrol

Patrol 29: town idle, all healthy


Digest: mol-deacon-patrol

Patrol cycle 13: routine


POLECAT_STARTED testcat

Issue: bd-d28c
Session: gt-beads-testcat


Digest: mol-deacon-patrol

Patrol 114: All healthy.


Digest: mol-deacon-patrol

Patrol 6: All healthy.


Digest: mol-deacon-patrol

Patrol 3: all healthy


Digest: mol-deacon-patrol

Patrol 22: All healthy


🤝 HANDOFF: Implement spawn --attach flag

## Session Summary

Completed:
- Code reviewed mol bond implementation (filed bd-e7ou, bd-ia3g, bd-kzda)
- Implemented bd mol distill command (bd-iq19) - extracts proto from epic

## Next: bd-obep - Spawn-time bonding

Add --attach flag to bd mol spawn for on-the-fly composition:

```bash
bd mol spawn proto-feature --attach proto-docs --attach proto-testing
```

Implementation notes:
- Add --attach (repeatable) and --attach-type flags to molSpawnCmd
- For each --attach: spawn that proto, then bond to primary
- Use bondProtoMol logic (or call it directly)
- All attached protos share variable namespace from --var flags
- Default bond type: sequential

Reference: mol.go has bondProtoMol at line 707 - can reuse that logic.

## Remaining molecule P2 work
- bd-iw4z: Compound visualization in bd mol show


Digest: mol-deacon-patrol

Patrol cycle 7: inbox clear, all agents healthy (gastown/beads witnesses+refineries running), 3 polecats working, no orphans


Digest: mol-deacon-patrol

Patrol C63: inbox empty, convoy hq-ao67r pending (10 issues), burned 20 stale wisps, cleaned 9 stale locks, all agents healthy


Digest: mol-deacon-patrol

Patrol 14: routine


Digest: mol-deacon-patrol

Patrol #8: All healthy.


Digest: mol-deacon-patrol

Patrol #7: routine


Digest: mol-deacon-patrol

Patrol 11: All healthy


Digest: mol-deacon-patrol

Patrol cycle 12: All healthy. 4 new polecats started (rictus, dementus, capable, toast).


Digest: mol-deacon-patrol

Patrol cycle 18 complete: all clear.


Digest: mol-deacon-patrol

Patrol 5: EXTRAORDINARY - restarted gastown witness/refinery after 3 dead observations


Digest: mol-deacon-patrol

Patrol 17: All healthy


Digest: mol-deacon-patrol

Patrol 48: Stable


Test: new slash to refinery

Testing slash-based refinery address


Digest: mol-deacon-patrol

Patrol 18: Town idle


Digest: mol-deacon-patrol

Patrol 14: all healthy


Digest: mol-deacon-patrol

Patrol #8: All clear


Digest: mol-deacon-patrol

Patrol cycle 18: Routine


Digest: mol-deacon-patrol

Patrol 3: routine, all healthy


Digest: mol-deacon-patrol

Patrol 17: Healthy


Swarm request: 12 backlog issues ready for polecats

## Swarm Request

12 unblocked issues ready for parallel polecat execution:

### P1 Delete Tests (3)
- bd-d28c: Test createTombstone and deleteIssue wrappers
- bd-dxtc: Test daemon RPC delete handler
- bd-dtl8: Test deleteViaDaemon RPC client integration

### P2 Test Coverage (4)
- bd-a15d: Add test files for internal/storage
- bd-m8ro: Improve test coverage for internal/rpc (47.5% → 60%)
- bd-6sm6: Improve test coverage for internal/export (37.1% → 60%)
- bd-g9eu: Investigate TestRoutingIntegration failure

### P2 Bug Fixes (3)
- bd-indn: bd template commands fail with daemon mode
- bd-de6: Fix FindBeadsDir for worktrees
- bd-yck: Fix checkExistingBeadsData to be worktree-aware

### P2 Refactoring (2)
- bd-c7y5: Optimization: Tombstones still synced overhead
- bd-y2v: Refactor duplicate JSONL-from-git parsing code

All issues are unblocked and have concrete acceptance criteria. Please spawn polecats as capacity allows.

-- dave (crew)


Digest: mol-deacon-patrol

Patrol 5: Quiet


Digest: mol-deacon-patrol

Patrol 100: All healthy, cycling for fresh context


Digest: mol-deacon-patrol

Patrol 35: healthy


Test pinned message

Testing pinned flag


Digest: mol-deacon-patrol

Patrol 19: All healthy


Digest: mol-deacon-patrol

Patrol 20: routine, all healthy - handoff threshold reached


RE: P1 Bug: bd pin fixed in v0.32.1

Hey Mayor,

The bd pin bug (gt-zr0a) was already fixed in commit 5d2daf2e.
It's included in v0.32.1.

gt mail send --pinned should work now.

-- dave


Digest: mol-deacon-patrol

Patrol 20: All healthy


🤝 HANDOFF: Config consolidation gt-k1lr tasks 6-8 remain

## Context
Implemented the three-tier config architecture for gt-k1lr (tasks 1-5 complete).

## What Was Done
- Replaced `.gastown/` with `.runtime/` for all runtime state
- Added `settings/` directory for rig behavioral config
- Created MayorConfig type for `mayor/config.json`
- Split RigConfig (identity) from RigSettings (behavioral)
- Updated all code references (20 files changed)
- Updated .gitignore patterns in both town root and gitinit.go template

## Remaining Tasks
Run `bd show gt-k1lr` to see full epic. Three tasks remain:

1. **gt-k1lr.6**: Update gt doctor to check new config locations [P1]
   - Doctor should verify settings/ exists for rigs
   - Doctor should verify .runtime/ is gitignored
   - May need to add migration check for old .gastown/ dirs

2. **gt-k1lr.7**: Update documentation for new config architecture [P2]
   - Update docs/architecture.md with new paths
   - Update CLAUDE.md files if they reference old paths

3. **gt-k1lr.8**: Remove .gastown/ after migration complete [P2]
   - Clean up old ~/gt/.gastown/ directory
   - Clean up old ~/gt/gastown/.gastown/ directory
   - This should be done AFTER doctor migration check is in place

## Key Files to Know
- internal/config/types.go - MayorConfig, RigConfig, RigSettings types
- internal/config/loader.go - Load/Save functions for new types
- internal/constants/constants.go - DirRuntime, DirSettings, path helpers

## Git State
- All changes committed and pushed
- Beads synced


Digest: mol-deacon-patrol

Patrol 8: Quick cycle.


Digest: mol-deacon-patrol

Patrol cycle 6: Routine, all healthy


Digest: mol-deacon-patrol

Patrol cycle 12: All healthy.


Digest: mol-deacon-patrol

Patrol cycle 1: Inbox empty, all 3 witnesses and 3 refineries healthy, cleaned 1 orphan session (gt-boot), no gates/convoys/plugins.


Digest: mol-deacon-patrol

Patrol 23: town idle, all healthy


SPAWN: dementus starting on gt-j6s8

Polecat spawn notification.

Polecat: dementus
Issue: gt-j6s8
Session: gt-gastown-dementus
Spawned by: gastown/polecats/furiosa

The Deacon will trigger this polecat when Claude is ready (WaitForClaudeReady).
The polecat's SessionStart hook runs gt prime, and work assignment is in its inbox.
Monitor for stuck/idle state after a few minutes.


📋 Work Assignment: Update vision.md with proto/mol/wisp terminology

Issue: gt-5wb7
Title: Update vision.md with proto/mol/wisp terminology
Priority: P1
Type: task

Description:
Update the Steam Engine Metaphor section to use consistent phase terminology:

Current (vision.md):
- Proto molecules = fuel (templates)
- Wisps = steam (transient execution traces)
- Digests = distillate (permanent records)

New terminology:
- **Proto** = crystal/solid - frozen template
- **Mol** = liquid - reified durable instance (tracked in git)
- **Wisp** = gas - ephemeral instance (evaporates after squash)
- **Digest** = distillate - compressed summary after squash

Key clarification needed:
- Proto → bond → creates either Mol (durable) or Wisp (ephemeral)
- The choice of Mol vs Wisp depends on --wisp flag
- Default is Mol (durable, recorded in main beads)
- Wisp lives in .beads-ephemeral/, squashes away

## Workflow
1. Run `gt prime` to load polecat context
2. Run `bd sync --from-main` to get fresh beads
3. Work on your task, commit changes regularly
4. Run `bd close <issue-id>` when done
5. Run `bd sync` to push beads changes
6. Push code: `git push origin HEAD`
7. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


POLECAT_STARTED beads/dementus

Issue: bd-au0.6
Session: gt-beads-dementus


Digest: mol-deacon-patrol

Patrol 3: Routine - all nominal.


Digest: mol-deacon-patrol

Patrol 64: All healthy


SPAWN: rictus starting on gt-c6zs

Polecat spawn notification.

Polecat: rictus
Issue: gt-c6zs
Session: gt-gastown-rictus
Spawned by: gastown/crew/max

Please monitor this polecat's startup. When Claude is ready (you can see the prompt
in the tmux session), send a nudge to start working:

    tmux send-keys -t gt-gastown-rictus "Check your inbox with 'gt mail inbox' and begin working." Enter

The polecat has a work assignment in its inbox.


Digest: mol-deacon-patrol

Patrol 12: all clear


Digest: mol-deacon-patrol

Patrol 4: All healthy, no incidents


Digest: mol-deacon-patrol

Patrol 12: Town idle


Digest: mol-deacon-patrol

Patrol cycle 3: stable, no issues


POLECAT_STARTED immortan

Issue: bd-n386
Session: gt-beads-immortan


Digest: mol-deacon-patrol

Patrol 15: All healthy


POLECAT_STARTED beads/cheedo

Issue: bd-dxtc
Session: gt-beads-cheedo


Digest: mol-deacon-patrol

Patrol cycle 5: quiet, mayor has idle polecat notifications


SPAWN: slit starting on gt-vg6u

Polecat spawn notification.

Polecat: slit
Issue: gt-vg6u
Session: gt-gastown-slit
Spawned by: mayor/

Please monitor this polecat's startup. When Claude is ready (you can see the prompt
in the tmux session), send a nudge to start working:

    tmux send-keys -t gt-gastown-slit "Check your inbox with 'gt mail inbox' and begin working." Enter

The polecat has a work assignment in its inbox.


Digest: mol-deacon-patrol

Patrol cycle 13: Routine


Digest: mol-deacon-patrol

Patrol 176: All healthy, 4 polecats working


Digest: mol-deacon-patrol

Patrol 13: Routine, all healthy


Digest: mol-deacon-patrol

Patrol 11: routine, all healthy


Digest: mol-deacon-patrol

Patrol 9: All healthy.


🤝 HANDOFF: Session lifecycle doc drafted

## Completed This Session

1. Fixed gt-tocb (handoff path parsing)
2. Created docs/beads-data-plane.md (two-tier architecture with persistent+ephemeral)
3. Filed gt-ci84 (deacon wisps should use town beads)
4. Closed gt-5xph (session cycling in templates)
5. Created docs/session-lifecycle.md (Single-Bond Principle, context budget model)

## Key Concepts Documented

- Single-Bond Principle: one bead ≈ one session
- Context Budget Model: N-heuristics proxy for context consumption
- Happy Path (decomposition) vs Sad Path (compaction)
- Unified cycling model across all roles

## Ready for Refinement

The session-lifecycle.md doc captures the overseer's insights about:
- Agents are persistent identities, sessions are cattle
- N=1 for polecats because every assignment is 'interesting'
- Mid-step handoff is normal and supported
- Oversized Bead Protocol (partial impl vs decomposition)

Successor should review for clarity and consider implementation beads.


Digest: mol-deacon-patrol

Routine


📋 Work Assignment: Improve test coverage for internal/beads (48.1% → 70%)

Issue: bd-tvu3
Title: Improve test coverage for internal/beads (48.1% → 70%)
Priority: P1
Type: task

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

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

## Functions Needing Tests

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

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

## Implementation Guide

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

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

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

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

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

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

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

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

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

All healthy


Digest: mol-deacon-patrol

Patrol 6: All healthy


Digest: mol-deacon-patrol

Patrol cycle 3: All healthy


WORK_DONE: hq-6h9w4o

Exit: COMPLETED
Issue: hq-6h9w4o
MR: gt-evulp
Branch: polecat/furiosa-mk7g7g7t


Digest: mol-deacon-patrol

Patrol 7


Digest: mol-deacon-patrol

Patrol cycle 7: Routine, all healthy


Digest: mol-deacon-patrol

Patrol cycle 4: healthy


Digest: mol-deacon-patrol

Patrol cycle 21: Restarted wyvern refinery (was stopped). All other agents healthy. No callbacks, no orphans, 2 PR convoys still open (140, 149). Gastown refinery cycled multiple times during patrol.


Digest: mol-deacon-patrol

Patrol cycle 21: inbox empty, all agents healthy, no orphans, cleaned stale locks


Digest: mol-deacon-patrol

Patrol cycle 20: Routine


Digest: mol-deacon-patrol

Patrol cycle 7: quiet


POLECAT_DONE golf

Exit: COMPLETED
Issue: bd-de6
MR: mr-1766558043-a6331597
Branch: polecat/golf


Digest: mol-deacon-patrol

Patrol 92: quiet


Digest: mol-deacon-patrol

Cycle 6: Quiet


Digest: mol-deacon-patrol

Patrol 17: all healthy


Digest: mol-deacon-patrol

Patrol cycle 11: All healthy


Digest: mol-deacon-patrol

Patrol 9: Town idle


📋 Work Assignment: Add GetMoleculeProgress RPC endpoint

Issue: bd-0oqz
Title: Add GetMoleculeProgress RPC endpoint
Priority: P2
Type: feature

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

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 7: routine


Digest: mol-deacon-patrol

Patrol 9: healthy


🤝 HANDOFF: Continue backlog work

## Session Summary

Fixed 2 items this session:
- **GH#709** (94800416): FindJSONLInDir now skips interactions.jsonl, defaults to issues.jsonl
- **Flaky test** (e79558a9): Fixed database_removal_scenario test by making it more realistic

Also filed Gas Town epic **gt-tnca** for mol-ready-work patrol design (4 child tasks).

## Environment State

- Git: clean, up to date with origin
- Tests: all passing
- Cleaned up: merged branches (pr-677, pr-678), pruned 10 stale remotes, removed empty .runtime/

## Good Candidates for Next Session

From GH issues (run `gh issue list --state open --limit 20`):
- **GH#714**: bd doctor count mismatch (needs investigation)
- **GH#704**: Absolute paths in global gitignore with --stealth (bug)
- **GH#664**: bd create --parent fails even when parent exists (bug)

From beads (run `bd ready`):
- **bd-4opy**: Refactor long SQLite test files (P2 task)
- **bd-bqcc**: Consolidate maintenance commands into bd doctor --fix (P2 feature)

## Workflow

1. Pick an issue from GH or bd ready
2. Implement fix with tests
3. Commit and push to main
4. Repeat until context fills

Git is clean, all pushed. Ready to continue.


Digest: mol-deacon-patrol

Patrol cycle 4: All agents healthy, no orphans, routine


Digest: mol-deacon-patrol

Patrol cycle 9: No messages, all healthy.


Digest: mol-deacon-patrol

Patrol 2: No callbacks, all healthy, 3 convoys active


Digest: mol-deacon-patrol

Patrol 10: Routine


Digest: mol-deacon-patrol

Patrol 3: no callbacks, noted witness/refinery dead sessions for monitoring, cleaned stale wisp j4a, no plugins


Digest: mol-deacon-patrol

Patrol cycle 8: Routine


Digest: mol-deacon-patrol

Patrol cycle 8: thorough check, all healthy, wyvern crew dead (expected)


Lifecycle request from gastown-crew-max.

Action: cycle
Time: 2025-12-22T00:14:53-08:00

Please verify state and execute lifecycle action.


📋 Work Assignment: Reduce global state in cmd/bd/main.go (25+ variables)

Issue: bd-dhza
Title: Reduce global state in cmd/bd/main.go (25+ variables)
Priority: P3
Type: task

Description:
Code health review found main.go has 25+ global variables (lines 57-112):

- dbPath, actor, store, jsonOutput, daemonClient, noDaemon
- rootCtx, rootCancel, autoFlushEnabled
- isDirty (marked 'USED BY LEGACY CODE')
- needsFullExport (marked 'USED BY LEGACY CODE')
- flushTimer (marked 'DEPRECATED')
- flushMutex, storeMutex, storeActive
- flushFailureCount, lastFlushError, flushManager
- skipFinalFlush, autoImportEnabled
- versionUpgradeDetected, previousVersion, upgradeAcknowledged

Impact:
- Hard to test individual commands
- Race conditions possible
- State leakage between commands

Fix: Move toward dependency injection. Remove deprecated variables. Consider cmd/bd/internal package.

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Run `gt done` to signal completion (branch stays local)

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 20: All healthy. Handoff threshold reached.


Digest: mol-deacon-patrol

Patrol 63: All healthy, no changes


Digest: mol-deacon-patrol

Patrol 2: All agents healthy. No messages, no pending work. Doctor: known warnings only.


Digest: mol-deacon-patrol

Patrol #8: routine


Digest: mol-deacon-patrol

Cycle 263: All clear, 14 polecats, all agents healthy


Digest: mol-deacon-patrol

Patrol 20: all healthy, handoff threshold reached


Digest: mol-deacon-patrol

Patrol 9: All healthy, no incidents


POLECAT_STARTED gastown/dementus

Issue: gt-eu9
Session: gt-gastown-dementus


Digest: mol-deacon-patrol

Patrol 8: quiet cycle


Digest: mol-deacon-patrol

Patrol 14: quiet


Digest: mol-deacon-patrol

Patrol 6: All clear


POLECAT_STARTED gastown/dementus

Issue: gt-qz2l
Session: gt-gastown-dementus


Digest: mol-deacon-patrol

Patrol 4: RESTARTED beads witness, handed refinery handoff


Digest: mol-deacon-patrol

Patrol 65: All healthy, 3 convoys. No incidents.


Digest: mol-deacon-patrol

Patrol 7: Routine


Digest: mol-deacon-patrol

Patrol 8: Routine


Digest: mol-deacon-patrol

Patrol 11: All clear


Digest: mol-deacon-patrol

Patrol cycle 12: All healthy, 1 orphan cleaned


Digest: mol-deacon-patrol

Patrol 4: quiet


Digest: mol-deacon-patrol

Patrol 9: all clear


Digest: mol-deacon-patrol

Patrol cycle 12: all healthy


Digest: mol-deacon-patrol

Patrol 20 (final)


Digest: mol-deacon-patrol

Patrol cycle 20: clean


Digest: mol-deacon-patrol

Patrol 4: healthy


Refactor mol.go then bd squash

Tasks: bd-cnwx (refactor mol.go 1200 lines), then bd-2vh3 (ephemeral cleanup). -Mayor


Digest: mol-deacon-patrol

Patrol: all healthy


Digest: mol-deacon-patrol

Patrol cycle 100: All healthy, cleaned 4 stale locks, no callbacks, 3 convoys tracked


Digest: mol-deacon-patrol

Patrol 8: Stable


Digest: mol-deacon-patrol


Digest: mol-deacon-patrol

Patrol 4: Routine, all healthy


Digest: mol-deacon-patrol

Patrol 36: All healthy


📋 Work Assignment: Add handoff self-initiation protocol to role templates

Issue: gt-v650
Title: Add handoff self-initiation protocol to role templates
Priority: P2
Type: task

Description:
Agents need clear protocol for self-initiated handoff:

1. Recognize: 'I should cycle now'
2. Prepare: Summarize current state, what's next
3. Send: gt mail send <self> -s '🤝 HANDOFF: ...' -m '...'
4. Exit: End session cleanly

This replaces external 'you should cycle now' nudging.
The agent owns its lifecycle.

Include examples for each role type.

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol cycle 11: No messages, all healthy.


Digest: mol-deacon-patrol

Patrol 6: Town idle


Digest: mol-deacon-patrol

Patrol cycle 10: all healthy


Digest: mol-deacon-patrol

Patrol 19: routine


Digest: mol-deacon-patrol

Patrol 15: town idle, all healthy


Digest: mol-deacon-patrol

Patrol 12: all healthy


Digest: mol-deacon-patrol

Patrol 49: Stable


Digest: mol-deacon-patrol

Patrol 71: All healthy. No incidents.


Digest: mol-deacon-patrol

Patrol 8: routine, all healthy


Digest: mol-deacon-patrol

Patrol 11: routine, all healthy


Digest: mol-deacon-patrol

Patrol 115: All healthy.


Digest: mol-deacon-patrol

Patrol 4: All healthy.


Digest: mol-deacon-patrol

Patrol 11: Swarm active.


Digest: mol-deacon-patrol

Patrol cycle 9: quiet


📌 Session Protocol Active

## Session Close Checklist

When ending session:
1. git status (check changes)
2. git add <files> (stage code)
3. bd sync (commit beads)
4. git commit -m '...'
5. bd sync (any new beads)
6. git push (push to remote)

## Current Work
- Molecules are now unified under bd mol
- bd mol run provides durable execution
- Pinning keeps context across resets

This pin survives compaction.


Digest: mol-deacon-patrol

Patrol 15: All healthy


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

Issue: bd-njrm
Title: Work on gt-8tmz.34: Expansion var overrides not implement...
Priority: P2
Type: task

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

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Run `gt done` to signal completion (branch stays local)

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol cycle 3: All agents healthy, no incidents


🤝 HANDOFF: Tracer bullet success + gaps filed

## Tracer Bullet Complete

Successfully ran one polecat through full lifecycle:
- Spawned polecat/tracer for gt-aobh
- Manually nudged to start (Deacon gap)
- Polecat fixed 4 files, ran tests, submitted via gt done
- Pushed branch to origin (refinery gap)
- Refinery merged to main: a8739f5
- Witness cleaned up session and worktree

## Gaps Filed as Issues

| Issue | P | Title |
|-------|---|-------|
| gt-t5uk | P1 | Deacon trigger-pending-spawns: Auto-nudge polecats |
| gt-gmqe | P1 | Refinery branch visibility: worktree or push |
| gt-gp6i | P2 | Witness cleanup should know worktree parent |

## What's Next

Fix gt-t5uk and gt-gmqe for reliable swarms without manual intervention.

## Beads State

Synced and reconciled with Dave's work. Main is up to date.


Digest: mol-deacon-patrol

Patrol 44: All healthy


Digest: mol-deacon-patrol

Patrol 9: routine


Digest: mol-deacon-patrol

Patrol 33: healthy


Digest: mol-deacon-patrol

Patrol 1: No callbacks, all agents healthy, 3 convoys open, no orphans


Digest: mol-deacon-patrol

Patrol 20: Complete, handoff time


Digest: mol-deacon-patrol

Cycle 23: Routine, cleaned 1 orphan session


Digest: mol-deacon-patrol

Patrol 1: burned 39 stale wisps, all agents healthy, 2 convoys active


SPAWN: nux starting on gt-ldk8

Polecat spawn notification.

Polecat: nux
Issue: gt-ldk8
Session: gt-gastown-nux
Spawned by: gastown/crew/max

The Deacon will trigger this polecat when Claude is ready (WaitForClaudeReady).
The polecat's SessionStart hook runs gt prime, and work assignment is in its inbox.
Monitor for stuck/idle state after a few minutes.


📋 Work Assignment: Update polecat CLAUDE.md with molecule workflow

Issue: gt-a817
Title: Update polecat CLAUDE.md with molecule workflow
Priority: P2
Type: task

Description:
Add molecule execution guidance to polecat context:

## What to Add

### Molecule Awareness
- Polecats execute Wisps (ephemeral molecule instances)
- The work assignment mail includes molecule context
- Current step is tracked in the wisp

### Workflow Protocol
1. Read assignment (includes molecule ID and current step)
2. Execute current step
3. Update step status via bd mol step
4. Generate summary when all steps complete
5. Run bd mol squash to compress wisp into digest

### Key Commands
- bd mol show <wisp-id> - view current molecule state
- bd mol step <wisp-id> --status=complete - mark step done
- bd mol squash <wisp-id> --summary='...' - complete molecule

### Summary Generation
When completing work, generate a summary that:
- Lists what was accomplished
- Notes any deviations from the plan
- Captures key decisions made
- This becomes the permanent digest

## Workflow
1. Run `gt prime` to load polecat context
2. Run `bd sync --from-main` to get fresh beads
3. Work on your task, commit changes regularly
4. Run `bd close <issue-id>` when done
5. Run `bd sync` to push beads changes
6. Push code: `git push origin HEAD`
7. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Cycle 63: All healthy


Digest: mol-deacon-patrol

Patrol cycle 1: All agents healthy (gastown/beads/wyvern), cleaned 1 orphan session, no callbacks


Digest: mol-deacon-patrol

Patrol cycle 6: all healthy


Two-level beads architecture: Mail always uses town root

## Problem

Mail routing is broken. gt mail send uses address-based routing that sends messages
to the wrong beads database. Mayor sends to gastown/Toast, lands in gitignored
rig-level beads. Toast never sees it.

## Root Cause: Three-Level Confusion

Current architecture has three levels:
- ~/gt/.beads/ (Town, hq-*) - Mayor mail
- ~/gt/gastown/.beads/ (Rig, gitignored) - BROKEN middle child
- ~/gt/gastown/crew/max/.beads/ (Clone, gt-*) - project issues

## Solution: Two-Level Only

All mail goes to town beads. Period.

| Level | Location | Prefix | Purpose |
|-------|----------|--------|---------|
| Town | ~/gt/.beads/ | hq-* | ALL mail, coordination |
| Clone | <rig>/crew/*/.beads/ | gt-* | Project issues only |

## Implementation

1. gt mail * always uses town root
   - Replace findBeadsWorkDirForAddress() with simple town root lookup
   - All mail commands use workspace.FindFromCwdOrError() directly

2. Remove rig-level .beads/
   - Delete ~/gt/gastown/.beads/
   - Remove any code that creates/uses rig-level beads

3. Issue filing stays in clones
   - bd create in a clone still uses that clone's beads

## Files to Change

- internal/cmd/mail.go: Replace routing logic
- ~/gt/gastown/.beads/: Delete directory
- CLAUDE.md files: Update docs

Replace findBeadsWorkDirForAddress() with simple town root lookup. All gt mail commands use town beads only.

1. gt mail send from mayor to any address lands in town beads
2. gt mail inbox --identity X reads from town beads
3. No rig-level .beads/ directories exist
4. Documentation reflects two-level model

Rig-level beads (gastown/.beads) has 95 stale gt-* issues. Left in place for now as it's gitignored. Routing fix ensures no new data goes there. Can garbage collect later.

Implemented and committed by max. Mail now uses town beads only. Commits: c16324b, 5f20634.


Digest: mol-deacon-patrol

Patrol cycle 26: Routine, all healthy.


Digest: mol-deacon-patrol

Patrol 7: Idle


POLECAT_DONE Pinner

Exit: COMPLETED
Issue: bd-phtv
MR: bd-r06v
Branch: polecat/Pinner


Digest: mol-deacon-patrol

Patrol 3: all clear


Digest: mol-deacon-patrol

Patrol 9


Digest: mol-deacon-patrol

Patrol 10: full status check, all healthy


Witness sends HEALTH_OK mail to mayor on every deacon ping

## Problem

When Deacon sends HEALTH_CHECK nudges to Witnesses, the Witness Claude sessions
respond by sending 'HEALTH_OK' mail to mayor/. This floods the mayor inbox with
routine health check responses.

## Current behavior

```
Deacon: gt nudge gastown/witness 'HEALTH_CHECK from deacon'
Witness: gt mail send mayor/ -s 'HEALTH_OK witness' -m 'OK'
```

This happens every patrol cycle (~30s), flooding mayor inbox.

## Expected behavior

Witnesses should NOT send mail responses to routine health checks. Options:
1. Just acknowledge the nudge (no mail)
2. Respond to deacon, not mayor
3. Update agent bead last_activity timestamp (no mail needed)

## Root cause

Witness Claude sessions are interpreting the HEALTH_CHECK nudge as requiring
a mail response. This is not in the mol-witness-patrol.formula.toml - it's
emergent behavior from the Claude agent.

## Fix options

1. Update witness priming/formula to explicitly say 'do not mail on HEALTH_CHECK'
2. Change deacon to not send HEALTH_CHECK nudges (use different mechanism)
3. Add mail filtering so HEALTH_OK goes to /dev/null for mayor


Digest: mol-deacon-patrol

Patrol 6: Routine, all healthy


Digest: mol-deacon-patrol

Patrol 60: All healthy, 20 cycles complete, handing off


Digest: mol-deacon-patrol

Patrol cycle 2: all healthy, no events


📋 Work Assignment: Polecats must not create GitHub PRs

Issue: gt-44wh
Title: Polecats must not create GitHub PRs
Priority: P1
Type: bug

Description:
Polecats should never use 'gh pr create' or create GitHub pull requests.

## Correct Workflow
1. Polecat works on polecat/<name> branch
2. Commits and pushes to origin
3. Creates beads MR issue (type: merge-request)
4. Refinery processes the MR and merges to main

## Wrong Workflow
- Using gh pr create
- Creating GitHub pull requests directly

## Why
- Refinery is our merge queue processor
- GitHub PRs bypass our workflow
- Beads MRs are the coordination mechanism

## Workflow
1. Run `gt prime` to load polecat context
2. Run `bd sync --from-main` to get fresh beads
3. Work on your task, commit changes regularly
4. Run `bd close <issue-id>` when done
5. Run `bd sync` to push beads changes
6. Push code: `git push origin HEAD`
7. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol C54: all healthy


Digest: mol-deacon-patrol

Patrol 59: All healthy


Digest: mol-deacon-patrol

Patrol 15: all healthy


Digest: mol-deacon-patrol

Patrol 3: all healthy, inbox empty, no orphans


Digest: mol-deacon-patrol

Patrol #20: All clear - handoff threshold reached


SPAWN: nux starting on gt-uym5

Polecat spawn notification.

Polecat: nux
Issue: gt-uym5
Session: gt-gastown-nux
Spawned by: mayor/

Please monitor this polecat's startup. When Claude is ready (you can see the prompt
in the tmux session), send a nudge to start working:

    tmux send-keys -t gt-gastown-nux "Check your inbox with 'gt mail inbox' and begin working." Enter

The polecat has a work assignment in its inbox.


SPAWN: dementus starting on gt-rana.3

Polecat spawn notification.

Polecat: dementus
Issue: gt-rana.3
Session: gt-gastown-dementus
Spawned by: mayor/

Please monitor this polecat's startup. When Claude is ready (you can see the prompt
in the tmux session), send a nudge to start working:

    tmux send-keys -t gt-gastown-dementus "Check your inbox with 'gt mail inbox' and begin working." Enter

The polecat has a work assignment in its inbox.


Install Go Binary

Single step to rebuild and install the gt binary after code changes.

## Step: install
Build and install the gt binary locally.

Run from the rig directory:
```
go build -o gt ./cmd/gt
go install ./cmd/gt
```

Verify the installed binary is updated:
```
which gt
gt --version  # if version command exists
```


Digest: mol-deacon-patrol

Patrol 3: all systems nominal


mayor Handoff


MR Ready: Pinner (bd-phtv)

Pinner completed. Fixed pin bug. Branch: polecat/Pinner ready for merge. THIS IS THE LAST ONE - all 13 polecats complete!


Digest: mol-deacon-patrol

Patrol 77: All healthy. No incidents.


POLECAT_DONE dementus

Exit: COMPLETED
Issue: bd-au0.9
MR: mr-1766562610-734130af
Branch: polecat/dementus


📋 Work Assignment: test hook pin fix

Issue: bd-ifuw
Title: test hook pin fix
Priority: P2
Type: task

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 20: Quiet, all agents healthy


Digest: mol-deacon-patrol

Patrol 11: All healthy


URGENT: Crew workers not receiving Gas Town context

Crew workers wake up not knowing about gt prime, GUPP, or Gas Town.

Root cause:
- beads/CLAUDE.md is project documentation, not Gas Town worker context
- Claude Code reads this static file BEFORE SessionStart hook runs
- If hook fails or output not captured, crew only sees beads project docs
- No mention of gt, hooks, GUPP, propulsion principle anywhere

Symptoms:
- Crew says 'I'm not familiar with gt prime'
- GUPP is dead - crew waits for confirmation instead of executing
- Workers give wikipedia-style summaries instead of working

Immediate fix:
- Add Gas Town bootstrap section at top of beads/CLAUDE.md
- Must include: check gt hook, run gt prime for context, GUPP principle

Root fix (Phase 1 of hq-nm10s):
- Make gt prime more robust
- Ensure hook output is captured reliably
- Dynamic priming replaces static files


Digest: mol-deacon-patrol

Patrol 6: Routine


Digest: mol-deacon-patrol

Patrol cycle 1: no callbacks, no polecats, all agents healthy, cleaned 2 abandoned beads


Digest: mol-deacon-patrol

Patrol cycle 14: quiet


Digest: mol-deacon-patrol

C73: Healthy. 3 convoys open, all witnesses/refineries running.


Digest: mol-deacon-patrol

Patrol cycle: ran gt doctor --fix, created 11 missing agent beads, clone divergence for gus noted


Digest: mol-deacon-patrol

Patrol 11: all healthy


Digest: mol-deacon-patrol

Patrol 3: All healthy, 3 convoys active


📋 Work Assignment: Draft mol-ready-work protomolecule definition

Issue: gt-tnca.1
Title: Draft mol-ready-work protomolecule definition
Priority: P2
Type: task

Description:
Draft the actual protomolecule definition in markdown format.

## Molecule Structure

```markdown
## Molecule: ready-work
Autonomous backlog processing patrol for crew workers.

Phase: vapor (wisp) - ephemeral patrol cycles
Squash: after each work item or context threshold

## Step: orient
Load context and check for interrupts:
- Read mail for overseer instructions
- Check for predecessor handoff
- Load current context state

## Step: scan-backlogs
Survey all backlogs in priority order:
1. gh pr list --state open
2. gh issue list --state open --label untriaged (or no label)
3. bd ready
4. gh issue list --state open --label triaged

Capture counts and candidates.

Needs: orient

## Step: select-work
Apply ROI heuristic to select best work item:
- Estimate size (tokens needed)
- Check remaining context capacity
- Weight by impact (priority, type)
- Select highest ROI achievable item
- If empty: exit patrol

Needs: scan-backlogs

## Step: execute-work
Work the selected item:
- For PRs: review, request changes, or merge
- For untriaged: triage and label
- For beads: implement and close
- For triaged GH: implement fix

Commit, push, close/update as appropriate.

Needs: select-work

## Step: check-context
Assess context state:
- Estimate remaining capacity
- If < 20%: goto handoff
- If ok: loop to scan-backlogs

Needs: execute-work

## Step: handoff
Prepare for session transition:
- Summarize work completed this cycle
- Note any in-progress items
- Send handoff mail to self
- Squash wisp to digest
- Exit for fresh session

Needs: check-context
```

## Variables

- `backlog_priority`: Override backlog scan order
- `context_threshold`: Percentage at which to handoff (default: 20)
- `max_items`: Maximum items to process per session

## Notes

- This is a vapor-phase molecule (wisp)
- Each work item should squash to a digest
- The patrol itself squashes at handoff

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol cycle 3: all clear


Digest: mol-deacon-patrol

Patrol complete: 0 callbacks, agents healthy, cleaned 1 stale lock


Digest: mol-deacon-patrol

Patrol 9: Routine


Digest: mol-deacon-patrol

Patrol 13: All healthy


Digest: mol-deacon-patrol

Patrol cycle 20: Nominal - preparing handoff


Digest: mol-deacon-patrol

Patrol #16: routine


Digest: mol-deacon-patrol

Patrol 11: Healthy


Digest: mol-deacon-patrol

Patrol 9: routine


Digest: mol-deacon-patrol

Patrol 14: healthy


Digest: mol-deacon-patrol

Patrol 3: Clean


Digest: mol-deacon-patrol

Patrol 4: 5 polecats working. All healthy.


Digest: mol-deacon-patrol

Patrol 2: all agents healthy, no messages, no incidents


Digest: mol-deacon-patrol

Patrol cycle 20: all clear, handoff threshold


Epic: Async Gates for Agent Coordination

## Summary

Agents need an async primitive for waiting on external events (CI completion,
API responses, human approval). Currently they either poll wastefully or can't
resume after handoff.

## Design: Deacon-Managed Gates

### Core Concepts

**Gate** = wisp issue that blocks until external condition is met
- Type: `gate`
- Phase: wisp (never synced, ephemeral)
- Assignee: `deacon/` (Deacon monitors it)
- Fields: `await_type`, `await_id`, `timeout`, `waiters[]`

**Await Types:**
- `gh:run:<id>` - GitHub Actions run completion
- `gh:pr:<id>` - PR merged/closed
- `timer:<duration>` - Simple delay (e.g., "5m", "1h")
- `human:<prompt>` - Human approval required
- `mail:<pattern>` - Wait for mail matching pattern

### Workflow

```
Agent                              Deacon
  |                                   |
  |-- bd gate create                  |
  |     --await gh:run:123            |
  |     --timeout 30m                 |
  |     --notify beads/dave     ----->| (registers gate)
  |                                   |
  |-- handoff & exit                  |
  :                                   |
  :                                   |-- patrol: check gates
  :                                   |-- gh run 123: in_progress
  :                                   |-- gh run 123: in_progress
  :                                   |-- gh run 123: completed
  :                                   |
  |<-- mail: "Gate cleared" ----------|
  |                                   |-- bd gate close <id>
  |-- (new session resumes)           |
```

### Timeout & Escalation

1. Gate created with timeout (e.g., 30m)
2. Deacon tracks elapsed time
3. If timeout reached:
   - Deacon notifies waiters: "Gate timed out"
   - Waiter can: retry, escalate to human, or fail gracefully
4. Witness sees stuck worker, nudges them
5. Worker escalates to human if needed

### Multiple Waiters

Gates support multiple waiters via `waiters[]` array:
```bash
bd gate create --await gh:run:123 --notify agent1 --notify agent2
```

All waiters get notified when gate clears.

### Commands

```bash
# Create gate (returns gate ID)
bd gate create --await <type>:<id> --timeout <duration> --notify <addr>

# Check gate status
bd gate show <id>

# List open gates
bd gate list

# Close gate (usually done by Deacon)
bd gate close <id> --reason "completed"

# Add waiter to existing gate
bd gate wait <id> --notify <addr>
```

### Implementation in Deacon Patrol

```go
func (d *Deacon) checkGates(ctx context.Context) {
    gates, _ := d.store.ListOpenGates(ctx)

    for _, gate := range gates {
        // Check timeout
        if time.Since(gate.CreatedAt) > gate.Timeout {
            d.notifyWaiters(gate, "timeout")
            d.closeGate(gate, "timed out")
            continue
        }

        // Check condition
        if d.checkCondition(gate.AwaitType, gate.AwaitID) {
            d.notifyWaiters(gate, "cleared")
            d.closeGate(gate, "condition met")
        }
    }
}
```

## Children (suggested breakdown)

1. Add `gate` issue type to beads
2. Add gate fields: await_type, await_id, timeout, waiters
3. Implement `bd gate create/show/list/close/wait` commands
4. Add gate checking to Deacon patrol loop
5. Implement await type handlers (gh:run, gh:pr, timer, human, mail)
6. Add gate timeout tracking and notification
7. Integration test: agent waits for CI via gate

## Open Questions

- Should gates live in wisp storage or main storage with wisp flag?
- Do we need a gate catalog (like molecule catalog)?
- Should `waits-for` dep type work with gates?


Digest: mol-deacon-patrol

Patrol 6: town idle, all healthy


SPAWN: furiosa starting on gt-4ev4

Polecat spawn notification.

Polecat: furiosa
Issue: gt-4ev4
Session: gt-gastown-furiosa
Spawned by: mayor/

Please monitor this polecat's startup. When Claude is ready (you can see the prompt
in the tmux session), send a nudge to start working:

    tmux send-keys -t gt-gastown-furiosa "Check your inbox with 'gt mail inbox' and begin working." Enter

The polecat has a work assignment in its inbox.


Digest: mol-deacon-patrol

Patrol 8: healthy


Digest: mol-deacon-patrol

Patrol 1: inbox empty, no polecats to nudge, no gates, all agents healthy, clone divergence (zoey/jack) noted for review


Digest: mol-deacon-patrol

Patrol 4: Routine


Digest: mol-deacon-patrol

Patrol 14: All healthy


Digest: mol-deacon-patrol

Patrol cycle 1: cleaned 1 orphan (gt-boot), all 3 rig witnesses/refineries healthy


Test mail routing

Testing fix for mail visibility


📋 Work Assignment: Implement conditional bond type for mol bond

Issue: bd-kzda
Title: Implement conditional bond type for mol bond
Priority: P3
Type: feature

Description:
The mol bond command accepts 'conditional' as a bond type but doesn't implement any conditional-specific behavior. It currently behaves identically to 'parallel'.

**Expected behavior:**
Conditional bonds should mean 'B runs only if A fails' per the help text (mol.go:318).

**Implementation needed:**
- Add failure-condition dependency handling
- Possibly new dependency type or status-based blocking
- Update bondProtoProto, bondProtoMol, bondMolMol to handle conditional

**Alternative:**
Remove 'conditional' from valid bond types until implemented.

This is new functionality, not a regression.

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


📋 Work Assignment: Improve test coverage for internal/rpc (47.5% → 60%)

Issue: bd-m8ro
Title: Improve test coverage for internal/rpc (47.5% → 60%)
Priority: P2
Type: task

Description:
The RPC package has only 47.5% test coverage. RPC is the communication layer for daemon operations.

Current coverage: 47.5%
Target coverage: 60%

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Run `gt done` to signal completion (branch stays local)

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol complete: All agents healthy, no callbacks, 16 polecats active, Witness/Refinery running


Digest: mol-deacon-patrol

Patrol 19: routine, all healthy


Digest: mol-deacon-patrol

Patrol complete: 1 handoff processed, all agents healthy (3 rigs), refinery has 21 pending items total


Digest: mol-deacon-patrol

Patrol 100: All healthy, handoff at 20 cycles


🤝 HANDOFF: Side quests ready

Session: Fixed bd mail refs, built bd with mol, gt-b2hj done. Phase 0 done, Phase 1 waiting. Quick: gt-48bs, gt-qivm. Medium: gt-tca, gt-pc5d. Bigger: gt-975, gt-fjvo. Run bd ready.


Digest: mol-deacon-patrol

Patrol 25: routine, all healthy


Research

Investigation workflow.

## Step: investigate
Explore the question. Search code, read docs,
understand context. Take notes.

## Step: document
Write up findings. Include:
- What you learned
- Recommendations
- Open questions
Needs: investigate


Digest: mol-deacon-patrol

Patrol 83: Routine, all healthy


Digest: mol-deacon-patrol

Patrol 6: all healthy


Replace WaitForClaudeReady with gt peek for steady-state agent observation

## Problem

WaitForClaudeReady uses regex to detect Claude's prompt ("> "), which is a ZFC violation - an AI system using pattern matching to detect AI readiness.

## Current State

```go
// Polls looking for "> " at start of line
func WaitForClaudeReady(session string, timeout time.Duration) error {
    for _, line := range lines {
        if strings.HasPrefix(trimmed, "> ") || trimmed == ">" {
            return nil
        }
    }
}
```

Used by:
- Daemon bootstrap (getting Deacon online)
- `gt deacon trigger-pending` (triggering polecats)
- Other agent startup paths

## Architectural Fix

### Bootstrap (ZFC violation acceptable)
During cold town startup, no AI is available. Using regex to get the Deacon online is acceptable - it's the bootstrap exception.

### Steady State (proper ZFC)
Once any agent is running, AI should observe AI:
- **Deacon starting polecats** → Deacon uses `gt peek` to observe them
- **Deacon restarting** → Mayor watches via `gt peek`
- **Mayor restarting** → Deacon watches via `gt peek`

### Implementation

1. Keep `WaitForClaudeReady` for daemon bootstrap only
2. Add `WaitForClaudeReadyAI(session)` that uses `gt peek`
3. Update `gt deacon trigger-pending` to use AI observation
4. Document the bootstrap vs steady-state distinction

## gt peek Integration

`gt peek` should answer: "Is this Claude session ready for input?"
- Can detect ready state
- Can detect error states (crashed, permission denied)
- Robust to prompt format changes


🤝 HANDOFF: Code review mol spawn --attach and mol distill

## Session Summary

Implemented bd-obep: spawn-time bonding with --attach flag.

**Changes in commit 16518223:**
- Added --attach (repeatable) and --attach-type flags to bd mol spawn
- Fixed pre-existing bug in bondProtoMol and bondMolMol that tried to add
  duplicate dependencies (UNIQUE constraint violation)
- Sequential bonds now use blocks type, parallel/conditional use parent-child

## Code Review Requested

Review the following in cmd/bd/mol.go:

### 1. spawn --attach implementation (lines ~254-400)
- Attachment validation and loading
- Variable collection from all attached protos
- Dry-run output for attachments
- Bonding loop after spawning primary molecule

### 2. bondProtoMol fix (lines ~868-898)
- Changed from adding both parent-child + blocks to single dependency
- Sequential uses blocks, parallel/conditional uses parent-child

### 3. bondMolMol fix (lines ~917-934)
- Same pattern as bondProtoMol

### 4. mol distill command (lines ~972+)
- Implemented in previous session (bd-iq19)
- Extracts proto from existing epic
- Supports --var for value→placeholder replacement
- Supports --as for custom proto title

## Review Focus Areas
- Error handling completeness
- Edge cases (empty attachments, missing variables, non-proto attachments)
- Code duplication that could be extracted
- Documentation/comment quality
- Any missing test coverage


POLECAT_STARTED hotel

Issue: bd-yck
Session: gt-beads-hotel


Digest: mol-deacon-patrol

Patrol 17: Routine.


POLECAT_DONE nux

Exit: COMPLETED
Issue: gt-h6eq.1
MR: gt-05cx
Branch: polecat/nux


Digest: mol-deacon-patrol

## Molecule Execution Summary

**Molecule**: mol-deacon-patrol
**Steps**: 9

**Completed**: 9/9

---

### Steps

1. **[closed]** Burn and respawn or loop
   Burn and let daemon respawn, or exit if context high.

Decision point at end of patrol cycle:

If context is LOW:
- Sleep briefly (avoid tight loop)
- Return to inbox-check step

If context is HIGH:
-...

2. **[closed]** Find abandoned work
   Find abandoned work.

Scan for orphaned state:
- Issues marked in_progress with no active polecat
- Polecats that stopped responding mid-work
- Merge queue entries with no polecat owner
- Wisp session...

3. **[closed]** Handle callbacks from agents
   Handle callbacks from agents.

Check the Mayor's inbox for messages from:
- Witnesses reporting polecat status
- Refineries reporting merge results
- Polecats requesting help or escalation
- External ...

4. **[closed]** Execute registered plugins
   Execute registered plugins.

Scan ~/gt/plugins/ for plugin directories. Each plugin has a plugin.md with YAML frontmatter defining its gate (when to run) and instructions (what to do).

See docs/deaco...

5. **[closed]** Check own context limit
   Check own context limit.

The Deacon runs in a Claude session with finite context. Check if approaching the limit:

```bash
gt context --usage
```

If context is high (>80%), prepare for handoff:
- Su...

6. **[closed]** Nudge newly spawned polecats
   Nudge newly spawned polecats that are ready for input.

When polecats are spawned, their Claude session takes 10-20 seconds to initialize. The spawn command returns immediately without waiting. This s...

7. **[closed]** Check Witness and Refinery health
   Check Witness and Refinery health for each rig.

**ZFC Principle**: You (Claude) make the judgment call about what is "stuck" or "unresponsive" - there are no hardcoded thresholds in Go. Read the sign...

8. **[closed]** Clean dead sessions
   Clean dead sessions and orphaned state.

Run `gt doctor -v` to check for issues, then `gt doctor --fix` to clean up.

**⚠ CRITICAL: The Deacon NEVER kills crew workers or polecats!**

The orphan-...

9. **[closed]** Evaluate pending async gates
   Evaluate pending async gates.

Gates are async coordination primitives that block until conditions are met.
The Deacon is responsible for monitoring gates and closing them when ready.

**Timer gates**...


Digest: mol-deacon-patrol

Patrol cycle 201: Mayor restarted (was stalled with 14 unread msgs), closed Formula Molecules convoy (7/7 complete), all agents healthy


Digest: mol-deacon-patrol

Patrol 7: All agents healthy. No incidents.


Digest: mol-deacon-patrol

Patrol 17: Quiet. All healthy.


Digest: mol-deacon-patrol

Patrol cycle 17: All healthy


Chemistry UX: New Beads Commands Needed

## Summary

Overseer and I designed the molecular chemistry UX for Gas Town. Need your help implementing the Beads side.

## New Commands Needed

1. **bd pour <proto>** - Instantiate proto as mol (liquid/persistent)
   - Alias for: bd mol spawn <proto> --pour
   - Creates in permanent .beads/

2. **bd wisp <proto>** - Instantiate proto as wisp (vapor/ephemeral)
   - Alias for: bd mol spawn <proto> (wisp is now default)
   - Creates in .beads-wisp/

3. **bd pin <mol-id> [--for agent]** - Attach mol to agent hook
   - Sets pinned: true and assignee on head bead

4. **bd hook [--agent name]** - Inspect what is on agent hook

## Flag Changes

- Rename --persistent to --pour in bd mol spawn
- Add --pour flag to bd mol bond (force liquid when spawning)

## Digest ID Reservation

When wisp is created, reserve its ID in permanent beads (placeholder).
On squash, replace placeholder with digest. Cross-phase refs stay valid.

## Full Spec

See: gastown/mayor/rig/docs/chemistry-design-changes.md

## Priority

P0 for Christmas launch - gt-3x0z.9 is blocked on this.

## Note

The installed bd v0.33.2 seems outdated - doesnt have --wisp flag that code shows. May need rebuild.


Digest: mol-deacon-patrol

Patrol cycle 7: all clear


DOC: Add gt nudge guidance to mayor template

dispatched_by: mayor

## Problem

Mayor template discourages nudging (line 180: 'NOT your job') but provides no guidance for when Mayor DOES need to kick a stuck refinery/witness.

I (Mayor) reached for `tmux send-keys` which always fails.

## Missing from mayor.md.tmpl

1. **Key Commands → Coordination section**:
```
### Coordination
- `gt nudge <target> "message"` - Send message to agent session
  **ALWAYS use gt nudge, NEVER tmux send-keys** (drops Enter key)
```

2. **Clarify line 180**: Change from 'nudging workers is not your job' to:
```
**NOT your job**: Per-worker cleanup, session killing, routine nudging (Witness handles that)
**Exception**: If refinery/witness is stuck, use `gt nudge refinery "Process MQ"`
```

## Also missing from

- `~/gt/CLAUDE.md` - No nudge guidance at all
- System prompt - No warning about tmux send-keys

## Evidence

The docs exist in reference.md:315-317 and witness.md.tmpl:302 but not in mayor context.


Digest: mol-deacon-patrol

Patrol cycle 7: EXTRAORDINARY - Mayor was stopped, restarted successfully. 3 witnesses healthy. gastown refinery queue stale (14 pending).


Digest: mol-deacon-patrol

Patrol cycle 1: All healthy - gastown (witness/refinery running, 15 MQ), beads (witness/refinery running), wyvern (witness running, refinery stopped/empty). No callbacks, no convoys, no orphans.


POLECAT_STARTED beads/Syncer

Issue: bd-io8c
Session: gt-beads-Syncer


📋 Work Assignment: Work on gt-8tmz.36: Validate expanded step IDs are unique...

Issue: bd-c4wq
Title: Work on gt-8tmz.36: Validate expanded step IDs are unique...
Priority: P2
Type: task

Description:
Work on gt-8tmz.36: Validate expanded step IDs are unique. In internal/formula/, add validation during cooking that checks for duplicate step IDs after expansion. When done: 1) bd close gt-8tmz.36, 2) bd sync, 3) git push, 4) gt mq submit

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Run `gt done` to signal completion (branch stays local)

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 20: All healthy, handoff threshold reached


Digest: mol-deacon-patrol

Patrol 20: thorough check complete, all healthy


Digest: mol-deacon-patrol

Patrol cycle 15: quiet


Digest: mol-deacon-patrol

Patrol 1: All healthy, no callbacks, no orphans


Digest: mol-deacon-patrol

Patrol cycle 16: all clear


Digest: mol-deacon-patrol

Patrol 19: Routine.


Digest: mol-deacon-patrol

Patrol 30: healthy


Digest: mol-deacon-patrol

Patrol 3: routine


Digest: mol-deacon-patrol

Patrol #11: 3 polecats active. All healthy.


Digest: mol-deacon-patrol

Patrol 6: healthy


Digest: mol-deacon-patrol

Patrol 10: All healthy, no inbox


Digest: mol-deacon-patrol

Patrol 1: inbox clear, no gates, all agents healthy


Digest: mol-deacon-patrol

Patrol 20: All healthy. Handoff threshold reached.


POLECAT_STARTED beads/nux

Issue: bd-dtl8
Session: gt-beads-nux


📋 Work Assignment: Phase 2.2: gt prime shows ephemeral molecule context

Issue: gt-3x0z.5
Title: Phase 2.2: gt prime shows ephemeral molecule context
Priority: P1
Type: task

Description:
Update gt prime to detect and display ephemeral molecule state.

## Detection

1. Check for active ephemeral molecule assigned to current identity
2. Parse molecule progress (current step, total steps)
3. Show in prime output

## Output

```
🔧 Polecat furiosa, checking in.

📦 Molecule: mol-polecat-work (eph-abc123)
   Step 3/8: do-work
   Source: gt-rixa
   Started: 10 minutes ago

Run 'bd mol status' for full molecule state.
```

## Workflow
1. Run `gt prime` to load polecat context
2. Run `bd sync --from-main` to get fresh beads
3. Work on your task, commit changes regularly
4. Run `bd close <issue-id>` when done
5. Run `bd sync` to push beads changes
6. Push code: `git push origin HEAD`
7. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol 5: quiet


🤝 HANDOFF: Molecular Chemistry Cleanup filed

## This Session

1. Completed gt-lz13: Updated 4 role templates with bd mol current / bd close --continue
2. Reviewed patrol templates (Deacon, Witness, Refinery) - found major issues
3. Created gt-ingm: Molecular Chemistry Cleanup epic with full inventory

## Key Findings

The OLD model (molecules defined in Go code as structs) conflicts with the CORRECT model:
- Formula (YAML) → cook → Proto (template beads) → pour/wisp → Mol/Wisp

Major issues:
- molecules_*.go files define molecules in Go (45KB of wrong code)
- Protos are empty (mol-witness-patrol has 0 children, mol-refinery-patrol doesn't exist)
- Role templates list steps that should come from beads

## Created Issues

- gt-ingm: Molecular Chemistry Cleanup (6 children with deps)
- bd-8y9t: Remove bd mol spawn - use pour/wisp only (for Dave)

## Next Session

Start gt-ingm.1: Create patrol formula YAML files for:
- mol-deacon-patrol.formula.yaml
- mol-witness-patrol.formula.yaml
- mol-refinery-patrol.formula.yaml

Use molecules_patrol.go as reference for step content, but output as formula YAML.


Digest: mol-deacon-patrol

Patrol 16: nominal


Digest: mol-deacon-patrol

Patrol cycle 2: All witnesses/refineries healthy, no messages, no orphans


Digest: mol-deacon-patrol

Patrol cycle 9: Routine


Digest: mol-deacon-patrol

Patrol 12: healthy


📋 Work Assignment: Audit and standardize JSON output across all commands

Issue: bd-au0.7
Title: Audit and standardize JSON output across all commands
Priority: P1
Type: task

Description:
Ensure consistent JSON format and error handling when --json flag is used.

**Scope:**
1. Verify all commands respect --json flag
2. Standardize success response format
3. Standardize error response format
4. Document JSON schemas

**Commands to audit:**
- Core CRUD: create, update, delete, show, list, search ✓
- Queries: ready, blocked, stale, count, stats, status
- Deps: dep add/remove/tree/cycles
- Labels: label commands
- Comments: comments add/list/delete
- Epics: epic status/close-eligible
- Export/import: already support --json ✓

**Testing:**
- Success cases return valid JSON
- Error cases return valid JSON (not plain text)
- Consistent field naming (snake_case vs camelCase)
- Array vs object wrapping consistency

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Run `gt done` to signal completion (branch stays local)

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol cycle 5: No messages, 2 convoys still open, cleaned 1 orphan session, all agents healthy.


🤝 HANDOFF: gt-3x0z.9 Done, Binary Freshness Issues

## Session Summary

### Completed
- **gt-3x0z.9**: Deacon wisp-based patrol - DONE (commit ae513a5)
  - Removed checkDeaconAttachment from daemon
  - Updated deacon.md.tmpl for wisp-based patrol

- **gt-a07f**: Closed - Dave finished chemistry commands (bd pour, bd wisp, bd hook)

- **bd-d9mu**: Created cross-rig external dependency feature request in Beads

- **gt-0a90**: Created gt hook command issue

- **gt-q6lg**: Created mol-crew-session issue for crew startup/shutdown protocols

### Issues Found
1. **Mail address mismatch**: beads/dave vs beads/crew/dave
   - Fix exists (commit ebbe886) but wasn't deployed
   - Root cause: fix-gt script didn't copy to ~/go/bin/gt
   - Fixed fix-gt to: rm before cp, sign after copy

2. **gt binary freshness**: crew clones have stale binaries
   - Causes hangs, mail failures, etc.
   - gt-q6lg filed for mol-crew-session startup protocol

### Binary Sync Status
Updated: ~/go/bin/gt, ~/gt/gt, crew/joe/gt, crew/max/gt
Daemon restarted with new binary

### Remaining P1
All done! Only P2 items remain:
- gt-3x0z.10: Witness/Refinery patrol molecules
- gt-3x0z.11: Document ephemeral architecture
- gt-0a90: gt hook command
- gt-q6lg: mol-crew-session

### Start Here
```
bd show gt-3x0z.10  # Next patrol molecule
bd ready            # Find unblocked work
```


Digest: mol-deacon-patrol

Patrol 2: All agents healthy. Gastown (13 pending MQ), beads (8 pending MQ). No callbacks, no orphans.


Digest: mol-deacon-patrol

Patrol 19: Quick cycle.


Digest: mol-deacon-patrol

Patrol 15: Routine


Digest: mol-deacon-patrol

Patrol 6: All healthy.


🤝 HANDOFF: Code review wisp simplification

## Context

Completed wisp simplification integration (gt-fgms + bd-bkul).

## What Was Done

1. Pulled Dave's bd-bkul work from beads repo
2. Found bug: sync_export.go wasn't filtering wisps (autoflush.go was)
3. Fixed by adding wisp filter to sync_export.go
4. Committed and pushed: 9f8b3478

## Code Review Needed

Review these files in ~/gt/beads/crew/dave for correctness:

1. **cmd/bd/sync_export.go** - My fix (wisp filtering)
2. **cmd/bd/mol_squash.go** - Dave's changes (removed cross-store logic)
3. **cmd/bd/mol_burn.go** - Dave's changes (rewritten for main store)
4. **cmd/bd/mol_bond.go** - Dave's changes (--wisp/--pour flags)
5. **cmd/bd/autoflush.go** - Existing wisp filter (reference)

## Key Review Points

- Verify all JSONL export paths filter wisps
- Check mol squash handles wisp children correctly
- Check mol burn rejects non-wisp molecules
- Verify bond --wisp creates Wisp=true in main store
- Look for any other export paths that might leak wisps

## Test Commands

gt mail send gastown/max --wisp -s 'Test' -m 'test'
bd sync
grep wisp ~/gt/.beads/issues.jsonl  # Should find nothing with wisp:true


Digest: mol-deacon-patrol

Patrol 24: All healthy


Digest: mol-deacon-patrol

Patrol 15: All healthy.


Digest: mol-deacon-patrol

Patrol cycle 20: All healthy. 3 rigs operational. No incidents.


Digest: mol-deacon-patrol

Patrol 7: quiet


Simple kill protection: SafeToKill() check + no auto-kill

## Problem
Workers keep getting killed with uncommitted work.

## Simple Solution

### 1. SafeToKill() function
```go
func SafeToKill(worktree string) (bool, string) {
    if hasUncommittedWork(worktree) {
        return false, "uncommitted changes"
    }
    if hasUnpushedCommits(worktree) {
        return false, "unpushed commits"
    }
    return true, "clean"
}
```

### 2. Add check to gt polecat nuke
Refuse to kill if SafeToKill() returns false, unless --force flag.

### 3. Remove auto-kill from Deacon
Deacon should NEVER kill sessions. Report-only via gt doctor.

### 4. gt doctor --fix should not touch sessions
Diagnosis and reporting only. Human decides.

## Acceptance Criteria
- `gt polecat nuke` checks for dirty state before killing
- Deacon has no kill authority
- `gt doctor` never kills sessions

Already implemented in v0.2.3: polecat nuke has multi-layer safety checks, Deacon has no kill authority (dry-run only + death warrants), doctor never kills sessions


Digest: mol-deacon-patrol

Patrol 5: all clear


POLECAT_STARTED beads/rictus

Issue: bd-au0.7
Session: gt-beads-rictus


Digest: mol-deacon-patrol

Patrol 19: all nominal


📋 Work Assignment: Refinery patrol: Add banners and wisp-based execution

Issue: gt-qz2l
Title: Refinery patrol: Add banners and wisp-based execution
Priority: P1
Type: task

Description:
Bring Refinery patrol up to Deacon's level of sophistication:

## Current state
- mol-refinery-patrol exists (needs verification)
- Basic merge queue processing

## Needed
1. **Banners** - Print step banners like Deacon does:
   ```
   ═══════════════════════════════════════════════════════════════
     ⚗ QUEUE-CHECK
     Processing merge queue entries
   ═══════════════════════════════════════════════════════════════
   ```

2. **Wisp-based execution** - Spawn patrol as wisp, squash when complete
3. **Handoff bead attachment** - Refinery needs its own handoff bead with attached_molecule
4. **Loop-or-exit step** - Context-aware cycling like Deacon
5. **Patrol summary banner** at end of each cycle

## Reference
See Deacon patrol implementation in ~/gt/deacon/CLAUDE.md

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol cycle 7: All quiet


Digest: mol-deacon-patrol

Patrol cycle 6: All agents healthy


Digest: mol-deacon-patrol

Patrol cycle 12: All healthy


Digest: mol-deacon-patrol

Patrol #22: beads/crew/emma active (1h+). All healthy.


Digest: mol-deacon-patrol

Patrol 18: all clear


Digest: mol-deacon-patrol

Patrol 16: All healthy.


Digest: mol-deacon-patrol

Patrol 64: All healthy, 3 convoys, no incidents.


📋 Work Assignment: Update templates with molecule navigation workflow

Issue: gt-lz13
Title: Update templates with molecule navigation workflow
Priority: P1
Type: task

Description:
Update all agent templates to use new molecule navigation commands.

## Commands to integrate
- bd mol current: orientation after startup/handoff (bd-sal9)
- bd close --continue: seamless step transitions (bd-ieyy)

## Templates to update

### prompts/roles/polecat.md
- Add bd mol current to 'Finding Your Work' section
- Replace manual 3-command dance with bd close --continue
- Update 'Working Through Steps' section

### prompts/roles/crew.md
- Add molecule navigation to workflow section
- Show bd mol current for session startup

### prompts/roles/refinery.md
- Update patrol step transitions to use --continue

### prompts/roles/witness.md
- Update patrol step transitions to use --continue

### prompts/roles/deacon.md
- Update patrol step transitions to use --continue

## Key message
The Propulsion Principle: close a step, immediately get handed the next.
No friction, no forgetting, no 3-command dance.

## Blocked by (Beads features)
- bd-sal9: bd mol current
- bd-ieyy: bd close --continue

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

P16: clear


Digest: mol-deacon-patrol

Patrol cycle 6: All healthy.


Digest: mol-deacon-patrol

Patrol 13: Clean


Digest: mol-deacon-patrol

Patrol cycle 8 complete: all clear.


Deacon Patrol

Mayor's daemon patrol loop.

The Deacon is the Mayor's background process that runs continuously,
handling callbacks, monitoring rig health, and performing cleanup.
Each patrol cycle runs these steps in sequence, then loops or exits.

## Step: inbox-check
Handle callbacks from agents.

Check the Mayor's inbox for messages from:
- Witnesses reporting polecat status
- Refineries reporting merge results
- Polecats requesting help or escalation
- External triggers (webhooks, timers)

Process each message:
```bash
gt mail inbox
# For each message:
gt mail read <id>
# Handle based on message type
```

Callbacks may spawn new polecats, update issue state, or trigger other actions.

## Step: health-scan
Ping Witnesses and Refineries.

For each rig, verify:
- Witness is responsive
- Refinery is processing queue
- No stalled operations

```bash
gt status --health
# Check each rig
for rig in $(gt rigs); do
    gt rig status $rig
done
```

Report any issues found. Restart unresponsive components if needed.
Needs: inbox-check

## Step: plugin-run
Execute registered plugins.

Run any plugins registered with the Deacon:
- Custom health checks
- Integration hooks (Slack, GitHub, etc.)
- Metrics collection
- External system sync

Plugins are defined in the Mayor's config and run on each patrol cycle.
Skip this step if no plugins are registered.
Needs: health-scan

## Step: orphan-check
Find abandoned work.

Scan for orphaned state:
- Issues marked in_progress with no active polecat
- Polecats that stopped responding mid-work
- Merge queue entries with no polecat owner
- Wisp sessions that outlived their spawner

```bash
bd list --status=in_progress
gt polecats --all --orphan
```

For each orphan:
- Check if polecat session still exists
- If not, mark issue for reassignment or retry
- File incident beads if data loss occurred
Needs: health-scan

## Step: session-gc
Clean dead sessions.

Garbage collect terminated sessions:
- Remove stale polecat directories
- Clean up wisp session artifacts
- Prune old logs and temp files
- Archive completed molecule state

```bash
gt gc --sessions
gt gc --wisps --age=1h
```

Preserve audit trail. Only clean sessions confirmed dead.
Needs: orphan-check

## Step: context-check
Check own context limit.

The Deacon runs in a Claude session with finite context.
Check if approaching the limit:

```bash
gt context --usage
```

If context is high (>80%), prepare for handoff:
- Summarize current state
- Note any pending work
- Write handoff to molecule state

This enables the Deacon to burn and respawn cleanly.
Needs: session-gc

## Step: loop-or-exit
Burn and let daemon respawn, or exit if context high.

Decision point at end of patrol cycle:

If context is LOW:
- Sleep briefly (avoid tight loop)
- Return to inbox-check step

If context is HIGH:
- Write state to persistent storage
- Exit cleanly
- Let the daemon orchestrator respawn a fresh Deacon

The daemon ensures Deacon is always running:
```bash
# Daemon respawns on exit
gt daemon status
```

This enables infinite patrol duration via context-aware respawning.
Needs: context-check


📋 Work Assignment: Add date and priority filters to bd search

Issue: bd-au0.5
Title: Add date and priority filters to bd search
Priority: P1
Type: task

Description:
Add date and priority filters to bd search for parity with bd list.

## Current State
bd search supports: --status, --type, --assignee, --label, --limit
bd list supports: all of the above PLUS date ranges and priority filters

## Filters to Add

### Priority Filters
```bash
bd search "query" --priority 1           # Exact priority
bd search "query" --priority-min 0       # P0 and above (higher priority)
bd search "query" --priority-max 2       # P2 and below (lower priority)
```

### Date Filters
```bash
bd search "query" --created-after 2025-01-01
bd search "query" --created-before 2025-12-31
bd search "query" --updated-after 2025-01-01
bd search "query" --closed-after 2025-01-01
```

### Content Filters
```bash
bd search "query" --desc-contains "bug"
bd search "query" --notes-contains "todo"
bd search "query" --empty-description    # Issues with no description
bd search "query" --no-assignee          # Unassigned issues
bd search "query" --no-labels            # Issues without labels
```

## Files to Modify

### 1. cmd/bd/search.go
Add flag definitions in init():
```go
searchCmd.Flags().IntP("priority", "p", -1, "Filter by exact priority (0-4)")
searchCmd.Flags().Int("priority-min", -1, "Filter by minimum priority")
searchCmd.Flags().Int("priority-max", -1, "Filter by maximum priority")
searchCmd.Flags().String("created-after", "", "Filter by creation date (YYYY-MM-DD)")
searchCmd.Flags().String("created-before", "", "Filter by creation date")
searchCmd.Flags().String("updated-after", "", "Filter by update date")
searchCmd.Flags().String("updated-before", "", "Filter by update date")
searchCmd.Flags().String("closed-after", "", "Filter by close date")
searchCmd.Flags().String("closed-before", "", "Filter by close date")
searchCmd.Flags().String("desc-contains", "", "Filter by description content")
searchCmd.Flags().String("notes-contains", "", "Filter by notes content")
searchCmd.Flags().Bool("empty-description", false, "Filter issues with empty description")
searchCmd.Flags().Bool("no-assignee", false, "Filter unassigned issues")
searchCmd.Flags().Bool("no-labels", false, "Filter issues without labels")
```

### 2. internal/rpc/protocol.go
Update SearchArgs struct:
```go
type SearchArgs struct {
    Query             string
    Filter            types.IssueFilter
    // Already has most fields via IssueFilter
}
```

Note: types.IssueFilter already has these fields - just need to wire them up!

### 3. cmd/bd/search.go Run function
Parse flags and populate filter:
```go
if priority, _ := cmd.Flags().GetInt("priority"); priority >= 0 {
    filter.Priority = &priority
}
if createdAfter, _ := cmd.Flags().GetString("created-after"); createdAfter != "" {
    t, err := time.Parse("2006-01-02", createdAfter)
    if err != nil {
        FatalError("invalid date format for --created-after: %v", err)
    }
    filter.CreatedAfter = &t
}
// ... similar for other flags
```

## Implementation Steps

1. **Check types.IssueFilter** - verify all needed fields exist
2. **Add flags to search.go** init()
3. **Parse flags** in Run function
4. **Pass to SearchIssues** via filter
5. **Test all combinations**

## Testing
```bash
# Create test issues
bd create "Test P1" -p 1
bd create "Test P2" -p 2 --description "Has description"

# Test filters
bd search "" --priority 1
bd search "" --priority-min 0 --priority-max 1
bd search "" --empty-description
bd search "" --desc-contains "description"
```

## Success Criteria
- All filters work in both direct and daemon mode
- Date parsing handles YYYY-MM-DD format
- --json output includes filtered results
- Help text documents all new flags

## Workflow
1. Run `gt prime` to load polecat context
2. Work on your task, commit changes regularly
3. Run `bd close <issue-id>` when done
4. Run `bd sync` to push beads changes
5. Push code: `git push origin HEAD`
6. Run `gt done` to signal completion

## Handoff Protocol
Before signaling done, ensure:
- Git status is clean (no uncommitted changes)
- Issue is closed with `bd close`
- Beads are synced with `bd sync`
- Code is pushed to origin

The `gt done` command verifies these and signals the Witness.


Digest: mol-deacon-patrol

Patrol cycle 1: All healthy. 3 rigs running. No callbacks, no convoys completed, no orphans.